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
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
//! # Vault Registry Module
//! Based on the [specification](https://spec.interlay.io/spec/vault-registry.html).

// #![deny(warnings)]
#![cfg_attr(test, feature(proc_macro_hygiene))]
#![cfg_attr(not(feature = "std"), no_std)]

mod ext;
pub mod types;

#[cfg(any(feature = "runtime-benchmarks", test))]
pub mod benchmarking;

mod default_weights;

mod pool_manager;
pub use pool_manager::PoolManager;

pub use default_weights::WeightInfo;

#[cfg(test)]
mod tests;

#[cfg(test)]
mod mock;

#[cfg(test)]
extern crate mocktopus;

#[cfg(test)]
use mocktopus::macros::mockable;
use primitives::VaultCurrencyPair;

use crate::types::{
    BalanceOf, BtcAddress, CurrencyId, DefaultSystemVault, RichSystemVault, RichVault, UnsignedFixedPoint, Version,
};

use crate::types::DefaultVaultCurrencyPair;
#[doc(inline)]
pub use crate::types::{
    BtcPublicKey, CurrencySource, DefaultVault, DefaultVaultId, SystemVault, Vault, VaultId, VaultStatus,
};
pub use currency::Amount;
use currency::Rounding;
use frame_support::{
    dispatch::{DispatchError, DispatchResult},
    ensure,
    traits::Get,
    transactional, PalletId,
};
use frame_system::{
    ensure_signed,
    offchain::{SendTransactionTypes, SubmitTransaction},
};
use oracle::OracleKey;
use sp_core::{H256, U256};
use sp_runtime::{
    traits::*,
    transaction_validity::{InvalidTransaction, TransactionSource, TransactionValidity, ValidTransaction},
    ArithmeticError, FixedPointNumber,
};
use sp_std::{convert::TryInto, vec::Vec};
use traits::NominationApi;

// value taken from https://github.com/substrate-developer-hub/recipes/blob/master/pallets/ocw-demo/src/lib.rs
pub const UNSIGNED_TXS_PRIORITY: u64 = 100;

pub use pallet::*;

#[frame_support::pallet]
pub mod pallet {
    use crate::types::DefaultVaultCurrencyPair;

    use super::*;
    use frame_support::pallet_prelude::*;
    use frame_system::pallet_prelude::*;

    #[pallet::pallet]
    pub struct Pallet<T>(_);

    #[pallet::config]
    pub trait Config:
        frame_system::Config
        + SendTransactionTypes<Call<Self>>
        + oracle::Config
        + security::Config
        + currency::Config
        + fee::Config
    {
        /// The vault module id, used for deriving its sovereign account ID.
        #[pallet::constant] // put the constant in metadata
        type PalletId: Get<PalletId>;

        /// The overarching event type.
        type RuntimeEvent: From<Event<Self>>
            + Into<<Self as frame_system::Config>::RuntimeEvent>
            + IsType<<Self as frame_system::Config>::RuntimeEvent>;

        /// Weight information for the extrinsics in this module.
        type WeightInfo: WeightInfo;

        /// Currency used for griefing collateral, e.g. DOT.
        #[pallet::constant]
        type GetGriefingCollateralCurrencyId: Get<CurrencyId<Self>>;
    }

    #[pallet::hooks]
    impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
        fn offchain_worker(n: BlockNumberFor<T>) {
            log::info!("Off-chain worker started on block {:?}", n);
            Self::_offchain_worker();
        }

        fn on_runtime_upgrade() -> frame_support::weights::Weight {
            crate::types::v1::migrate_v1_to_v6::<T>()
        }
    }

    #[pallet::validate_unsigned]
    impl<T: Config> frame_support::unsigned::ValidateUnsigned for Pallet<T> {
        type Call = Call<T>;

        fn validate_unsigned(source: TransactionSource, call: &Self::Call) -> TransactionValidity {
            match source {
                TransactionSource::External => {
                    // receiving unsigned transaction from network - disallow
                    return InvalidTransaction::Call.into();
                }
                TransactionSource::Local => {}   // produced by off-chain worker
                TransactionSource::InBlock => {} // some other node included it in a block
            };

            let valid_tx = |provide| {
                ValidTransaction::with_tag_prefix("vault-registry")
                    .priority(UNSIGNED_TXS_PRIORITY)
                    .and_provides([&provide])
                    .longevity(3)
                    .propagate(false)
                    .build()
            };

            match call {
                Call::report_undercollateralized_vault { .. } => valid_tx(b"report_undercollateralized_vault".to_vec()),
                _ => InvalidTransaction::Call.into(),
            }
        }
    }

    #[pallet::call]
    impl<T: Config> Pallet<T> {
        /// Initiates the registration procedure for a new Vault.
        /// The Vault locks up collateral, which is to be used in the issuing process.
        ///
        ///
        /// # Errors
        /// * `InsufficientVaultCollateralAmount` - if the collateral is below the minimum threshold
        /// * `VaultAlreadyRegistered` - if a vault is already registered for the origin account
        /// * `InsufficientCollateralAvailable` - if the vault does not own enough collateral
        #[pallet::call_index(0)]
        #[pallet::weight(<T as Config>::WeightInfo::register_vault())]
        #[transactional]
        pub fn register_vault(
            origin: OriginFor<T>,
            currency_pair: DefaultVaultCurrencyPair<T>,
            #[pallet::compact] collateral: BalanceOf<T>,
        ) -> DispatchResultWithPostInfo {
            let account_id = ensure_signed(origin)?;
            let vault_id = VaultId::new(account_id, currency_pair.collateral, currency_pair.wrapped);
            Self::_register_vault(vault_id, collateral)?;
            Ok(().into())
        }

        /// Registers a new Bitcoin address for the vault.
        ///
        /// # Arguments
        /// * `public_key` - the BTC public key of the vault to update
        #[pallet::call_index(1)]
        #[pallet::weight(<T as Config>::WeightInfo::register_public_key())]
        #[transactional]
        pub fn register_public_key(origin: OriginFor<T>, public_key: BtcPublicKey) -> DispatchResultWithPostInfo {
            let account_id = ensure_signed(origin)?;

            ensure!(
                !VaultBitcoinPublicKey::<T>::get(&account_id).is_some(),
                Error::<T>::PublicKeyAlreadyRegistered
            );

            VaultBitcoinPublicKey::<T>::insert(&account_id, &public_key);

            Self::deposit_event(Event::<T>::UpdatePublicKey { account_id, public_key });
            Ok(().into())
        }

        /// Configures whether or not the vault accepts new issues.
        ///
        /// # Arguments
        ///
        /// * `origin` - sender of the transaction (i.e. the vault)
        /// * `accept_new_issues` - true indicates that the vault accepts new issues
        ///
        /// # Weight: `O(1)`
        #[pallet::call_index(2)]
        #[pallet::weight(<T as Config>::WeightInfo::accept_new_issues())]
        #[transactional]
        pub fn accept_new_issues(
            origin: OriginFor<T>,
            currency_pair: DefaultVaultCurrencyPair<T>,
            accept_new_issues: bool,
        ) -> DispatchResultWithPostInfo {
            let account_id = ensure_signed(origin)?;
            let vault_id = VaultId::new(account_id, currency_pair.collateral, currency_pair.wrapped);
            let mut vault = Self::get_active_rich_vault_from_id(&vault_id)?;
            vault.set_accept_new_issues(accept_new_issues)?;
            PoolManager::<T>::on_vault_settings_change(&vault_id)?;
            Self::deposit_event(Event::<T>::SetAcceptNewIssues {
                vault_id,
                accept_new_issues,
            });
            Ok(().into())
        }

        /// Configures a custom, higher secure collateral threshold for the vault.
        ///
        /// # Arguments
        ///
        /// * `origin` - sender of the transaction (i.e. the vault)
        /// * `custom_threshold` - either the threshold, or None to use the systemwide default
        ///
        /// # Weight: `O(1)`
        #[pallet::call_index(3)]
        #[pallet::weight(<T as Config>::WeightInfo::set_custom_secure_threshold())]
        #[transactional]
        pub fn set_custom_secure_threshold(
            origin: OriginFor<T>,
            currency_pair: DefaultVaultCurrencyPair<T>,
            custom_threshold: Option<UnsignedFixedPoint<T>>,
        ) -> DispatchResultWithPostInfo {
            let account_id = ensure_signed(origin)?;
            let vault_id = VaultId::new(account_id, currency_pair.collateral, currency_pair.wrapped);
            Self::try_set_vault_custom_secure_threshold(&vault_id, custom_threshold)?;
            PoolManager::<T>::on_vault_settings_change(&vault_id)?;
            Self::deposit_event(Event::<T>::SetCustomSecureThreshold {
                vault_id,
                custom_threshold,
            });
            Ok(().into())
        }

        #[pallet::call_index(4)]
        #[pallet::weight(<T as Config>::WeightInfo::report_undercollateralized_vault())]
        #[transactional]
        pub fn report_undercollateralized_vault(
            _origin: OriginFor<T>,
            vault_id: DefaultVaultId<T>,
        ) -> DispatchResultWithPostInfo {
            log::info!("Vault reported");
            let vault = Self::get_vault_from_id(&vault_id)?;
            let liquidation_threshold =
                Self::liquidation_collateral_threshold(&vault_id.currencies).ok_or(Error::<T>::ThresholdNotSet)?;
            if Self::is_vault_below_liquidation_threshold(&vault, liquidation_threshold)? {
                Self::liquidate_vault(&vault_id)?;
                Ok(().into())
            } else {
                log::info!("Not liquidating; vault not below liquidation threshold");
                Err(Error::<T>::VaultNotBelowLiquidationThreshold.into())
            }
        }

        /// Changes the minimum amount of collateral required for registration
        /// (only executable by the Root account)
        ///
        /// # Arguments
        /// * `currency_id` - the collateral's currency id
        /// * `minimum` - the new minimum collateral
        #[pallet::call_index(5)]
        #[pallet::weight(<T as Config>::WeightInfo::set_minimum_collateral())]
        #[transactional]
        pub fn set_minimum_collateral(
            origin: OriginFor<T>,
            currency_id: CurrencyId<T>,
            minimum: BalanceOf<T>,
        ) -> DispatchResult {
            ensure_root(origin)?;
            MinimumCollateralVault::<T>::insert(currency_id, minimum);
            Ok(())
        }

        /// Changes the collateral ceiling for a currency (only executable by the Root account)
        ///
        /// # Arguments
        /// * `currency_pair` - the currency pair to change
        /// * `ceiling` - the new collateral ceiling
        #[pallet::call_index(6)]
        #[pallet::weight(<T as Config>::WeightInfo::set_system_collateral_ceiling())]
        #[transactional]
        pub fn set_system_collateral_ceiling(
            origin: OriginFor<T>,
            currency_pair: DefaultVaultCurrencyPair<T>,
            ceiling: BalanceOf<T>,
        ) -> DispatchResult {
            ensure_root(origin)?;
            Self::_set_system_collateral_ceiling(currency_pair, ceiling);
            Ok(())
        }

        /// Changes the secure threshold for a currency (only executable by the Root account)
        ///
        /// # Arguments
        /// * `currency_pair` - the currency pair to change
        /// * `threshold` - the new secure threshold
        #[pallet::call_index(7)]
        #[pallet::weight(<T as Config>::WeightInfo::set_secure_collateral_threshold())]
        #[transactional]
        pub fn set_secure_collateral_threshold(
            origin: OriginFor<T>,
            currency_pair: DefaultVaultCurrencyPair<T>,
            threshold: UnsignedFixedPoint<T>,
        ) -> DispatchResult {
            ensure_root(origin)?;
            Self::_set_secure_collateral_threshold(currency_pair.clone(), threshold.clone());
            Self::deposit_event(Event::<T>::SetSecureCollateralThreshold {
                currency_pair,
                threshold,
            });
            Ok(())
        }

        /// Changes the collateral premium redeem threshold for a currency (only executable by the Root account)
        ///
        /// # Arguments
        /// * `currency_pair` - the currency pair to change
        /// * `ceiling` - the new collateral ceiling
        #[pallet::call_index(8)]
        #[pallet::weight(<T as Config>::WeightInfo::set_premium_redeem_threshold())]
        #[transactional]
        pub fn set_premium_redeem_threshold(
            origin: OriginFor<T>,
            currency_pair: DefaultVaultCurrencyPair<T>,
            threshold: UnsignedFixedPoint<T>,
        ) -> DispatchResult {
            ensure_root(origin)?;
            Self::_set_premium_redeem_threshold(currency_pair.clone(), threshold.clone());
            Self::deposit_event(Event::<T>::SetPremiumRedeemThreshold {
                currency_pair,
                threshold,
            });
            Ok(())
        }

        /// Changes the collateral liquidation threshold for a currency (only executable by the Root account)
        ///
        /// # Arguments
        /// * `currency_pair` - the currency pair to change
        /// * `ceiling` - the new collateral ceiling
        #[pallet::call_index(9)]
        #[pallet::weight(<T as Config>::WeightInfo::set_liquidation_collateral_threshold())]
        #[transactional]
        pub fn set_liquidation_collateral_threshold(
            origin: OriginFor<T>,
            currency_pair: DefaultVaultCurrencyPair<T>,
            threshold: UnsignedFixedPoint<T>,
        ) -> DispatchResult {
            ensure_root(origin)?;
            Self::_set_liquidation_collateral_threshold(currency_pair.clone(), threshold.clone());
            Self::deposit_event(Event::<T>::SetLiquidationCollateralThreshold {
                currency_pair,
                threshold,
            });
            Ok(())
        }

        /// Recover vault ID from a liquidated status.
        ///
        /// # Arguments
        /// * `currency_pair` - the currency pair to change
        #[pallet::call_index(10)]
        #[pallet::weight(<T as Config>::WeightInfo::recover_vault_id())]
        #[transactional]
        pub fn recover_vault_id(origin: OriginFor<T>, currency_pair: DefaultVaultCurrencyPair<T>) -> DispatchResult {
            let account_id = ensure_signed(origin)?;
            let vault_id = VaultId::new(account_id, currency_pair.collateral, currency_pair.wrapped);
            ensure!(Self::is_vault_liquidated(&vault_id)?, Error::<T>::VaultNotRecoverable);

            let mut vault = Self::get_rich_vault_from_id(&vault_id.clone())?;
            ensure!(vault.to_be_redeemed_tokens().is_zero(), Error::<T>::VaultNotRecoverable);

            // Vault accepts new issues by default
            vault.set_accept_new_issues(true)?;

            Ok(())
        }
    }

    #[pallet::event]
    #[pallet::generate_deposit(pub(super) fn deposit_event)]
    pub enum Event<T: Config> {
        RegisterVault {
            vault_id: DefaultVaultId<T>,
            collateral: BalanceOf<T>,
        },
        IncreaseLockedCollateral {
            currency_pair: DefaultVaultCurrencyPair<T>,
            delta: BalanceOf<T>,
            total: BalanceOf<T>,
        },
        DecreaseLockedCollateral {
            currency_pair: DefaultVaultCurrencyPair<T>,
            delta: BalanceOf<T>,
            total: BalanceOf<T>,
        },
        UpdatePublicKey {
            account_id: T::AccountId,
            public_key: BtcPublicKey,
        },
        RegisterAddress {
            vault_id: DefaultVaultId<T>,
            address: BtcAddress,
        },
        IncreaseToBeIssuedTokens {
            vault_id: DefaultVaultId<T>,
            increase: BalanceOf<T>,
        },
        DecreaseToBeIssuedTokens {
            vault_id: DefaultVaultId<T>,
            decrease: BalanceOf<T>,
        },
        IssueTokens {
            vault_id: DefaultVaultId<T>,
            increase: BalanceOf<T>,
        },
        IncreaseToBeRedeemedTokens {
            vault_id: DefaultVaultId<T>,
            increase: BalanceOf<T>,
        },
        DecreaseToBeRedeemedTokens {
            vault_id: DefaultVaultId<T>,
            decrease: BalanceOf<T>,
        },
        IncreaseToBeReplacedTokens {
            vault_id: DefaultVaultId<T>,
            increase: BalanceOf<T>,
        },
        DecreaseToBeReplacedTokens {
            vault_id: DefaultVaultId<T>,
            decrease: BalanceOf<T>,
        },
        DecreaseTokens {
            vault_id: DefaultVaultId<T>,
            user_id: T::AccountId,
            decrease: BalanceOf<T>,
        },
        RedeemTokens {
            vault_id: DefaultVaultId<T>,
            redeemed_amount: BalanceOf<T>,
        },
        RedeemTokensPremium {
            vault_id: DefaultVaultId<T>,
            redeemed_amount: BalanceOf<T>,
            collateral: BalanceOf<T>,
            user_id: T::AccountId,
        },
        RedeemTokensLiquidatedVault {
            vault_id: DefaultVaultId<T>,
            tokens: BalanceOf<T>,
            collateral: BalanceOf<T>,
        },
        RedeemTokensLiquidation {
            redeemer_id: T::AccountId,
            burned_tokens: BalanceOf<T>,
            transferred_collateral: BalanceOf<T>,
        },
        ReplaceTokens {
            old_vault_id: DefaultVaultId<T>,
            new_vault_id: DefaultVaultId<T>,
            amount: BalanceOf<T>,
            additional_collateral: BalanceOf<T>,
        },
        LiquidateVault {
            vault_id: DefaultVaultId<T>,
            issued_tokens: BalanceOf<T>,
            to_be_issued_tokens: BalanceOf<T>,
            to_be_redeemed_tokens: BalanceOf<T>,
            to_be_replaced_tokens: BalanceOf<T>,
            backing_collateral: BalanceOf<T>,
            status: VaultStatus,
            replace_collateral: BalanceOf<T>,
        },
        BanVault {
            vault_id: DefaultVaultId<T>,
            banned_until: BlockNumberFor<T>,
        },
        SetAcceptNewIssues {
            vault_id: DefaultVaultId<T>,
            accept_new_issues: bool,
        },
        SetSecureCollateralThreshold {
            currency_pair: DefaultVaultCurrencyPair<T>,
            threshold: UnsignedFixedPoint<T>,
        },
        SetPremiumRedeemThreshold {
            currency_pair: DefaultVaultCurrencyPair<T>,
            threshold: UnsignedFixedPoint<T>,
        },
        SetLiquidationCollateralThreshold {
            currency_pair: DefaultVaultCurrencyPair<T>,
            threshold: UnsignedFixedPoint<T>,
        },
        SetCustomSecureThreshold {
            vault_id: DefaultVaultId<T>,
            custom_threshold: Option<UnsignedFixedPoint<T>>,
        },
    }

    #[pallet::error]
    pub enum Error<T> {
        /// Not enough free collateral available.
        InsufficientCollateral,
        /// The amount of tokens to be issued is higher than the issuable amount by the vault
        ExceedingVaultLimit,
        /// The requested amount of tokens exceeds the amount available to this vault.
        InsufficientTokensCommitted,
        /// Action not allowed on banned vault.
        VaultBanned,
        /// The provided collateral was insufficient - it must be above ``MinimumCollateralVault``.
        InsufficientVaultCollateralAmount,
        /// Returned if a vault tries to register while already being registered
        VaultAlreadyRegistered,
        /// The specified vault does not exist.
        VaultNotFound,
        /// Attempted to liquidate a vault that is not undercollateralized.
        VaultNotBelowLiquidationThreshold,
        /// Deposit address could not be generated with the given public key.
        InvalidPublicKey,
        /// The collateral ceiling would be exceeded for the vault's currency.
        CurrencyCeilingExceeded,
        /// Vault is no longer usable as it was liquidated due to undercollateralization.
        VaultLiquidated,
        /// Vault must be liquidated.
        VaultNotRecoverable,
        /// No bitcoin public key is registered for the vault.
        NoBitcoinPublicKey,
        /// A bitcoin public key was already registered for this account.
        PublicKeyAlreadyRegistered,

        // Errors used exclusively in RPC functions
        /// Collateralization is infinite if no tokens are issued
        NoTokensIssued,
        NoVaultWithSufficientCollateral,
        NoVaultWithSufficientTokens,
        NoVaultUnderThePremiumRedeemThreshold,

        /// Failed attempt to modify vault's collateral because it was in the wrong currency
        InvalidCurrency,

        /// Threshold was not found for the given currency
        ThresholdNotSet,
        /// Ceiling was not found for the given currency
        CeilingNotSet,
        /// Vault attempted to set secure threshold below the global secure threshold
        ThresholdNotAboveGlobalThreshold,

        /// Unable to convert value
        TryIntoIntError,

        /// Vault is not accepting new issue requests.
        VaultNotAcceptingIssueRequests,

        // Minimum collateral was not found for the given currency
        MinimumCollateralNotSet,
    }

    /// The minimum collateral (e.g. DOT/KSM) a Vault needs to provide to register.
    #[pallet::storage]
    #[pallet::getter(fn minimum_collateral_vault)]
    pub(super) type MinimumCollateralVault<T: Config> =
        StorageMap<_, Blake2_128Concat, CurrencyId<T>, BalanceOf<T>, ValueQuery>;

    /// If a Vault fails to execute a correct redeem or replace, it is temporarily banned
    /// from further issue, redeem or replace requests. This value configures the duration
    /// of this ban (in number of blocks) .
    #[pallet::storage]
    #[pallet::getter(fn punishment_delay)]
    pub(super) type PunishmentDelay<T: Config> = StorageValue<_, BlockNumberFor<T>, ValueQuery>;

    /// Determines the over-collateralization rate for collateral locked by Vaults, necessary for
    /// wrapped tokens. This threshold should be greater than the LiquidationCollateralThreshold.
    #[pallet::storage]
    pub(super) type SystemCollateralCeiling<T: Config> =
        StorageMap<_, Blake2_128Concat, DefaultVaultCurrencyPair<T>, BalanceOf<T>>;

    /// Determines the over-collateralization rate for collateral locked by Vaults, necessary for
    /// wrapped tokens. This threshold should be greater than the LiquidationCollateralThreshold.
    #[pallet::storage]
    #[pallet::getter(fn secure_collateral_threshold)]
    pub(super) type SecureCollateralThreshold<T: Config> =
        StorageMap<_, Blake2_128Concat, DefaultVaultCurrencyPair<T>, UnsignedFixedPoint<T>>;

    /// Determines the rate for the collateral rate of Vaults, at which users receive a premium,
    /// allocated from the Vault's collateral, when performing a redeem with this Vault. This
    /// threshold should be greater than the LiquidationCollateralThreshold.
    #[pallet::storage]
    #[pallet::getter(fn premium_redeem_threshold)]
    pub(super) type PremiumRedeemThreshold<T: Config> =
        StorageMap<_, Blake2_128Concat, DefaultVaultCurrencyPair<T>, UnsignedFixedPoint<T>>;

    /// Determines the lower bound for the collateral rate in issued tokens. If a Vault’s
    /// collateral rate drops below this, automatic liquidation (forced Redeem) is triggered.
    #[pallet::storage]
    #[pallet::getter(fn liquidation_collateral_threshold)]
    pub(super) type LiquidationCollateralThreshold<T: Config> =
        StorageMap<_, Blake2_128Concat, DefaultVaultCurrencyPair<T>, UnsignedFixedPoint<T>>;

    #[pallet::storage]
    pub(super) type LiquidationVault<T: Config> =
        StorageMap<_, Blake2_128Concat, DefaultVaultCurrencyPair<T>, DefaultSystemVault<T>, OptionQuery>;

    /// Mapping of Vaults, using the respective Vault account identifier as key.
    #[pallet::storage]
    pub(super) type Vaults<T: Config> = StorageMap<_, Blake2_128Concat, DefaultVaultId<T>, DefaultVault<T>>;

    /// Mapping of Vaults, using the respective Vault account identifier as key.
    #[pallet::storage]
    pub(super) type VaultBitcoinPublicKey<T: Config> =
        StorageMap<_, Blake2_128Concat, T::AccountId, BtcPublicKey, OptionQuery>;

    /// Mapping of reserved BTC addresses to the registered account
    #[pallet::storage]
    pub(super) type ReservedAddresses<T: Config> =
        StorageMap<_, Blake2_128Concat, BtcAddress, DefaultVaultId<T>, OptionQuery>;

    /// Total collateral used for collateral tokens issued by active vaults, excluding the liquidation vault
    #[pallet::storage]
    pub(super) type TotalUserVaultCollateral<T: Config> =
        StorageMap<_, Blake2_128Concat, DefaultVaultCurrencyPair<T>, BalanceOf<T>, ValueQuery>;

    #[pallet::type_value]
    pub(super) fn DefaultForStorageVersion() -> Version {
        Version::V6
    }

    /// Pallet storage version
    #[pallet::storage]
    #[pallet::getter(fn storage_version)]
    pub(super) type StorageVersion<T: Config> = StorageValue<_, Version, ValueQuery, DefaultForStorageVersion>;

    #[pallet::genesis_config]
    #[derive(frame_support::DefaultNoBound)]
    pub struct GenesisConfig<T: Config> {
        pub minimum_collateral_vault: Vec<(CurrencyId<T>, BalanceOf<T>)>,
        pub punishment_delay: BlockNumberFor<T>,
        pub system_collateral_ceiling: Vec<(DefaultVaultCurrencyPair<T>, BalanceOf<T>)>,
        pub secure_collateral_threshold: Vec<(DefaultVaultCurrencyPair<T>, UnsignedFixedPoint<T>)>,
        pub premium_redeem_threshold: Vec<(DefaultVaultCurrencyPair<T>, UnsignedFixedPoint<T>)>,
        pub liquidation_collateral_threshold: Vec<(DefaultVaultCurrencyPair<T>, UnsignedFixedPoint<T>)>,
    }

    #[pallet::genesis_build]
    impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
        fn build(&self) {
            PunishmentDelay::<T>::put(self.punishment_delay);
            for (currency_id, minimum) in self.minimum_collateral_vault.iter() {
                MinimumCollateralVault::<T>::insert(currency_id, minimum);
            }
            for (currency_pair, ceiling) in self.system_collateral_ceiling.iter() {
                SystemCollateralCeiling::<T>::insert(currency_pair, ceiling);
            }
            for (currency_pair, threshold) in self.secure_collateral_threshold.iter() {
                SecureCollateralThreshold::<T>::insert(currency_pair, threshold);
            }
            for (currency_pair, threshold) in self.premium_redeem_threshold.iter() {
                PremiumRedeemThreshold::<T>::insert(currency_pair, threshold);
            }
            for (currency_pair, threshold) in self.liquidation_collateral_threshold.iter() {
                LiquidationCollateralThreshold::<T>::insert(currency_pair, threshold);
            }
            StorageVersion::<T>::put(Version::V3);
        }
    }
}

// "Internal" functions, callable by code.
#[cfg_attr(test, mockable)]
impl<T: Config> Pallet<T> {
    fn _offchain_worker() {
        for vault in Self::undercollateralized_vaults() {
            log::info!("Reporting vault {:?}", vault);
            let call = Call::report_undercollateralized_vault { vault_id: vault };
            let _ = SubmitTransaction::<T, Call<T>>::submit_unsigned_transaction(call.into());
        }
    }

    /// Public functions

    pub fn liquidation_vault_account_id() -> T::AccountId {
        <T as Config>::PalletId::get().into_account_truncating()
    }

    pub fn _register_vault(vault_id: DefaultVaultId<T>, collateral: BalanceOf<T>) -> DispatchResult {
        ensure!(
            SecureCollateralThreshold::<T>::contains_key(&vault_id.currencies),
            Error::<T>::ThresholdNotSet
        );
        ensure!(
            PremiumRedeemThreshold::<T>::contains_key(&vault_id.currencies),
            Error::<T>::ThresholdNotSet
        );
        ensure!(
            LiquidationCollateralThreshold::<T>::contains_key(&vault_id.currencies),
            Error::<T>::ThresholdNotSet
        );
        ensure!(
            MinimumCollateralVault::<T>::contains_key(vault_id.collateral_currency()),
            Error::<T>::MinimumCollateralNotSet
        );
        ensure!(
            SystemCollateralCeiling::<T>::contains_key(&vault_id.currencies),
            Error::<T>::CeilingNotSet
        );

        // make sure a public key is registered
        let _ = Self::get_bitcoin_public_key(&vault_id.account_id)?;

        let collateral_currency = vault_id.currencies.collateral;
        let amount = Amount::new(collateral, collateral_currency);

        ensure!(
            amount.ge(&Self::get_minimum_collateral_vault(collateral_currency))?,
            Error::<T>::InsufficientVaultCollateralAmount
        );
        ensure!(!Self::vault_exists(&vault_id), Error::<T>::VaultAlreadyRegistered);

        let vault = Vault::new(vault_id.clone());
        Self::insert_vault(&vault_id, vault);

        Self::try_deposit_collateral(&vault_id, &amount)?;

        Self::deposit_event(Event::<T>::RegisterVault {
            vault_id: vault_id.clone(),
            collateral,
        });

        Ok(())
    }

    pub fn try_set_vault_custom_secure_threshold(
        vault_id: &DefaultVaultId<T>,
        new_threshold: Option<UnsignedFixedPoint<T>>,
    ) -> DispatchResult {
        if let Some(some_new_threshold) = new_threshold {
            let global_threshold =
                Self::secure_collateral_threshold(&vault_id.currencies).ok_or(Error::<T>::ThresholdNotSet)?;
            ensure!(
                some_new_threshold.gt(&global_threshold),
                Error::<T>::ThresholdNotAboveGlobalThreshold
            );
        }
        let mut vault = Self::get_rich_vault_from_id(&vault_id)?;
        vault.set_custom_secure_threshold(new_threshold)
    }

    pub fn get_vault_secure_threshold(vault_id: &DefaultVaultId<T>) -> Result<UnsignedFixedPoint<T>, DispatchError> {
        let vault = Self::get_rich_vault_from_id(&vault_id)?;
        vault.get_secure_threshold()
    }

    pub fn get_bitcoin_public_key(account_id: &T::AccountId) -> Result<BtcPublicKey, DispatchError> {
        VaultBitcoinPublicKey::<T>::get(account_id).ok_or(Error::<T>::NoBitcoinPublicKey.into())
    }

    pub fn get_vault_from_id(vault_id: &DefaultVaultId<T>) -> Result<DefaultVault<T>, DispatchError> {
        Vaults::<T>::get(vault_id).ok_or(Error::<T>::VaultNotFound.into())
    }

    pub fn get_backing_collateral(vault_id: &DefaultVaultId<T>) -> Result<Amount<T>, DispatchError> {
        ext::staking::total_current_stake::<T>(vault_id)
    }

    /// Calculate the maximum premium that can be given by a vault.
    ///
    /// # Arguments
    /// * `vault_id` - The identifier of the vault for which the maximum premium is being calculated.
    ///
    /// # Returns
    /// Returns a `Result` containing the calculated maximum premium as an `Amount<T>`.
    pub fn get_vault_max_premium_redeem(vault_id: &DefaultVaultId<T>) -> Result<Amount<T>, DispatchError> {
        // The goal of premium redeems is to get the vault back the a healthy collateralization ratio. As such,
        // we only award a premium for the amount of tokens required to get the vault back to secure threshold.
        // The CollateralizationRate is defined as `totalCollateral / convertToCollateral(totalTokens)`
        // When paying a premium, the collateralization rate gets updated according to the following formula:
        //     `NewCollateralization = (oldCol - awardedPremium) / ( oldTokens*EXCH - awardedPremium/FEE)`
        // To calculate the maximum premium we are willing to pay, we set the newCollateralization to
        // the secure threshold, which gives:
        //     `SECURE = (oldCol - awardedPremium) / (oldTokens*EXCH - awardedPremium/FEE)``
        // We can rewrite this formula to calculate the `premium` amount that would get us to the secure threshold:
        //     `maxPremium = (oldTokens * EXCH * SECURE - oldCol) * (FEE / (SECURE - FEE))`
        // Which can be interpreted as:
        //     `maxPremium = missingCollateral * (FEE / (SECURE - FEE))

        // Note that to prevent repeated premium redeems while waiting for execution, we use to_be_backed_tokens
        // for `oldCol`, which takes into account pending issues and redeems
        let to_be_backed_tokens = Self::vault_to_be_backed_tokens(&vault_id)?;
        let global_secure_threshold = Self::get_global_secure_threshold(&vault_id.currencies)?;
        let premium_redeem_rate = ext::fee::premium_redeem_reward_rate::<T>();

        let required_collateral =
            Self::get_required_collateral_for_wrapped(&to_be_backed_tokens, vault_id.collateral_currency())?;
        let current_collateral = Self::get_backing_collateral(&vault_id)?;
        let missing_collateral = required_collateral.saturating_sub(&current_collateral)?;

        // factor = fee / (secure - fee)
        let factor = premium_redeem_rate
            .checked_div(
                &global_secure_threshold
                    .checked_sub(&premium_redeem_rate)
                    .ok_or(ArithmeticError::Underflow)?,
            )
            .ok_or(ArithmeticError::DivisionByZero)?;

        let max_premium = missing_collateral.checked_mul(&factor)?;
        Ok(max_premium)
    }

    pub fn get_liquidated_collateral(vault_id: &DefaultVaultId<T>) -> Result<Amount<T>, DispatchError> {
        let vault = Self::get_vault_from_id(vault_id)?;
        Ok(Amount::new(vault.liquidated_collateral, vault_id.currencies.collateral))
    }

    pub fn get_free_redeemable_tokens(vault_id: &DefaultVaultId<T>) -> Result<Amount<T>, DispatchError> {
        Ok(Self::get_rich_vault_from_id(vault_id)?.freely_redeemable_tokens()?)
    }

    /// Like get_vault_from_id, but additionally checks that the vault is active
    pub fn get_active_vault_from_id(vault_id: &DefaultVaultId<T>) -> Result<DefaultVault<T>, DispatchError> {
        let vault = Self::get_vault_from_id(vault_id)?;
        match vault.status {
            VaultStatus::Active(_) => Ok(vault),
            VaultStatus::Liquidated => Err(Error::<T>::VaultLiquidated.into()),
        }
    }

    /// Deposit an `amount` of collateral to be used for collateral tokens
    ///
    /// # Arguments
    /// * `vault_id` - the id of the vault
    /// * `amount` - the amount of collateral
    pub fn try_deposit_collateral(vault_id: &DefaultVaultId<T>, amount: &Amount<T>) -> DispatchResult {
        T::NominationApi::deposit_vault_collateral(&vault_id, &amount)
    }

    /// Withdraw an `amount` of collateral without checking collateralization
    ///
    /// # Arguments
    /// * `vault_id` - the id of the vault
    /// * `amount` - the amount of collateral
    pub fn force_withdraw_collateral(vault_id: &DefaultVaultId<T>, amount: &Amount<T>) -> DispatchResult {
        // will fail if reserved_balance is insufficient
        amount.unlock_on(&vault_id.account_id)?;
        Self::decrease_total_backing_collateral(&vault_id.currencies, amount)?;

        // Withdraw `amount` of stake from the pool
        PoolManager::<T>::withdraw_collateral(vault_id, &vault_id.account_id, Some(amount.clone()), None)?;

        Ok(())
    }

    /// Checks if the vault would be above the secure threshold after withdrawing collateral
    pub fn is_allowed_to_withdraw_collateral(
        vault_id: &DefaultVaultId<T>,
        amount: Option<Amount<T>>,
    ) -> Result<bool, DispatchError> {
        let vault = Self::get_rich_vault_from_id(vault_id)?;

        let new_collateral = if let Some(amount) = amount {
            match Self::get_backing_collateral(vault_id)?.checked_sub(&amount) {
                Ok(x) => x,
                Err(x) if x == ArithmeticError::Underflow.into() => return Ok(false),
                Err(x) => return Err(x),
            }
        } else {
            Amount::<T>::zero(vault_id.collateral_currency())
        };

        ensure!(
            new_collateral.is_zero()
                || new_collateral.ge(&Self::get_minimum_collateral_vault(vault_id.currencies.collateral))?,
            Error::<T>::InsufficientVaultCollateralAmount
        );

        let is_below_threshold =
            Pallet::<T>::is_collateral_below_vault_secure_threshold(&new_collateral, &vault.backed_tokens()?, &vault)?;
        Ok(!is_below_threshold)
    }

    pub fn transfer_funds_saturated(
        from: CurrencySource<T>,
        to: CurrencySource<T>,
        amount: &Amount<T>,
    ) -> Result<Amount<T>, DispatchError> {
        let available_amount = from.current_balance(amount.currency())?;
        let amount = if available_amount.lt(&amount)? {
            available_amount
        } else {
            amount.clone()
        };
        Self::transfer_funds(from, to, &amount)?;
        Ok(amount)
    }

    fn slash_backing_collateral(vault_id: &DefaultVaultId<T>, amount: &Amount<T>) -> DispatchResult {
        amount.unlock_on(&vault_id.account_id)?;
        Self::decrease_total_backing_collateral(&vault_id.currencies, amount)?;
        PoolManager::<T>::slash_collateral(vault_id, amount)?;
        Ok(())
    }

    pub fn transfer_funds(from: CurrencySource<T>, to: CurrencySource<T>, amount: &Amount<T>) -> DispatchResult {
        match from {
            CurrencySource::Collateral(ref vault_id) => {
                ensure!(
                    vault_id.currencies.collateral == amount.currency(),
                    Error::<T>::InvalidCurrency
                );
                Self::slash_backing_collateral(vault_id, amount)?;
            }
            CurrencySource::AvailableReplaceCollateral(ref vault_id) => {
                let mut vault = Self::get_active_rich_vault_from_id(&vault_id)?;
                vault.decrease_available_replace_collateral(amount)?;
                amount.unlock_on(&from.account_id())?;
            }
            CurrencySource::ActiveReplaceCollateral(ref vault_id) => {
                let mut vault = Self::get_rich_vault_from_id(&vault_id)?;
                vault.decrease_active_replace_collateral(amount)?;
                amount.unlock_on(&from.account_id())?;
            }
            CurrencySource::UserGriefing(_) => {
                amount.unlock_on(&from.account_id())?;
            }
            CurrencySource::LiquidatedCollateral(VaultId { ref currencies, .. }) => {
                Self::decrease_total_backing_collateral(currencies, amount)?;
                amount.unlock_on(&from.account_id())?;
            }
            CurrencySource::LiquidationVault(ref currencies) => {
                let mut liquidation_vault = Self::get_rich_liquidation_vault(currencies);
                liquidation_vault.decrease_collateral(amount)?;
                Self::decrease_total_backing_collateral(currencies, amount)?;
                amount.unlock_on(&from.account_id())?;
            }
            CurrencySource::FreeBalance(_) => {
                // do nothing
            }
        };

        // move from sender's free balance to receiver's free balance
        amount.transfer(&from.account_id(), &to.account_id())?;

        // move receiver funds from free balance to specified currency source
        match to {
            CurrencySource::Collateral(ref vault_id) => {
                // todo: do we need to do this for griefing as well?
                ensure!(
                    vault_id.currencies.collateral == amount.currency(),
                    Error::<T>::InvalidCurrency
                );
                Self::try_deposit_collateral(vault_id, amount)?;
            }
            CurrencySource::AvailableReplaceCollateral(ref vault_id) => {
                let mut vault = Self::get_active_rich_vault_from_id(&vault_id)?;
                vault.increase_available_replace_collateral(amount)?;
                amount.lock_on(&to.account_id())?;
            }
            CurrencySource::ActiveReplaceCollateral(ref vault_id) => {
                let mut vault = Self::get_rich_vault_from_id(&vault_id)?;
                vault.increase_active_replace_collateral(amount)?;
                amount.lock_on(&to.account_id())?;
            }
            CurrencySource::UserGriefing(_) => {
                amount.lock_on(&to.account_id())?;
            }
            CurrencySource::LiquidatedCollateral(VaultId { ref currencies, .. }) => {
                Self::try_increase_total_backing_collateral(currencies, amount)?;
                amount.lock_on(&to.account_id())?;
            }
            CurrencySource::LiquidationVault(ref currencies) => {
                Self::try_increase_total_backing_collateral(currencies, amount)?;
                let mut liquidation_vault = Self::get_rich_liquidation_vault(currencies);
                liquidation_vault.increase_collateral(amount)?;
                amount.lock_on(&to.account_id())?;
            }
            CurrencySource::FreeBalance(_) => {
                // do nothing
            }
        };

        Ok(())
    }

    /// Checks if the vault has sufficient collateral to increase the to-be-issued tokens, and
    /// if so, increases it
    ///
    /// # Arguments
    /// * `vault_id` - the id of the vault from which to increase to-be-issued tokens
    /// * `tokens` - the amount of tokens to be reserved
    pub fn try_increase_to_be_issued_tokens(
        vault_id: &DefaultVaultId<T>,
        tokens: &Amount<T>,
    ) -> Result<(), DispatchError> {
        let mut vault = Self::get_active_rich_vault_from_id(&vault_id)?;

        let issuable_tokens = vault.issuable_tokens()?;
        ensure!(issuable_tokens.ge(&tokens)?, Error::<T>::ExceedingVaultLimit);
        vault.request_issue_tokens(tokens)?;

        Self::deposit_event(Event::<T>::IncreaseToBeIssuedTokens {
            vault_id: vault.id(),
            increase: tokens.amount(),
        });
        Ok(())
    }

    /// Registers a btc address
    ///
    /// # Arguments
    /// * `issue_id` - secure id for generating deposit address
    pub fn register_deposit_address(vault_id: &DefaultVaultId<T>, issue_id: H256) -> Result<BtcAddress, DispatchError> {
        let mut vault = Self::get_active_rich_vault_from_id(&vault_id)?;
        let btc_address = vault.new_deposit_address(issue_id)?;
        Self::deposit_event(Event::<T>::RegisterAddress {
            vault_id: vault.id(),
            address: btc_address,
        });
        Ok(btc_address)
    }

    /// returns the amount of tokens that a vault can request to be replaced on top of the
    /// current to-be-replaced tokens
    pub fn requestable_to_be_replaced_tokens(vault_id: &DefaultVaultId<T>) -> Result<Amount<T>, DispatchError> {
        let vault = Self::get_active_rich_vault_from_id(&vault_id)?;

        vault
            .issued_tokens()
            .checked_sub(&vault.to_be_replaced_tokens())?
            .checked_sub(&vault.to_be_redeemed_tokens())
    }

    /// returns the new total to-be-replaced and replace-collateral
    pub fn try_increase_to_be_replaced_tokens(
        vault_id: &DefaultVaultId<T>,
        tokens: &Amount<T>,
    ) -> Result<Amount<T>, DispatchError> {
        let mut vault = Self::get_active_rich_vault_from_id(&vault_id)?;

        let new_to_be_replaced = vault.to_be_replaced_tokens().checked_add(&tokens)?;
        let total_decreasing_tokens = new_to_be_replaced.checked_add(&vault.to_be_redeemed_tokens())?;

        ensure!(
            total_decreasing_tokens.le(&vault.issued_tokens())?,
            Error::<T>::InsufficientTokensCommitted
        );

        vault.set_to_be_replaced_amount(&new_to_be_replaced)?;

        Self::deposit_event(Event::<T>::IncreaseToBeReplacedTokens {
            vault_id: vault.id(),
            increase: tokens.amount(),
        });

        Ok(new_to_be_replaced)
    }

    pub fn decrease_to_be_replaced_tokens(
        vault_id: &DefaultVaultId<T>,
        tokens: &Amount<T>,
    ) -> Result<(Amount<T>, Amount<T>), DispatchError> {
        let mut vault = Self::get_rich_vault_from_id(&vault_id)?;

        let initial_to_be_replaced = Amount::new(vault.data.to_be_replaced_tokens, vault_id.wrapped_currency());
        let initial_griefing_collateral =
            Amount::new(vault.data.replace_collateral, T::GetGriefingCollateralCurrencyId::get());

        let used_tokens = tokens.min(&initial_to_be_replaced)?;

        let used_collateral =
            Self::calculate_collateral(&initial_griefing_collateral, &used_tokens, &initial_to_be_replaced)?;

        // make sure we don't use too much if a rounding error occurs
        let used_collateral = used_collateral.min(&initial_griefing_collateral)?;

        let new_to_be_replaced = initial_to_be_replaced.checked_sub(&used_tokens)?;

        vault.set_to_be_replaced_amount(&new_to_be_replaced)?;

        Self::deposit_event(Event::<T>::DecreaseToBeReplacedTokens {
            vault_id: vault.id(),
            decrease: tokens.amount(),
        });

        Ok((used_tokens, used_collateral))
    }

    /// Decreases the amount of tokens to be issued in the next issue request from the
    /// vault, or from the liquidation vault if the vault is liquidated
    ///
    /// # Arguments
    /// * `vault_id` - the id of the vault from which to decrease to-be-issued tokens
    /// * `tokens` - the amount of tokens to be unreserved
    pub fn decrease_to_be_issued_tokens(vault_id: &DefaultVaultId<T>, tokens: &Amount<T>) -> DispatchResult {
        let mut vault = Self::get_rich_vault_from_id(vault_id)?;
        vault.cancel_issue_tokens(tokens)?;

        Self::deposit_event(Event::<T>::DecreaseToBeIssuedTokens {
            vault_id: vault_id.clone(),
            decrease: tokens.amount(),
        });
        Ok(())
    }

    /// Issues an amount of `tokens` tokens for the given `vault_id`
    /// At this point, the to-be-issued tokens assigned to a vault are decreased
    /// and the issued tokens balance is increased by the amount of issued tokens.
    ///
    /// # Arguments
    /// * `vault_id` - the id of the vault from which to issue tokens
    /// * `tokens` - the amount of tokens to issue
    ///
    /// # Errors
    /// * `VaultNotFound` - if no vault exists for the given `vault_id`
    /// * `InsufficientTokensCommitted` - if the amount of tokens reserved is too low
    pub fn issue_tokens(vault_id: &DefaultVaultId<T>, tokens: &Amount<T>) -> DispatchResult {
        let mut vault = Self::get_rich_vault_from_id(&vault_id)?;
        vault.execute_issue_tokens(tokens)?;
        Self::deposit_event(Event::<T>::IssueTokens {
            vault_id: vault.id(),
            increase: tokens.amount(),
        });
        Ok(())
    }

    /// Get the global secure threshold for a specified currency pair.
    ///
    /// # Arguments
    /// * `currency_pair` - The currency pair for which to retrieve the global secure threshold.
    ///
    /// # Returns
    /// Returns the global secure threshold for the specified currency pair or an error if the threshold is not set.
    ///
    /// # Errors
    /// * `ThresholdNotSet` - If the secure collateral threshold for the given `currency_pair` is not set.
    #[cfg_attr(feature = "integration-tests", visibility::make(pub))]
    fn get_global_secure_threshold(
        currency_pair: &VaultCurrencyPair<CurrencyId<T>>,
    ) -> Result<UnsignedFixedPoint<T>, DispatchError> {
        let global_secure_threshold =
            Self::secure_collateral_threshold(&currency_pair).ok_or(Error::<T>::ThresholdNotSet)?;
        Ok(global_secure_threshold)
    }

    /// Adds an amount tokens to the to-be-redeemed tokens balance of a vault.
    /// This function serves as a prevention against race conditions in the
    /// redeem and replace procedures. If, for example, a vault would receive
    /// two redeem requests at the same time that have a higher amount of tokens
    ///  to be issued than his issuedTokens balance, one of the two redeem
    /// requests should be rejected.
    ///
    /// # Arguments
    /// * `vault_id` - the id of the vault from which to increase to-be-redeemed tokens
    /// * `tokens` - the amount of tokens to be redeemed
    ///
    /// # Errors
    /// * `VaultNotFound` - if no vault exists for the given `vault_id`
    /// * `InsufficientTokensCommitted` - if the amount of redeemable tokens is too low
    pub fn try_increase_to_be_redeemed_tokens(vault_id: &DefaultVaultId<T>, tokens: &Amount<T>) -> DispatchResult {
        let mut vault = Self::get_active_rich_vault_from_id(&vault_id)?;
        let redeemable = vault.issued_tokens().checked_sub(&vault.to_be_redeemed_tokens())?;
        ensure!(redeemable.ge(&tokens)?, Error::<T>::InsufficientTokensCommitted);

        vault.request_redeem_tokens(tokens)?;

        Self::deposit_event(Event::<T>::IncreaseToBeRedeemedTokens {
            vault_id: vault.id(),
            increase: tokens.amount(),
        });
        Ok(())
    }

    /// Subtracts an amount tokens from the to-be-redeemed tokens balance of a vault.
    ///
    /// # Arguments
    /// * `vault_id` - the id of the vault from which to decrease to-be-redeemed tokens
    /// * `tokens` - the amount of tokens to be redeemed
    ///
    /// # Errors
    /// * `VaultNotFound` - if no vault exists for the given `vault_id`
    /// * `InsufficientTokensCommitted` - if the amount of to-be-redeemed tokens is too low
    pub fn decrease_to_be_redeemed_tokens(vault_id: &DefaultVaultId<T>, tokens: &Amount<T>) -> DispatchResult {
        let mut vault = Self::get_rich_vault_from_id(&vault_id)?;
        vault.cancel_redeem_tokens(tokens)?;

        Self::deposit_event(Event::<T>::DecreaseToBeRedeemedTokens {
            vault_id: vault.id(),
            decrease: tokens.amount(),
        });
        Ok(())
    }

    /// Decreases the amount of tokens f a redeem request is not fulfilled
    /// Removes the amount of tokens assigned to the to-be-redeemed tokens.
    /// At this point, we consider the tokens lost and the issued tokens are
    /// removed from the vault
    ///
    /// # Arguments
    /// * `vault_id` - the id of the vault from which to decrease tokens
    /// * `tokens` - the amount of tokens to be decreased
    /// * `user_id` - the id of the user making the redeem request
    pub fn decrease_tokens(vault_id: &DefaultVaultId<T>, user_id: &T::AccountId, tokens: &Amount<T>) -> DispatchResult {
        // decrease to-be-redeemed and issued
        let mut vault = Self::get_rich_vault_from_id(&vault_id)?;
        vault.execute_redeem_tokens(tokens)?;

        Self::deposit_event(Event::<T>::DecreaseTokens {
            vault_id: vault.id(),
            user_id: user_id.clone(),
            decrease: tokens.amount(),
        });
        Ok(())
    }

    /// Decreases the amount of collateral held after liquidation for any remaining to_be_redeemed tokens.
    ///
    /// # Arguments
    /// * `vault_id` - the id of the vault
    /// * `amount` - the amount of collateral to decrement
    pub fn decrease_liquidated_collateral(vault_id: &DefaultVaultId<T>, amount: &Amount<T>) -> DispatchResult {
        let mut vault = Self::get_rich_vault_from_id(vault_id)?;
        vault.decrease_liquidated_collateral(amount)?;
        Ok(())
    }

    /// Reduces the to-be-redeemed tokens when a redeem request completes
    ///
    /// # Arguments
    /// * `vault_id` - the id of the vault from which to redeem tokens
    /// * `tokens` - the amount of tokens to be decreased
    /// * `premium` - amount of collateral to be rewarded to the redeemer if the vault is not liquidated yet
    /// * `redeemer_id` - the id of the redeemer
    pub fn redeem_tokens(
        vault_id: &DefaultVaultId<T>,
        tokens: &Amount<T>,
        premium: &Amount<T>,
        redeemer_id: &T::AccountId,
    ) -> DispatchResult {
        let mut vault = Self::get_rich_vault_from_id(&vault_id)?;

        // need to read before we decrease it
        let to_be_redeemed_tokens = vault.to_be_redeemed_tokens();

        vault.execute_redeem_tokens(tokens)?;

        if !vault.data.is_liquidated() {
            if premium.is_zero() {
                Self::deposit_event(Event::<T>::RedeemTokens {
                    vault_id: vault.id(),
                    redeemed_amount: tokens.amount(),
                });
            } else {
                Self::transfer_funds(
                    CurrencySource::Collateral(vault_id.clone()),
                    CurrencySource::FreeBalance(redeemer_id.clone()),
                    premium,
                )?;

                Self::deposit_event(Event::<T>::RedeemTokensPremium {
                    vault_id: vault_id.clone(),
                    redeemed_amount: tokens.amount(),
                    collateral: premium.amount(),
                    user_id: redeemer_id.clone(),
                });
            }
        } else {
            // NOTE: previously we calculated the amount to release based on the Vault's `backing_collateral`
            // but this may now be wrong in the pull-based approach if the Vault is left with excess collateral
            let to_be_released =
                Self::calculate_collateral(&vault.liquidated_collateral(), tokens, &to_be_redeemed_tokens)?;
            Self::decrease_total_backing_collateral(&vault_id.currencies, &to_be_released)?;
            vault.decrease_liquidated_collateral(&to_be_released)?;

            // release the collateral back to the free balance of the vault
            to_be_released.unlock_on(&vault_id.account_id)?;

            Self::deposit_event(Event::<T>::RedeemTokensLiquidatedVault {
                vault_id: vault_id.clone(),
                tokens: tokens.amount(),
                collateral: to_be_released.amount(),
            });
        }

        Ok(())
    }

    /// Handles redeem requests which are executed against the LiquidationVault.
    /// Reduces the issued token of the LiquidationVault and slashes the
    /// corresponding amount of collateral.
    ///
    /// # Arguments
    /// * `currency_id` - the currency being redeemed
    /// * `redeemer_id` - the account of the user redeeming issued tokens
    /// * `tokens` - the amount of tokens to be redeemed in collateral with the LiquidationVault, denominated in BTC
    ///
    /// # Errors
    /// * `InsufficientTokensCommitted` - if the amount of tokens issued by the liquidation vault is too low
    /// * `InsufficientFunds` - if the liquidation vault does not have enough collateral to transfer
    pub fn redeem_tokens_liquidation(
        currency_id: CurrencyId<T>,
        redeemer_id: &T::AccountId,
        amount_wrapped: &Amount<T>,
    ) -> DispatchResult {
        let currency_pair = VaultCurrencyPair {
            collateral: currency_id,
            wrapped: amount_wrapped.currency(),
        };

        let liquidation_vault = Self::get_rich_liquidation_vault(&currency_pair);

        ensure!(
            liquidation_vault.redeemable_tokens()?.ge(&amount_wrapped)?,
            Error::<T>::InsufficientTokensCommitted
        );

        let source_liquidation_vault = CurrencySource::<T>::LiquidationVault(currency_pair.clone());

        // transfer liquidated collateral to redeemer
        let to_transfer = Self::calculate_collateral(
            &source_liquidation_vault.current_balance(currency_id)?,
            amount_wrapped,
            &liquidation_vault.to_be_backed_tokens()?,
        )?;

        Self::transfer_funds(
            source_liquidation_vault,
            CurrencySource::FreeBalance(redeemer_id.clone()),
            &to_transfer,
        )?;

        // need to requery since the liquidation vault gets modified in `transfer_funds`
        let mut liquidation_vault = Self::get_rich_liquidation_vault(&currency_pair);
        liquidation_vault.burn_issued(amount_wrapped)?;

        Self::deposit_event(Event::<T>::RedeemTokensLiquidation {
            redeemer_id: redeemer_id.clone(),
            burned_tokens: amount_wrapped.amount(),
            transferred_collateral: to_transfer.amount(),
        });

        Ok(())
    }

    /// Replaces the old vault by the new vault by transferring tokens
    /// from the old vault to the new one
    ///
    /// # Arguments
    /// * `old_vault_id` - the id of the old vault
    /// * `new_vault_id` - the id of the new vault
    /// * `tokens` - the amount of tokens to be transferred from the old to the new vault
    /// * `collateral` - the collateral to be locked by the new vault
    ///
    /// # Errors
    /// * `VaultNotFound` - if either the old or new vault does not exist
    /// * `InsufficientTokensCommitted` - if the amount of tokens of the old vault is too low
    /// * `InsufficientFunds` - if the new vault does not have enough collateral to lock
    pub fn replace_tokens(
        old_vault_id: &DefaultVaultId<T>,
        new_vault_id: &DefaultVaultId<T>,
        tokens: &Amount<T>,
        collateral: &Amount<T>,
    ) -> DispatchResult {
        let mut old_vault = Self::get_rich_vault_from_id(&old_vault_id)?;
        let mut new_vault = Self::get_rich_vault_from_id(&new_vault_id)?;

        if old_vault.data.is_liquidated() {
            let to_be_released = Self::calculate_collateral(
                &old_vault.liquidated_collateral(),
                tokens,
                &old_vault.to_be_redeemed_tokens(),
            )?;
            old_vault.decrease_liquidated_collateral(&to_be_released)?;

            // deposit old-vault's collateral (this was withdrawn on liquidation)
            PoolManager::<T>::deposit_collateral(old_vault_id, &old_vault_id.account_id, &to_be_released)?;
        }

        old_vault.execute_redeem_tokens(tokens)?;
        new_vault.execute_issue_tokens(tokens)?;

        Self::deposit_event(Event::<T>::ReplaceTokens {
            old_vault_id: old_vault_id.clone(),
            new_vault_id: new_vault_id.clone(),
            amount: tokens.amount(),
            additional_collateral: collateral.amount(),
        });
        Ok(())
    }

    /// Cancels a replace - which in the normal case decreases the old-vault's
    /// to-be-redeemed tokens, and the new-vault's to-be-issued tokens.
    /// When one or both of the vaults have been liquidated, this function also
    /// updates the liquidation vault.
    ///
    /// # Arguments
    /// * `old_vault_id` - the id of the old vault
    /// * `new_vault_id` - the id of the new vault
    /// * `tokens` - the amount of tokens to be transferred from the old to the new vault
    pub fn cancel_replace_tokens(
        old_vault_id: &DefaultVaultId<T>,
        new_vault_id: &DefaultVaultId<T>,
        tokens: &Amount<T>,
    ) -> DispatchResult {
        let mut old_vault = Self::get_rich_vault_from_id(&old_vault_id)?;
        let mut new_vault = Self::get_rich_vault_from_id(&new_vault_id)?;

        if old_vault.data.is_liquidated() {
            let to_be_transferred = Self::calculate_collateral(
                &old_vault.liquidated_collateral(),
                tokens,
                &old_vault.to_be_redeemed_tokens(),
            )?;
            old_vault.decrease_liquidated_collateral(&to_be_transferred)?;

            // transfer old-vault's collateral to liquidation_vault
            Self::transfer_funds(
                CurrencySource::LiquidatedCollateral(old_vault_id.clone()),
                CurrencySource::LiquidationVault(old_vault_id.currencies.clone()),
                &to_be_transferred,
            )?;
        }

        old_vault.cancel_redeem_tokens(tokens)?;
        new_vault.cancel_issue_tokens(tokens)?;

        Ok(())
    }

    /// Withdraws an `amount` of tokens that were requested for replacement by `vault_id`
    ///
    /// # Arguments
    /// * `vault_id` - the id of the vault
    /// * `amount` - the amount of tokens to be withdrawn from replace requests
    pub fn withdraw_replace_request(
        vault_id: &DefaultVaultId<T>,
        amount: &Amount<T>,
    ) -> Result<(Amount<T>, Amount<T>), DispatchError> {
        let (withdrawn_tokens, to_withdraw_collateral) = Self::decrease_to_be_replaced_tokens(&vault_id, &amount)?;

        // release the used collateral
        Self::transfer_funds(
            CurrencySource::AvailableReplaceCollateral(vault_id.clone()),
            CurrencySource::FreeBalance(vault_id.account_id.clone()),
            &to_withdraw_collateral,
        )?;

        Ok((withdrawn_tokens, to_withdraw_collateral))
    }

    fn undercollateralized_vaults() -> impl Iterator<Item = DefaultVaultId<T>> {
        <Vaults<T>>::iter().filter_map(|(vault_id, vault)| {
            if let Some(liquidation_threshold) = Self::liquidation_collateral_threshold(&vault.id.currencies) {
                if Self::is_vault_below_liquidation_threshold(&vault, liquidation_threshold).unwrap_or(false) {
                    return Some(vault_id);
                }
            }
            None
        })
    }

    /// Liquidates a vault, transferring all of its token balances to the
    /// `LiquidationVault`, as well as the collateral.
    ///
    /// # Arguments
    /// * `vault_id` - the id of the vault to liquidate
    /// * `status` - status with which to liquidate the vault
    pub fn liquidate_vault(vault_id: &DefaultVaultId<T>) -> Result<Amount<T>, DispatchError> {
        let mut vault = Self::get_active_rich_vault_from_id(&vault_id)?;
        let backing_collateral = vault.get_total_collateral()?;
        let vault_orig = vault.data.clone();

        let to_slash = vault.liquidate()?;

        Self::deposit_event(Event::<T>::LiquidateVault {
            vault_id: vault_id.clone(),
            issued_tokens: vault_orig.issued_tokens,
            to_be_issued_tokens: vault_orig.to_be_issued_tokens,
            to_be_redeemed_tokens: vault_orig.to_be_redeemed_tokens,
            to_be_replaced_tokens: vault_orig.to_be_replaced_tokens,
            backing_collateral: backing_collateral.amount(),
            status: VaultStatus::Liquidated,
            replace_collateral: vault_orig.replace_collateral,
        });
        Ok(to_slash)
    }

    pub fn try_increase_total_backing_collateral(
        currency_pair: &DefaultVaultCurrencyPair<T>,
        amount: &Amount<T>,
    ) -> DispatchResult {
        let new = Self::get_total_user_vault_collateral(currency_pair)?.checked_add(&amount)?;

        let limit = Self::get_collateral_ceiling(currency_pair)?;
        ensure!(new.le(&limit)?, Error::<T>::CurrencyCeilingExceeded);

        TotalUserVaultCollateral::<T>::insert(currency_pair, new.amount());

        Self::deposit_event(Event::<T>::IncreaseLockedCollateral {
            currency_pair: currency_pair.clone(),
            delta: amount.amount(),
            total: new.amount(),
        });
        Ok(())
    }

    pub fn decrease_total_backing_collateral(
        currency_pair: &DefaultVaultCurrencyPair<T>,
        amount: &Amount<T>,
    ) -> DispatchResult {
        let new = Self::get_total_user_vault_collateral(currency_pair)?.checked_sub(amount)?;

        TotalUserVaultCollateral::<T>::insert(currency_pair, new.amount());

        Self::deposit_event(Event::<T>::DecreaseLockedCollateral {
            currency_pair: currency_pair.clone(),
            delta: amount.amount(),
            total: new.amount(),
        });
        Ok(())
    }

    pub fn insert_vault(id: &DefaultVaultId<T>, vault: DefaultVault<T>) {
        Vaults::<T>::insert(id, vault)
    }

    pub fn ban_vault(vault_id: &DefaultVaultId<T>) -> DispatchResult {
        let height = ext::security::active_block_number::<T>();
        let mut vault = Self::get_active_rich_vault_from_id(vault_id)?;
        let banned_until = height + Self::punishment_delay();
        vault.ban_until(banned_until);
        Self::deposit_event(Event::<T>::BanVault {
            vault_id: vault.id(),
            banned_until,
        });
        Ok(())
    }

    pub fn ensure_not_banned(vault_id: &DefaultVaultId<T>) -> DispatchResult {
        let vault = Self::get_active_rich_vault_from_id(&vault_id)?;
        vault.ensure_not_banned()
    }

    /// Threshold checks
    pub fn is_vault_below_secure_threshold(vault_id: &DefaultVaultId<T>) -> Result<bool, DispatchError> {
        let vault = Self::get_rich_vault_from_id(&vault_id)?;
        let threshold = vault.get_secure_threshold()?;
        Self::is_vault_below_certain_threshold(vault_id, threshold)
    }

    pub fn is_vault_liquidated(vault_id: &DefaultVaultId<T>) -> Result<bool, DispatchError> {
        Ok(Self::get_vault_from_id(&vault_id)?.is_liquidated())
    }

    // note: unlike `is_vault_below_secure_threshold` and `is_vault_below_liquidation_threshold`,
    // this function uses to_be_backed tokens
    pub fn will_be_below_premium_threshold(vault_id: &DefaultVaultId<T>) -> Result<bool, DispatchError> {
        let vault = Self::get_rich_vault_from_id(&vault_id)?;
        let threshold = Self::premium_redeem_threshold(&vault_id.currencies).ok_or(Error::<T>::ThresholdNotSet)?;
        let collateral = Self::get_backing_collateral(vault_id)?;

        Self::is_collateral_below_threshold(&collateral, &vault.to_be_backed_tokens()?, threshold)
    }

    /// check if the vault is below the liquidation threshold.
    pub fn is_vault_below_liquidation_threshold(
        vault: &DefaultVault<T>,
        liquidation_threshold: UnsignedFixedPoint<T>,
    ) -> Result<bool, DispatchError> {
        Self::is_collateral_below_threshold(
            &Self::get_backing_collateral(&vault.id)?,
            &Amount::new(vault.issued_tokens, vault.id.wrapped_currency()),
            liquidation_threshold,
        )
    }

    /// Takes vault custom secure threshold into account (if set)
    pub fn is_collateral_below_vault_secure_threshold(
        collateral: &Amount<T>,
        wrapped_amount: &Amount<T>,
        vault: &RichVault<T>,
    ) -> Result<bool, DispatchError> {
        let threshold = vault.get_secure_threshold()?;
        Self::is_collateral_below_threshold(collateral, wrapped_amount, threshold)
    }

    pub fn _set_minimum_collateral_vault(collateral_currency: CurrencyId<T>, min_collateral: BalanceOf<T>) {
        MinimumCollateralVault::<T>::insert(collateral_currency, min_collateral);
    }

    pub fn _set_system_collateral_ceiling(currency_pair: DefaultVaultCurrencyPair<T>, ceiling: BalanceOf<T>) {
        SystemCollateralCeiling::<T>::insert(currency_pair, ceiling);
    }

    pub fn _set_secure_collateral_threshold(
        currency_pair: DefaultVaultCurrencyPair<T>,
        threshold: UnsignedFixedPoint<T>,
    ) {
        SecureCollateralThreshold::<T>::insert(currency_pair, threshold);
    }

    pub fn _set_premium_redeem_threshold(currency_pair: DefaultVaultCurrencyPair<T>, threshold: UnsignedFixedPoint<T>) {
        PremiumRedeemThreshold::<T>::insert(currency_pair, threshold);
    }

    pub fn _set_liquidation_collateral_threshold(
        currency_pair: DefaultVaultCurrencyPair<T>,
        threshold: UnsignedFixedPoint<T>,
    ) {
        LiquidationCollateralThreshold::<T>::insert(currency_pair, threshold);
    }

    /// return (collateral * Numerator) / denominator, used when dealing with liquidated vaults
    pub fn calculate_collateral(
        collateral: &Amount<T>,
        numerator: &Amount<T>,
        denominator: &Amount<T>,
    ) -> Result<Amount<T>, DispatchError> {
        if numerator.is_zero() && denominator.is_zero() {
            return Ok(collateral.clone());
        }

        let currency = collateral.currency();

        let collateral: U256 = collateral.amount().into();
        let numerator: U256 = numerator.amount().into();
        let denominator: U256 = denominator.amount().into();

        let amount = collateral
            .checked_mul(numerator)
            .ok_or(ArithmeticError::Overflow)?
            .checked_div(denominator)
            .ok_or(ArithmeticError::Underflow)?
            .try_into()
            .map_err(|_| Error::<T>::TryIntoIntError)?;
        Ok(Amount::new(amount, currency))
    }

    /// RPC

    /// get all vaults the are registered using the given account id. Note that one account id might be
    /// used in multiple vault ids.
    pub fn get_vaults_by_account_id(account_id: T::AccountId) -> Result<Vec<DefaultVaultId<T>>, DispatchError> {
        let vaults = Vaults::<T>::iter()
            .filter(|(vault_id, _)| vault_id.account_id == account_id)
            .map(|(vault_id, _)| vault_id)
            .collect();
        Ok(vaults)
    }

    /// Calculates the inclusion fee for a redeem transaction based on the provided parameters.
    pub fn calculate_inclusion_fee(
        wrapped_currency: CurrencyId<T>,
        redeem_tx_size: u32,
    ) -> Result<Amount<T>, DispatchError> {
        let satoshi_per_bytes = ext::oracle::get_price::<T>(OracleKey::FeeEstimation)?;

        let fee = satoshi_per_bytes
            .checked_mul_int(redeem_tx_size)
            .ok_or(ArithmeticError::Overflow)?;
        let amount = fee.try_into().map_err(|_| Error::<T>::TryIntoIntError)?;
        Ok(Amount::new(amount, wrapped_currency))
    }

    /// Get all vaults that:
    /// - are below the premium redeem threshold, and
    /// - have a non-zero amount of redeemable tokens, and thus
    /// - are not banned
    ///
    /// Return a tuple of (VaultId, RedeemTokens to get `max_premium` from vault)
    pub fn get_premium_redeem_vaults(
        redeem_transaction_size: u32,
    ) -> Result<Vec<(DefaultVaultId<T>, Amount<T>)>, DispatchError> {
        let premium_reward_rate = ext::fee::premium_redeem_reward_rate::<T>();

        let mut suitable_vaults = Vaults::<T>::iter()
            .filter_map(|(vault_id, _vault)| {
                // The calculation to calculate redeem tokens to get `max_premium` is referenced from
                // redeem pallet `request_redeem` method.
                // BurnTokensForReachingPremiumThreshold = BurnWrap + InclusionFee
                // RedeemTokens = BurnTokensForReachingPremiumThreshold / (1 - RedeemFee)
                let max_premium_in_collateral = Self::get_vault_max_premium_redeem(&vault_id).ok()?;
                let redeem_amount_wrapped_in_collateral =
                    max_premium_in_collateral.checked_div(&premium_reward_rate).ok()?;
                let burn_wrap = redeem_amount_wrapped_in_collateral
                    .convert_to(vault_id.wrapped_currency())
                    .ok()?;
                let inclusion_fee =
                    Self::calculate_inclusion_fee(vault_id.wrapped_currency(), redeem_transaction_size).ok()?;

                let vault_to_burn_tokens = burn_wrap.checked_add(&inclusion_fee).ok()?;

                let redeem_fee = ext::fee::get_redeem_fee_value::<T>();
                let amount_wrapped = UnsignedFixedPoint::<T>::one().saturating_sub(redeem_fee);

                let request_redeem_tokens_for_max_premium = vault_to_burn_tokens.checked_div(&amount_wrapped).ok()?;

                if Self::ensure_not_banned(&vault_id).is_ok()
                    && !request_redeem_tokens_for_max_premium.is_zero()
                    // Need to check `will_be_below_premium_threshold` to handle a corner case
                    // where the vault is above PremiumThreshold, but `request_redeem_tokens_for_max_premium` is being calculated as a non-zero amount
                    // since the `inclusion_fee` is a non-zero amount.
                    && Self::will_be_below_premium_threshold(&vault_id).unwrap_or(false)
                {
                    Some((vault_id, request_redeem_tokens_for_max_premium))
                } else {
                    None
                }
            })
            .collect::<Vec<(_, _)>>();

        if suitable_vaults.is_empty() {
            Err(Error::<T>::NoVaultUnderThePremiumRedeemThreshold.into())
        } else {
            suitable_vaults.sort_by(|a, b| b.1.amount().cmp(&a.1.amount()));
            Ok(suitable_vaults)
        }
    }

    /// Get all vaults with non-zero issuable tokens, ordered in descending order of this amount
    pub fn get_vaults_with_issuable_tokens() -> Result<Vec<(DefaultVaultId<T>, Amount<T>)>, DispatchError> {
        let mut vaults_with_issuable_tokens = Vaults::<T>::iter()
            .filter_map(|(vault_id, _vault)| {
                // NOTE: we are not checking if the vault accepts new issues here - if not, then
                // get_issuable_tokens_from_vault will return 0, and we will filter them out below

                // iterator returns tuple of (AccountId, Vault<T>),
                match Self::get_issuable_tokens_from_vault(&vault_id).ok() {
                    Some(issuable_tokens) => {
                        if !issuable_tokens.is_zero() {
                            Some((vault_id, issuable_tokens))
                        } else {
                            None
                        }
                    }
                    None => None,
                }
            })
            .collect::<Vec<(_, _)>>();

        vaults_with_issuable_tokens.sort_by(|a, b| b.1.amount().cmp(&a.1.amount()));
        Ok(vaults_with_issuable_tokens)
    }

    /// Get all vaults with non-zero issued (thus redeemable) tokens, ordered in descending order of this amount
    pub fn get_vaults_with_redeemable_tokens() -> Result<Vec<(DefaultVaultId<T>, Amount<T>)>, DispatchError> {
        // find all vault accounts with sufficient collateral
        let mut vaults_with_redeemable_tokens = Vaults::<T>::iter()
            .filter_map(|(vault_id, vault)| {
                let vault = Into::<RichVault<T>>::into(vault);
                let redeemable_tokens = vault.redeemable_tokens().ok()?;
                if !redeemable_tokens.is_zero() {
                    Some((vault_id, redeemable_tokens))
                } else {
                    None
                }
            })
            .collect::<Vec<(_, _)>>();

        vaults_with_redeemable_tokens.sort_by(|a, b| b.1.amount().cmp(&a.1.amount()));
        Ok(vaults_with_redeemable_tokens)
    }

    /// Get the amount of tokens a vault can issue
    pub fn get_issuable_tokens_from_vault(vault_id: &DefaultVaultId<T>) -> Result<Amount<T>, DispatchError> {
        let vault = Self::get_active_rich_vault_from_id(vault_id)?;
        // make sure the vault accepts new issue requests.
        // NOTE: get_vaults_with_issuable_tokens depends on this check
        if vault.data.status != VaultStatus::Active(true) {
            Ok(Amount::new(0u32.into(), vault_id.currencies.collateral))
        } else {
            vault.issuable_tokens()
        }
    }

    pub fn ensure_accepting_new_issues(vault_id: &DefaultVaultId<T>) -> Result<(), DispatchError> {
        let vault = Self::get_active_rich_vault_from_id(vault_id)?;
        ensure!(
            matches!(vault.data.status, VaultStatus::Active(true)),
            Error::<T>::VaultNotAcceptingIssueRequests
        );
        Ok(())
    }

    /// Get the amount of tokens issued by a vault
    pub fn get_to_be_issued_tokens_from_vault(vault_id: DefaultVaultId<T>) -> Result<Amount<T>, DispatchError> {
        let vault = Self::get_active_rich_vault_from_id(&vault_id)?;
        Ok(vault.to_be_issued_tokens())
    }

    /// Get the current collateralization of a vault
    pub fn get_collateralization_from_vault(
        vault_id: DefaultVaultId<T>,
        only_issued: bool,
    ) -> Result<UnsignedFixedPoint<T>, DispatchError> {
        let vault = Self::get_active_rich_vault_from_id(&vault_id)?;
        let collateral = vault.get_total_collateral()?;
        Self::get_collateralization_from_vault_and_collateral(vault_id, &collateral, only_issued)
    }

    pub fn get_collateralization_from_vault_and_collateral(
        vault_id: DefaultVaultId<T>,
        collateral: &Amount<T>,
        only_issued: bool,
    ) -> Result<UnsignedFixedPoint<T>, DispatchError> {
        let vault = Self::get_active_rich_vault_from_id(&vault_id)?;
        let issued_tokens = if only_issued {
            vault.issued_tokens()
        } else {
            vault.backed_tokens()?
        };

        ensure!(!issued_tokens.is_zero(), Error::<T>::NoTokensIssued);

        // convert the collateral to wrapped
        let collateral_in_wrapped = collateral.convert_to(vault_id.wrapped_currency())?;

        Self::get_collateralization(&collateral_in_wrapped, &issued_tokens)
    }

    /// Gets the minimum amount of collateral required for the given amount of btc
    /// with the current threshold and exchange rate
    ///
    /// # Arguments
    /// * `amount_wrapped` - the amount of wrapped
    /// * `currency_id` - the collateral currency
    pub fn get_required_collateral_for_wrapped(
        amount_wrapped: &Amount<T>,
        currency_id: CurrencyId<T>,
    ) -> Result<Amount<T>, DispatchError> {
        let currency_pair = VaultCurrencyPair {
            collateral: currency_id,
            wrapped: amount_wrapped.currency(),
        };
        let threshold = Self::secure_collateral_threshold(&currency_pair).ok_or(Error::<T>::ThresholdNotSet)?;
        let collateral =
            Self::get_required_collateral_for_wrapped_with_threshold(amount_wrapped, threshold, currency_id)?;
        Ok(collateral)
    }

    /// Get the amount of collateral required for the given vault to be at the
    /// current SecureCollateralThreshold with the current exchange rate
    pub fn get_required_collateral_for_vault(vault_id: DefaultVaultId<T>) -> Result<Amount<T>, DispatchError> {
        let vault = Self::get_active_rich_vault_from_id(&vault_id)?;
        let issued_tokens = vault.backed_tokens()?;

        let threshold = vault.get_secure_threshold()?;
        let required_collateral = Self::get_required_collateral_for_wrapped_with_threshold(
            &issued_tokens,
            threshold,
            vault_id.currencies.collateral,
        )?;

        Ok(required_collateral)
    }

    pub fn vault_exists(vault_id: &DefaultVaultId<T>) -> bool {
        Vaults::<T>::contains_key(vault_id)
    }

    pub fn compute_collateral(vault_id: &DefaultVaultId<T>) -> Result<Amount<T>, DispatchError> {
        let amount = ext::staking::compute_stake::<T>(vault_id, &vault_id.account_id)?;
        Ok(Amount::new(amount, vault_id.currencies.collateral))
    }

    pub fn compute_capacity(vault_id: &DefaultVaultId<T>) -> Result<Amount<T>, DispatchError> {
        let vault = Self::get_rich_vault_from_id(&vault_id)?;
        let amount = vault.get_vault_collateral()?;
        let threshold = vault.get_secure_threshold()?;
        Self::calculate_max_wrapped_from_collateral_for_threshold(&amount, vault_id.currencies.wrapped, threshold)
    }

    /// Private getters and setters

    fn get_collateral_ceiling(currency_pair: &DefaultVaultCurrencyPair<T>) -> Result<Amount<T>, DispatchError> {
        let ceiling_amount = SystemCollateralCeiling::<T>::get(currency_pair).ok_or(Error::<T>::CeilingNotSet)?;
        Ok(Amount::new(ceiling_amount, currency_pair.collateral))
    }

    #[cfg_attr(feature = "integration-tests", visibility::make(pub))]
    fn get_total_user_vault_collateral(
        currency_pair: &DefaultVaultCurrencyPair<T>,
    ) -> Result<Amount<T>, DispatchError> {
        Ok(Amount::new(
            TotalUserVaultCollateral::<T>::get(currency_pair),
            currency_pair.collateral,
        ))
    }

    #[cfg(feature = "integration-tests")]
    pub fn get_free_collateral(vault_id: &DefaultVaultId<T>) -> Result<Amount<T>, DispatchError> {
        let rich_vault = Self::get_rich_vault_from_id(vault_id)?;
        rich_vault.get_free_collateral()
    }

    fn get_rich_vault_from_id(vault_id: &DefaultVaultId<T>) -> Result<RichVault<T>, DispatchError> {
        Ok(Self::get_vault_from_id(vault_id)?.into())
    }

    /// Like get_rich_vault_from_id, but only returns active vaults
    fn get_active_rich_vault_from_id(vault_id: &DefaultVaultId<T>) -> Result<RichVault<T>, DispatchError> {
        Ok(Self::get_active_vault_from_id(vault_id)?.into())
    }

    pub fn get_liquidation_vault(currency_pair: &DefaultVaultCurrencyPair<T>) -> DefaultSystemVault<T> {
        if let Some(liquidation_vault) = LiquidationVault::<T>::get(currency_pair) {
            liquidation_vault
        } else {
            DefaultSystemVault::<T> {
                to_be_issued_tokens: 0u32.into(),
                issued_tokens: 0u32.into(),
                to_be_redeemed_tokens: 0u32.into(),
                collateral: 0u32.into(),
                currency_pair: currency_pair.clone(),
            }
        }
    }

    #[cfg_attr(feature = "integration-tests", visibility::make(pub))]
    fn get_rich_liquidation_vault(currency_pair: &DefaultVaultCurrencyPair<T>) -> RichSystemVault<T> {
        Self::get_liquidation_vault(currency_pair).into()
    }

    fn get_minimum_collateral_vault(currency_id: CurrencyId<T>) -> Amount<T> {
        let amount = MinimumCollateralVault::<T>::get(currency_id);
        Amount::new(amount, currency_id)
    }

    // Other helpers

    /// calculate the collateralization as a ratio of the issued tokens to the
    /// amount of provided collateral at the current exchange rate.
    fn get_collateralization(
        collateral_in_wrapped: &Amount<T>,
        issued_tokens: &Amount<T>,
    ) -> Result<UnsignedFixedPoint<T>, DispatchError> {
        collateral_in_wrapped.ratio(&issued_tokens)
    }

    #[cfg_attr(feature = "integration-tests", visibility::make(pub))]
    fn is_vault_below_certain_threshold(
        vault_id: &DefaultVaultId<T>,
        threshold: UnsignedFixedPoint<T>,
    ) -> Result<bool, DispatchError> {
        let vault = Self::get_rich_vault_from_id(&vault_id)?;

        // the current locked backing collateral by the vault
        let collateral = Self::get_backing_collateral(vault_id)?;

        Self::is_collateral_below_threshold(&collateral, &vault.issued_tokens(), threshold)
    }

    fn is_collateral_below_threshold(
        collateral: &Amount<T>,
        btc_amount: &Amount<T>,
        threshold: UnsignedFixedPoint<T>,
    ) -> Result<bool, DispatchError> {
        let max_tokens =
            Self::calculate_max_wrapped_from_collateral_for_threshold(collateral, btc_amount.currency(), threshold)?;
        // check if the max_tokens are below the issued tokens
        Ok(max_tokens.lt(&btc_amount)?)
    }

    /// Gets the minimum amount of collateral required for the given amount of btc
    /// with the current exchange rate and the given threshold. This function is the
    /// inverse of calculate_max_wrapped_from_collateral_for_threshold
    ///
    /// # Arguments
    /// * `amount_btc` - the amount of wrapped
    /// * `threshold` - the required secure collateral threshold
    fn get_required_collateral_for_wrapped_with_threshold(
        wrapped: &Amount<T>,
        threshold: UnsignedFixedPoint<T>,
        currency_id: CurrencyId<T>,
    ) -> Result<Amount<T>, DispatchError> {
        wrapped
            .checked_rounded_mul(&threshold, Rounding::Up)?
            .convert_to(currency_id)
    }

    fn calculate_max_wrapped_from_collateral_for_threshold(
        collateral: &Amount<T>,
        wrapped_currency: CurrencyId<T>,
        threshold: UnsignedFixedPoint<T>,
    ) -> Result<Amount<T>, DispatchError> {
        collateral.convert_to(wrapped_currency)?.checked_div(&threshold)
    }

    fn vault_to_be_backed_tokens(vault_id: &DefaultVaultId<T>) -> Result<Amount<T>, DispatchError> {
        let vault = Self::get_active_rich_vault_from_id(vault_id)?;
        vault.to_be_backed_tokens()
    }

    pub fn new_vault_deposit_address(
        vault_id: &DefaultVaultId<T>,
        secure_id: H256,
    ) -> Result<BtcAddress, DispatchError> {
        let mut vault = Self::get_active_rich_vault_from_id(vault_id)?;
        let btc_address = vault.new_deposit_address(secure_id)?;
        Ok(btc_address)
    }

    #[cfg(feature = "integration-tests")]
    pub fn collateral_integrity_check() {
        let griefing_currency = T::GetGriefingCollateralCurrencyId::get();
        for (vault_id, vault) in Vaults::<T>::iter().filter(|(_, vault)| matches!(vault.status, VaultStatus::Active(_)))
        {
            // check that there is enough griefing collateral
            let active_griefing = CurrencySource::<T>::ActiveReplaceCollateral(vault_id.clone())
                .current_balance(griefing_currency)
                .unwrap();
            let available_replace_collateral = CurrencySource::<T>::AvailableReplaceCollateral(vault_id.clone())
                .current_balance(griefing_currency)
                .unwrap();
            let total_replace_collateral = active_griefing + available_replace_collateral.clone();
            let reserved_balance = ext::currency::get_reserved_balance(griefing_currency, &vault_id.account_id);
            assert!(reserved_balance.ge(&total_replace_collateral).unwrap());

            if available_replace_collateral.is_zero() {
                // we can't have reserved collateral for to_be_replaced tokens if there are no to-be-replaced tokens
                assert!(vault.to_be_replaced_tokens.is_zero());
            }

            let liquidated_collateral = CurrencySource::<T>::LiquidatedCollateral(vault_id.clone())
                .current_balance(vault_id.collateral_currency())
                .unwrap();
            let backing_collateral = CurrencySource::<T>::Collateral(vault_id.clone())
                .current_balance(vault_id.collateral_currency())
                .unwrap()
                .checked_add(&liquidated_collateral)
                .unwrap();

            let reserved = ext::currency::get_reserved_balance(vault_id.collateral_currency(), &vault_id.account_id);
            assert!(reserved.ge(&backing_collateral).unwrap());

            let rich_vault: RichVault<T> = vault.clone().into();
            let expected_stake = if !vault.accepts_new_issues() {
                Amount::zero(vault_id.collateral_currency())
            } else {
                rich_vault
                    .get_total_collateral()
                    .unwrap()
                    .checked_div(&rich_vault.get_secure_threshold().unwrap())
                    .unwrap()
            };

            assert_eq!(ext::reward::get_stake::<T>(&vault_id).unwrap(), expected_stake.amount());
        }
    }

    #[cfg(feature = "integration-tests")]
    pub fn total_user_vault_collateral_integrity_check() {
        for (currency_pair, amount) in TotalUserVaultCollateral::<T>::iter() {
            let total_in_vaults = Vaults::<T>::iter()
                .filter_map(|(vault_id, vault)| {
                    if vault.id.currencies != currency_pair {
                        None
                    } else {
                        Some(Self::get_backing_collateral(&vault_id).unwrap().amount() + vault.liquidated_collateral)
                    }
                })
                .fold(0u32.into(), |acc: BalanceOf<T>, elem| acc + elem);
            let total = total_in_vaults
                + CurrencySource::<T>::LiquidationVault(currency_pair.clone())
                    .current_balance(currency_pair.collateral)
                    .unwrap()
                    .amount();
            assert_eq!(total, amount);
        }
    }
}