-
Notifications
You must be signed in to change notification settings - Fork 7
/
lib.rs
2118 lines (1871 loc) · 69.9 KB
/
lib.rs
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
//! # 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)]
#[cfg(test)]
extern crate mocktopus;
use codec::FullCodec;
use frame_support::{
dispatch::DispatchResult, ensure, sp_runtime, traits::Get, transactional, PalletId,
};
use frame_system::offchain::{SendTransactionTypes, SubmitTransaction};
#[cfg(test)]
use mocktopus::macros::mockable;
use sp_core::U256;
#[cfg(feature = "std")]
use sp_runtime::traits::AtLeast32BitUnsigned;
use sp_runtime::{traits::*, ArithmeticError, DispatchError, FixedPointOperand};
use sp_std::{
convert::{TryFrom, TryInto},
fmt::Debug,
vec::Vec,
};
pub use currency::Amount;
pub use default_weights::{SubstrateWeight, WeightInfo};
pub use pallet::*;
use primitives::{StellarPublicKeyRaw, VaultCurrencyPair};
use crate::types::{
BalanceOf, CurrencyId, DefaultSystemVault, DefaultVaultCurrencyPair, RichSystemVault,
RichVault, SignedInner, UnsignedFixedPoint,
};
#[doc(inline)]
pub use crate::types::{
CurrencySource, DefaultVault, DefaultVaultId, SystemVault, Vault, VaultId, VaultStatus,
};
mod ext;
pub mod types;
mod pool_staking_manager;
pub use pool_staking_manager::PoolManager;
#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
mod default_weights;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod mock;
// 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;
#[frame_support::pallet]
pub mod pallet {
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
use crate::types::DefaultVaultCurrencyPair;
use super::*;
#[pallet::pallet]
#[pallet::without_storage_info] // vault struct contains vec which doesn't implement MaxEncodedLen
pub struct Pallet<T>(_);
#[pallet::config]
pub trait Config:
frame_system::Config
+ SendTransactionTypes<Call<Self>>
+ oracle::Config
+ security::Config
+ currency::Config<Balance = BalanceOf<Self>>
+ fee::Config<UnsignedInner = BalanceOf<Self>, SignedInner = SignedInner<Self>>
{
/// 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>;
/// The primitive balance type.
type Balance: AtLeast32BitUnsigned
+ FixedPointOperand
+ Into<U256>
+ TryFrom<U256>
+ TryFrom<i64>
+ TryInto<i64>
+ MaybeSerializeDeserialize
+ FullCodec
+ Copy
+ Default
+ Debug
+ TypeInfo
+ MaxEncodedLen;
/// 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();
}
}
#[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())
}
/// Deposit collateral as a security against stealing the
/// Stellar assets locked with the caller.
///
/// # Arguments
/// * `amount` - the amount of extra collateral to lock
#[pallet::call_index(1)]
#[pallet::weight(<T as Config>::WeightInfo::deposit_collateral())]
#[transactional]
pub fn deposit_collateral(
origin: OriginFor<T>,
currency_pair: DefaultVaultCurrencyPair<T>,
#[pallet::compact] amount: BalanceOf<T>,
) -> DispatchResultWithPostInfo {
let account_id = ensure_signed(origin)?;
let vault_id =
VaultId::new(account_id, currency_pair.collateral, currency_pair.wrapped);
let vault = Self::get_active_rich_vault_from_id(&vault_id)?;
let amount = Amount::new(amount, currency_pair.collateral);
Self::try_deposit_collateral(&vault_id, &amount)?;
Self::deposit_event(Event::<T>::DepositCollateral {
vault_id: vault.id(),
new_collateral: amount.amount(),
total_collateral: vault.get_total_collateral()?.amount(),
free_collateral: vault.get_free_collateral()?.amount(),
});
Ok(().into())
}
/// Withdraws `amount` of the collateral from the amount locked by
/// the vault corresponding to the origin account
/// The collateral left after withdrawal must be more
/// (free or used in collateral issued tokens) than MinimumCollateralVault
/// and above the SecureCollateralThreshold. Collateral that is currently
/// being used to back issued tokens remains locked until the Vault
/// is used for a redeem request (full release can take multiple redeem requests).
///
/// # Arguments
/// * `amount` - the amount of collateral to withdraw
///
/// # Errors
/// * `VaultNotFound` - if no vault exists for the origin account
/// * `InsufficientCollateralAvailable` - if the vault does not own enough collateral
#[pallet::call_index(2)]
#[pallet::weight(<T as Config>::WeightInfo::withdraw_collateral())]
#[transactional]
pub fn withdraw_collateral(
origin: OriginFor<T>,
currency_pair: DefaultVaultCurrencyPair<T>,
#[pallet::compact] amount: BalanceOf<T>,
) -> DispatchResultWithPostInfo {
let account_id = ensure_signed(origin)?;
let vault_id =
VaultId::new(account_id, currency_pair.collateral, currency_pair.wrapped);
let vault = Self::get_rich_vault_from_id(&vault_id)?;
let amount = Amount::new(amount, currency_pair.collateral);
Self::try_withdraw_collateral(&vault_id, &amount)?;
Self::deposit_event(Event::<T>::WithdrawCollateral {
vault_id: vault.id(),
withdrawn_amount: amount.amount(),
total_collateral: vault.get_total_collateral()?.amount(),
});
Ok(().into())
}
/// Registers a new Stellar address for the vault.
///
/// # Arguments
/// * `public_key` - the Stellar public key of the vault to update
#[pallet::call_index(3)]
#[pallet::weight(<T as Config>::WeightInfo::register_public_key())]
#[transactional]
pub fn register_public_key(
origin: OriginFor<T>,
public_key: StellarPublicKeyRaw,
) -> DispatchResultWithPostInfo {
let account_id = ensure_signed(origin)?;
ensure!(
VaultStellarPublicKey::<T>::get(&account_id).is_none(),
Error::<T>::PublicKeyAlreadyRegistered
);
VaultStellarPublicKey::<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(4)]
#[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)?;
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(5)]
#[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)?;
Ok(().into())
}
#[pallet::call_index(6)]
#[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>::LiquidationCollateralThresholdNotSet)?;
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(7)]
#[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(8)]
#[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(9)]
#[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);
// We add each wrapped currency that has a secure threshold to the reward currencies of
// our staking pallet
// This will ensure that all rewards currencies are taking into account when
// collecting those rewards
ext::staking::add_reward_currency::<T>(currency_pair.wrapped)?;
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(10)]
#[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, 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(11)]
#[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, threshold);
Ok(())
}
/// Recover vault ID from a liquidated status.
///
/// # Arguments
/// * `currency_pair` - the currency pair to change
#[pallet::call_index(12)]
#[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)?;
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::call_index(13)]
#[pallet::weight(<T as Config>::WeightInfo::set_punishment_delay())]
#[transactional]
pub fn set_punishment_delay(
origin: OriginFor<T>,
punishment_delay: BlockNumberFor<T>,
) -> DispatchResult {
ensure_root(origin)?;
PunishmentDelay::<T>::put(punishment_delay);
Ok(())
}
}
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
RegisterVault {
vault_id: DefaultVaultId<T>,
collateral: BalanceOf<T>,
},
DepositCollateral {
vault_id: DefaultVaultId<T>,
new_collateral: BalanceOf<T>,
total_collateral: BalanceOf<T>,
free_collateral: BalanceOf<T>,
},
WithdrawCollateral {
vault_id: DefaultVaultId<T>,
withdrawn_amount: BalanceOf<T>,
total_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: StellarPublicKeyRaw,
},
RegisterAddress {
vault_id: DefaultVaultId<T>,
address: StellarPublicKeyRaw,
},
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>,
},
}
#[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 Max Nomination Ratio would be exceeded.
MaxNominationRatioViolation,
/// 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 Stellar public key is registered for the vault.
NoStellarPublicKey,
/// A Stellar 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
GlobalThresholdNotSet,
/// Threshold was not found for the given currency
LiquidationCollateralThresholdNotSet,
/// Threshold was not found for the given currency
PremiumRedeemThresholdNotSet,
/// Threshold was not found for the given currency
SecureCollateralThresholdNotSet,
/// 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 VaultStellarPublicKey<T: Config> =
StorageMap<_, Blake2_128Concat, T::AccountId, StellarPublicKeyRaw, 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::genesis_config]
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>)>,
}
impl<T: Config> Default for GenesisConfig<T> {
fn default() -> Self {
Self {
minimum_collateral_vault: Default::default(),
punishment_delay: Default::default(),
system_collateral_ceiling: Default::default(),
secure_collateral_threshold: Default::default(),
premium_redeem_threshold: Default::default(),
liquidation_collateral_threshold: Default::default(),
}
}
}
#[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);
}
}
}
}
// "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>::SecureCollateralThresholdNotSet
);
ensure!(
PremiumRedeemThreshold::<T>::contains_key(&vault_id.currencies),
Error::<T>::PremiumRedeemThresholdNotSet
);
ensure!(
LiquidationCollateralThreshold::<T>::contains_key(&vault_id.currencies),
Error::<T>::LiquidationCollateralThresholdNotSet
);
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_stellar_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, 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>::GlobalThresholdNotSet)?;
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_stellar_public_key(
account_id: &T::AccountId,
) -> Result<StellarPublicKeyRaw, DispatchError> {
VaultStellarPublicKey::<T>::get(account_id)
.ok_or_else(|| Error::<T>::NoStellarPublicKey.into())
}
pub fn get_vault_from_id(
vault_id: &DefaultVaultId<T>,
) -> Result<DefaultVault<T>, DispatchError> {
Vaults::<T>::get(vault_id).ok_or_else(|| Error::<T>::VaultNotFound.into())
}
pub fn get_backing_collateral(
vault_id: &DefaultVaultId<T>,
) -> Result<Amount<T>, DispatchError> {
let stake = ext::staking::total_current_stake::<T>(vault_id)?;
Ok(Amount::new(stake, vault_id.currencies.collateral))
}
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> {
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 {
// ensure the vault is active
let _vault = Self::get_active_rich_vault_from_id(vault_id)?;
// will fail if collateral ceiling exceeded
Self::try_increase_total_backing_collateral(&vault_id.currencies, amount)?;
// will fail if free_balance is insufficient
amount.lock_on(&vault_id.account_id)?;
// Deposit `amount` of stake in the pool
pool_staking_manager::PoolManager::deposit_collateral(
vault_id,
&vault_id.account_id,
&amount.clone(),
)?;
Ok(())
}
/// 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
pool_staking_manager::PoolManager::withdraw_collateral(
vault_id,
&vault_id.account_id,
amount,
None,
)?;
Ok(())
}
/// Withdraw an `amount` of collateral, ensuring that the vault is sufficiently
/// over-collateralized
///
/// # Arguments
/// * `vault_id` - the id of the vault
/// * `amount` - the amount of collateral
pub fn try_withdraw_collateral(
vault_id: &DefaultVaultId<T>,
amount: &Amount<T>,
) -> DispatchResult {
ensure!(
Self::is_allowed_to_withdraw_collateral(vault_id, amount)?,
Error::<T>::InsufficientCollateral
);
ensure!(
Self::is_max_nomination_ratio_preserved(vault_id, amount)?,
Error::<T>::MaxNominationRatioViolation
);
Self::force_withdraw_collateral(vault_id, amount)
}
pub fn is_max_nomination_ratio_preserved(
vault_id: &DefaultVaultId<T>,
amount: &Amount<T>,
) -> Result<bool, DispatchError> {
let vault_collateral = Self::compute_collateral(vault_id)?;
let backing_collateral = Self::get_backing_collateral(vault_id)?;
let current_nomination = backing_collateral.checked_sub(&vault_collateral)?;
let new_vault_collateral = vault_collateral.checked_sub(amount)?;
let max_nomination_after_withdrawal =
Self::get_max_nominatable_collateral(&new_vault_collateral, &vault_id.currencies)?;
current_nomination.le(&max_nomination_after_withdrawal)
}
/// 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: &Amount<T>,
) -> Result<bool, DispatchError> {
let vault = Self::get_rich_vault_from_id(vault_id)?;
let new_collateral = 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),