-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathlib.rs
992 lines (804 loc) · 31.1 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
#![cfg_attr(not(feature = "std"), no_std)]
/// Edit this file to define custom logic or remove it if it is not needed.
/// Learn more about FRAME and the core library of Substrate FRAME pallets:
/// <https://docs.substrate.io/v3/runtime/frame>
pub use pallet::*;
#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
mod curves;
pub mod traits;
mod types;
#[frame_support::pallet]
pub mod pallet {
use frame_support::{
dispatch::DispatchResult,
pallet_prelude::*,
traits::{
fungible::{Inspect as InspectFungible, MutateHold},
fungibles::{
metadata::{Inspect as FungiblesInspect, Mutate as FungiblesMetadata},
Create as CreateFungibles, Destroy as DestroyFungibles, Inspect as InspectFungibles,
Mutate as MutateFungibles,
},
tokens::{Fortitude, Precision as WithdrawalPrecision, Preservation, Provenance},
AccountTouch,
},
Hashable, Parameter,
};
use frame_system::pallet_prelude::*;
use parity_scale_codec::FullCodec;
use sp_arithmetic::ArithmeticError;
use sp_runtime::{
traits::{
Bounded, CheckedDiv, CheckedMul, One, SaturatedConversion, Saturating, StaticLookup, UniqueSaturatedInto,
Zero,
},
BoundedVec,
};
use sp_std::{
default::Default,
ops::{AddAssign, BitOrAssign, ShlAssign},
prelude::*,
vec::Vec,
};
use substrate_fixed::{
traits::{Fixed, FixedSigned, FixedUnsigned, ToFixed},
types::I9F23,
};
use crate::{
curves::{convert_to_fixed, BondingFunction, Curve, CurveInput},
traits::{FreezeAccounts, ResetTeam},
types::{Locks, PoolDetails, PoolManagingTeam, PoolStatus, TokenMeta},
};
type AccountIdLookupOf<T> = <<T as frame_system::Config>::Lookup as sp_runtime::traits::StaticLookup>::Source;
type AccountIdOf<T> = <T as frame_system::Config>::AccountId;
pub(crate) type DepositCurrencyBalanceOf<T> =
<<T as Config>::DepositCurrency as InspectFungible<<T as frame_system::Config>::AccountId>>::Balance;
pub(crate) type CollateralCurrenciesBalanceOf<T> =
<<T as Config>::CollateralCurrencies as InspectFungibles<<T as frame_system::Config>::AccountId>>::Balance;
pub(crate) type FungiblesBalanceOf<T> =
<<T as Config>::Fungibles as InspectFungibles<<T as frame_system::Config>::AccountId>>::Balance;
type FungiblesAssetIdOf<T> =
<<T as Config>::Fungibles as InspectFungibles<<T as frame_system::Config>::AccountId>>::AssetId;
type CollateralAssetIdOf<T> =
<<T as Config>::CollateralCurrencies as InspectFungibles<<T as frame_system::Config>::AccountId>>::AssetId;
type BoundedCurrencyVec<T> = BoundedVec<FungiblesAssetIdOf<T>, <T as Config>::MaxCurrencies>;
pub(crate) type CurrencyNameOf<T> = BoundedVec<u8, <T as Config>::MaxStringLength>;
pub(crate) type CurrencySymbolOf<T> = BoundedVec<u8, <T as Config>::MaxStringLength>;
pub(crate) type CurveParameterTypeOf<T> = <T as Config>::CurveParameterType;
pub(crate) type CurveParameterInputOf<T> = <T as Config>::CurveParameterInput;
pub(crate) type PoolDetailsOf<T> = PoolDetails<
<T as frame_system::Config>::AccountId,
Curve<CurveParameterTypeOf<T>>,
BoundedCurrencyVec<T>,
CollateralAssetIdOf<T>,
>;
pub(crate) type Precision = I9F23;
pub(crate) type PassiveSupply<T> = Vec<T>;
pub(crate) type TokenMetaOf<T> = TokenMeta<FungiblesBalanceOf<T>, CurrencyNameOf<T>, CurrencySymbolOf<T>>;
pub(crate) const LOG_TARGET: &str = "runtime::pallet-bonded-coins";
/// Configure the pallet by specifying the parameters and types on which it
/// depends.
#[pallet::config]
pub trait Config: frame_system::Config {
/// Because this pallet emits events, it depends on the runtime's
/// definition of an event.
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// The currency used for storage deposits.
type DepositCurrency: MutateHold<Self::AccountId, Reason = Self::RuntimeHoldReason>;
/// A fungibles trait implementation to interact with currencies which
/// can be used as collateral for minting bonded tokens.
type CollateralCurrencies: MutateFungibles<Self::AccountId>
+ AccountTouch<CollateralAssetIdOf<Self>, Self::AccountId>
+ FungiblesMetadata<Self::AccountId>;
/// Implementation of creating and managing new fungibles
type Fungibles: CreateFungibles<Self::AccountId, AssetId = Self::AssetId>
+ DestroyFungibles<Self::AccountId>
+ FungiblesMetadata<Self::AccountId>
+ FungiblesInspect<Self::AccountId>
+ MutateFungibles<Self::AccountId, Balance = CollateralCurrenciesBalanceOf<Self>>
+ FreezeAccounts<Self::AccountId, Self::AssetId>
+ ResetTeam<Self::AccountId>;
/// The maximum number of currencies allowed for a single pool.
#[pallet::constant]
type MaxCurrencies: Get<u32>;
/// The deposit required for each bonded currency.
#[pallet::constant]
type MaxStringLength: Get<u32>;
/// The deposit required for each bonded currency.
#[pallet::constant]
type DepositPerCurrency: Get<DepositCurrencyBalanceOf<Self>>;
/// The base deposit required to create a new pool, primarily to cover
/// the ED of the pool account.
#[pallet::constant]
type BaseDeposit: Get<DepositCurrencyBalanceOf<Self>>;
/// The origin for most permissionless and priviledged operations.
type DefaultOrigin: EnsureOrigin<Self::RuntimeOrigin, Success = Self::AccountId>;
/// The dedicated origin for creating new bonded currency pools
/// (typically permissionless).
type PoolCreateOrigin: EnsureOrigin<Self::RuntimeOrigin, Success = Self::AccountId>;
/// The origin for permissioned operations (force_* transactions).
type ForceOrigin: EnsureOrigin<Self::RuntimeOrigin>;
/// The type used for pool ids
type PoolId: Parameter + MaxEncodedLen + From<[u8; 32]> + Into<Self::AccountId>;
/// The type used for asset ids. This is the type of the bonded
/// currencies.
type AssetId: Parameter + Member + FullCodec + MaxEncodedLen + Saturating + One + Default;
type RuntimeHoldReason: From<HoldReason>;
/// The type used for the curve parameters.
type CurveParameterType: Parameter
+ Member
+ FixedSigned
+ MaxEncodedLen
+ PartialOrd<Precision>
+ From<Precision>;
type CurveParameterInput: Parameter + FixedUnsigned + MaxEncodedLen;
}
#[pallet::pallet]
pub struct Pallet<T>(_);
#[pallet::storage]
#[pallet::getter(fn pools)]
pub(crate) type Pools<T: Config> = StorageMap<_, Twox64Concat, T::PoolId, PoolDetailsOf<T>, OptionQuery>;
#[pallet::storage]
#[pallet::getter(fn nex_asset_id)]
pub(crate) type NextAssetId<T: Config> = StorageValue<_, FungiblesAssetIdOf<T>, ValueQuery>;
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
LockSet {
id: T::PoolId,
lock: Locks,
},
Unlocked {
id: T::PoolId,
},
PoolCreated {
id: T::PoolId,
},
/// A bonded token pool has been moved to refunding state.
RefundingStarted {
id: T::PoolId,
},
/// A bonded token pool has been moved to destroying state.
DestructionStarted {
id: T::PoolId,
},
/// Collateral distribution to bonded token holders has been completed
/// for this pool (no more tokens or no more collateral to distribute).
RefundComplete {
id: T::PoolId,
},
/// A bonded token pool has been fully destroyed and all collateral and
/// deposits have been refunded.
Destroyed {
id: T::PoolId,
},
/// The manager of a pool has been updated.
ManagerUpdated {
id: T::PoolId,
manager: Option<T::AccountId>,
},
}
#[pallet::error]
pub enum Error<T> {
/// The pool id is not currently registered.
PoolUnknown,
/// The pool has no associated bonded currency with the given index.
IndexOutOfBounds,
/// The pool does not hold collateral to be refunded, or has no
/// remaining supply of tokens to exchange. Call start_destroy to
/// intiate teardown.
NothingToRefund,
/// The user is not privileged to perform the requested operation.
NoPermission,
/// The pool is deactivated (i.e., in destroying or refunding state) and
/// not available for use.
PoolNotLive,
/// There are active accounts associated with this pool and thus it
/// cannot be destroyed at this point.
LivePool,
/// This operation can only be made when the pool is in refunding state.
NotRefunding,
/// The number of currencies linked to a pool exceeds the limit
/// parameter. Thrown by transactions that require specifying the number
/// of a pool's currencies in order to determine weight limits upfront.
CurrencyCount,
InvalidInput,
Internal,
Slippage,
}
#[pallet::composite_enum]
pub enum HoldReason {
Deposit,
}
#[pallet::call]
impl<T: Config> Pallet<T>
where
<CurveParameterTypeOf<T> as Fixed>::Bits: Copy + ToFixed + AddAssign + BitOrAssign + ShlAssign,
{
#[pallet::call_index(0)]
#[pallet::weight(Weight::from_parts(10_000, 0) + T::DbWeight::get().writes(1))]
pub fn create_pool(
origin: OriginFor<T>,
curve: CurveInput<CurveParameterInputOf<T>>,
collateral_id: CollateralAssetIdOf<T>,
currencies: BoundedVec<TokenMetaOf<T>, T::MaxCurrencies>,
denomination: u8,
transferable: bool,
) -> DispatchResult {
let who = T::PoolCreateOrigin::ensure_origin(origin)?;
let currency_length = currencies.len();
let checked_curve = curve.try_into().map_err(|_| Error::<T>::InvalidInput)?;
let current_asset_id = NextAssetId::<T>::get();
let (currency_ids, next_asset_id) = Self::generate_sequential_asset_ids(current_asset_id, currency_length)?;
let pool_id = T::PoolId::from(currency_ids.blake2_256());
// Todo: change that.
T::DepositCurrency::hold(
&T::RuntimeHoldReason::from(HoldReason::Deposit),
&who,
Self::calculate_pool_deposit(currency_length),
)?;
let pool_account = &pool_id.clone().into();
currencies
.into_iter()
.zip(currency_ids.iter())
.try_for_each(|(entry, asset_id)| -> DispatchResult {
let TokenMeta {
min_balance,
name,
symbol,
} = entry;
T::Fungibles::create(asset_id.clone(), pool_account.to_owned(), false, min_balance)?;
// set metadata for new asset class
T::Fungibles::set(
asset_id.to_owned(),
pool_account,
name.into_inner(),
symbol.into_inner(),
denomination,
)?;
Ok(())
})?;
// Touch the pool account in order to be able to transfer the collateral
// currency to it. This should also verify that the currency actually exists.
T::CollateralCurrencies::touch(collateral_id.clone(), pool_account, &who)?;
Pools::<T>::set(
&pool_id,
Some(PoolDetails::new(
who,
checked_curve,
collateral_id,
currency_ids,
transferable,
denomination,
)),
);
// update the storage for the next tx.
NextAssetId::<T>::set(next_asset_id);
Self::deposit_event(Event::PoolCreated { id: pool_id });
Ok(())
}
#[pallet::call_index(1)]
#[pallet::weight(Weight::from_parts(10_000, 0) + T::DbWeight::get().writes(1))]
pub fn reset_team(
origin: OriginFor<T>,
pool_id: T::PoolId,
team: PoolManagingTeam<AccountIdOf<T>>,
currency_idx: u32,
) -> DispatchResult {
let who = T::DefaultOrigin::ensure_origin(origin)?;
let pool_details = Pools::<T>::get(&pool_id).ok_or(Error::<T>::PoolUnknown)?;
ensure!(pool_details.state.is_live(), Error::<T>::PoolNotLive);
ensure!(pool_details.is_manager(&who), Error::<T>::NoPermission);
let asset_id = pool_details
.bonded_currencies
.get(currency_idx.saturated_into::<usize>())
.ok_or(Error::<T>::IndexOutOfBounds)?;
let pool_id_account = pool_id.into();
let PoolManagingTeam { freezer, admin } = team;
T::Fungibles::reset_team(
asset_id.to_owned(),
pool_id_account.clone(),
admin,
pool_id_account,
freezer,
)
}
#[pallet::call_index(2)]
#[pallet::weight(Weight::from_parts(10_000, 0) + T::DbWeight::get().writes(1))]
pub fn reset_manager(
origin: OriginFor<T>,
pool_id: T::PoolId,
new_manager: Option<AccountIdOf<T>>,
) -> DispatchResult {
let who = T::DefaultOrigin::ensure_origin(origin)?;
Pools::<T>::try_mutate(&pool_id, |maybe_entry| -> DispatchResult {
let entry = maybe_entry.as_mut().ok_or(Error::<T>::PoolUnknown)?;
ensure!(entry.is_manager(&who), Error::<T>::NoPermission);
entry.manager = new_manager.clone();
Ok(())
})?;
Self::deposit_event(Event::ManagerUpdated {
id: pool_id,
manager: new_manager,
});
Ok(())
}
#[pallet::call_index(3)]
#[pallet::weight(Weight::from_parts(10_000, 0) + T::DbWeight::get().writes(1))]
pub fn set_lock(origin: OriginFor<T>, pool_id: T::PoolId, lock: Locks) -> DispatchResult {
let who = T::DefaultOrigin::ensure_origin(origin)?;
Pools::<T>::try_mutate(&pool_id, |pool| -> DispatchResult {
let entry = pool.as_mut().ok_or(Error::<T>::PoolUnknown)?;
ensure!(entry.is_manager(&who), Error::<T>::NoPermission);
ensure!(entry.state.is_live(), Error::<T>::PoolNotLive);
entry.state = PoolStatus::Locked(lock.clone());
Ok(())
})?;
Self::deposit_event(Event::LockSet { id: pool_id, lock });
Ok(())
}
#[pallet::call_index(4)]
#[pallet::weight(Weight::from_parts(10_000, 0) + T::DbWeight::get().writes(1))]
pub fn unlock(origin: OriginFor<T>, pool_id: T::PoolId) -> DispatchResult {
let who = T::DefaultOrigin::ensure_origin(origin)?;
Pools::<T>::try_mutate(&pool_id, |pool| -> DispatchResult {
let entry = pool.as_mut().ok_or(Error::<T>::PoolUnknown)?;
ensure!(entry.is_manager(&who), Error::<T>::NoPermission);
ensure!(entry.state.is_live(), Error::<T>::PoolNotLive);
entry.state = PoolStatus::Active;
Ok(())
})?;
Self::deposit_event(Event::Unlocked { id: pool_id });
Ok(())
}
#[pallet::call_index(5)]
#[pallet::weight(Weight::from_parts(10_000, 0) + T::DbWeight::get().writes(1))]
pub fn mint_into(
origin: OriginFor<T>,
pool_id: T::PoolId,
currency_idx: u32,
beneficiary: AccountIdLookupOf<T>,
amount_to_mint: FungiblesBalanceOf<T>,
max_cost: CollateralCurrenciesBalanceOf<T>,
currency_count: u32,
) -> DispatchResult {
let who = T::DefaultOrigin::ensure_origin(origin)?;
let beneficiary = T::Lookup::lookup(beneficiary)?;
let pool_details = Pools::<T>::get(&pool_id).ok_or(Error::<T>::PoolUnknown)?;
ensure!(pool_details.can_mint(&who), Error::<T>::NoPermission);
ensure!(
Self::get_currencies_number(&pool_details) <= currency_count,
Error::<T>::CurrencyCount
);
let bonded_currencies = pool_details.bonded_currencies;
let currency_idx: usize = currency_idx.saturated_into();
let target_currency_id = bonded_currencies
.get(currency_idx)
.ok_or(Error::<T>::IndexOutOfBounds)?;
let (active_pre, passive) = Self::calculate_normalized_passive_issuance(
&bonded_currencies,
pool_details.denomination,
currency_idx,
)?;
let normalized_amount_to_mint =
convert_to_fixed::<T>(amount_to_mint.saturated_into::<u128>(), pool_details.denomination)?;
let active_post = active_pre
.checked_add(normalized_amount_to_mint)
.ok_or(ArithmeticError::Overflow)?;
let cost = Self::calculate_collateral(
active_pre,
active_post,
passive,
&pool_details.curve,
pool_details.collateral_id.clone(),
)?;
// fail if cost > max_cost
ensure!(cost <= max_cost, Error::<T>::Slippage);
// Transfer the collateral. We do not want to kill the minter, so this operation
// can fail if the account is being reaped.
T::CollateralCurrencies::transfer(
pool_details.collateral_id,
&who,
&pool_id.into(),
cost,
Preservation::Preserve,
)?;
T::Fungibles::mint_into(target_currency_id.clone(), &beneficiary, amount_to_mint)?;
if !pool_details.transferable {
T::Fungibles::freeze(target_currency_id, &beneficiary).map_err(|freeze_error| freeze_error.into())?;
}
Ok(())
}
#[pallet::call_index(6)]
#[pallet::weight(Weight::from_parts(10_000, 0) + T::DbWeight::get().writes(1))]
pub fn burn_into(
origin: OriginFor<T>,
pool_id: T::PoolId,
currency_idx: u32,
beneficiary: AccountIdLookupOf<T>,
amount_to_burn: FungiblesBalanceOf<T>,
min_return: CollateralCurrenciesBalanceOf<T>,
currency_count: u32,
) -> DispatchResult {
let who = T::DefaultOrigin::ensure_origin(origin)?;
let beneficiary = T::Lookup::lookup(beneficiary)?;
let pool_details = Pools::<T>::get(&pool_id).ok_or(Error::<T>::PoolUnknown)?;
ensure!(pool_details.can_burn(&who), Error::<T>::NoPermission);
ensure!(
Self::get_currencies_number(&pool_details) <= currency_count,
Error::<T>::CurrencyCount
);
let bonded_currencies = pool_details.bonded_currencies;
let currency_idx: usize = currency_idx.saturated_into();
let target_currency_id = bonded_currencies
.get(currency_idx)
.ok_or(Error::<T>::IndexOutOfBounds)?;
let (high, passive) = Self::calculate_normalized_passive_issuance(
&bonded_currencies,
pool_details.denomination,
currency_idx,
)?;
let normalized_amount_to_burn =
convert_to_fixed::<T>(amount_to_burn.saturated_into::<u128>(), pool_details.denomination)?;
let low = high
.checked_sub(normalized_amount_to_burn)
.ok_or(ArithmeticError::Underflow)?;
let collateral_return = Self::calculate_collateral(
low,
high,
passive,
&pool_details.curve,
pool_details.collateral_id.clone(),
)?;
ensure!(collateral_return >= min_return, Error::<T>::Slippage);
T::CollateralCurrencies::transfer(
pool_details.collateral_id,
&pool_id.into(),
&beneficiary,
collateral_return,
Preservation::Expendable,
)?;
// just remove any locks, if existing.
T::Fungibles::thaw(target_currency_id, &beneficiary).map_err(|freeze_error| freeze_error.into())?;
T::Fungibles::burn_from(
target_currency_id.clone(),
&beneficiary,
amount_to_burn,
WithdrawalPrecision::Exact,
Fortitude::Force,
)?;
if !pool_details.transferable {
// Restore locks.
T::Fungibles::freeze(target_currency_id, &beneficiary).map_err(|freeze_error| freeze_error.into())?;
}
Ok(())
}
#[pallet::call_index(7)]
#[pallet::weight(Weight::from_parts(10_000, 0) + T::DbWeight::get().writes(1))]
pub fn swap_into(_origin: OriginFor<T>) -> DispatchResult {
todo!()
}
#[pallet::call_index(8)]
#[pallet::weight(Weight::from_parts(10_000, 0) + T::DbWeight::get().writes(1))]
pub fn start_refund(origin: OriginFor<T>, pool_id: T::PoolId, currency_count: u32) -> DispatchResult {
let who = T::DefaultOrigin::ensure_origin(origin)?;
Self::do_start_refund(pool_id, currency_count, Some(&who))?;
Ok(())
}
#[pallet::call_index(9)]
#[pallet::weight(Weight::from_parts(10_000, 0) + T::DbWeight::get().writes(1))]
pub fn force_start_refund(origin: OriginFor<T>, pool_id: T::PoolId, currency_count: u32) -> DispatchResult {
T::ForceOrigin::ensure_origin(origin)?;
Self::do_start_refund(pool_id, currency_count, None)?;
Ok(())
}
#[pallet::call_index(10)]
#[pallet::weight(Weight::from_parts(10_000, 0) + T::DbWeight::get().writes(1))]
pub fn refund_account(
origin: OriginFor<T>,
pool_id: T::PoolId,
account: AccountIdLookupOf<T>,
asset_idx: u32,
currency_count: u32,
) -> DispatchResult {
T::DefaultOrigin::ensure_origin(origin)?;
let who = T::Lookup::lookup(account)?;
let pool_details = Pools::<T>::get(&pool_id).ok_or(Error::<T>::PoolUnknown)?;
ensure!(
Self::get_currencies_number(&pool_details) <= currency_count,
Error::<T>::CurrencyCount
);
ensure!(pool_details.state.is_refunding(), Error::<T>::NotRefunding);
// get asset id from linked assets vector
let asset_id: &FungiblesAssetIdOf<T> = pool_details
.bonded_currencies
.get(asset_idx.saturated_into::<usize>())
.ok_or(Error::<T>::IndexOutOfBounds)?;
let pool_account = pool_id.clone().into();
// Choosing total_balance over reducible_balance to ensure that all funds are
// distributed fairly; in case of any locks present on the pool account, this
// could lead to refunds failing to execute. This case would have to be
// resolved by governance, either by removing locks or force_destroying the
// pool.
let total_collateral_issuance =
T::CollateralCurrencies::total_balance(pool_details.collateral_id.clone(), &pool_account);
// nothing to distribute; refunding is complete, user should call start_destroy
ensure!(
total_collateral_issuance > CollateralCurrenciesBalanceOf::<T>::zero(),
Error::<T>::NothingToRefund
);
// remove any existing locks on the account prior to burning
T::Fungibles::thaw(asset_id, &who).map_err(|freeze_error| freeze_error.into())?;
// With amount = max_value(), this trait implementation burns the reducible
// balance on the account and returns the actual amount burnt
let burnt = T::Fungibles::burn_from(
asset_id.clone(),
&who,
Bounded::max_value(),
WithdrawalPrecision::BestEffort,
Fortitude::Force,
)?;
if burnt.is_zero() {
// no funds available to be burnt on account; nothing to do here
return Ok(());
}
let sum_of_issuances = pool_details
.bonded_currencies
.into_iter()
.fold(FungiblesBalanceOf::<T>::zero(), |sum, id| {
sum.saturating_add(T::Fungibles::total_issuance(id))
});
let amount = burnt
.checked_mul(&total_collateral_issuance)
.ok_or(ArithmeticError::Overflow)? // TODO: do we need a fallback if this fails?
.checked_div(&sum_of_issuances)
.ok_or(Error::<T>::NothingToRefund)?; // should be impossible - how would we be able to burn funds if the sum of total
// supplies is 0?
if amount.is_zero()
|| T::CollateralCurrencies::can_deposit(
pool_details.collateral_id.clone(),
&who,
amount,
Provenance::Extant,
)
.into_result()
.is_err()
{
// Funds are burnt but the collateral received is not sufficient to be deposited
// to the account. This is tolerated as otherwise we could have edge cases where
// it's impossible to refund at least some accounts.
return Ok(());
}
let transferred = T::CollateralCurrencies::transfer(
pool_details.collateral_id,
&pool_account,
&who,
amount,
Preservation::Expendable,
)?; // TODO: check edge cases around existential deposit
// if collateral or total supply drops to zero, refunding is complete
// -> emit event
if sum_of_issuances <= burnt || total_collateral_issuance <= transferred {
Self::deposit_event(Event::RefundComplete { id: pool_id });
}
Ok(())
}
#[pallet::call_index(11)]
#[pallet::weight(Weight::from_parts(10_000, 0) + T::DbWeight::get().writes(1))]
pub fn start_destroy(origin: OriginFor<T>, pool_id: T::PoolId, currency_count: u32) -> DispatchResult {
let who = T::DefaultOrigin::ensure_origin(origin)?;
Self::do_start_destroy_pool(pool_id, currency_count, false, Some(&who))?;
Ok(())
}
#[pallet::call_index(12)]
#[pallet::weight(Weight::from_parts(10_000, 0) + T::DbWeight::get().writes(1))]
pub fn force_start_destroy(origin: OriginFor<T>, pool_id: T::PoolId, currency_count: u32) -> DispatchResult {
T::ForceOrigin::ensure_origin(origin)?;
Self::do_start_destroy_pool(pool_id, currency_count, true, None)?;
Ok(())
}
#[pallet::call_index(13)]
#[pallet::weight(Weight::from_parts(10_000, 0) + T::DbWeight::get().writes(1))]
pub fn finish_destroy(origin: OriginFor<T>, pool_id: T::PoolId, currency_count: u32) -> DispatchResult {
T::DefaultOrigin::ensure_origin(origin)?;
let pool_details = Pools::<T>::get(&pool_id).ok_or(Error::<T>::PoolUnknown)?;
let n_currencies = Self::get_currencies_number(&pool_details);
ensure!(n_currencies <= currency_count, Error::<T>::CurrencyCount);
ensure!(pool_details.state.is_destroying(), Error::<T>::LivePool);
for asset_id in pool_details.bonded_currencies {
if T::Fungibles::asset_exists(asset_id.clone()) {
// This would fail with an LiveAsset error if there are any accounts left on any
// currency
T::Fungibles::finish_destroy(asset_id)?;
}
}
let pool_account = pool_id.clone().into();
let total_collateral_issuance =
T::CollateralCurrencies::total_balance(pool_details.collateral_id.clone(), &pool_account);
if total_collateral_issuance > CollateralCurrenciesBalanceOf::<T>::zero() {
T::CollateralCurrencies::transfer(
pool_details.collateral_id,
&pool_account,
&pool_details.owner,
total_collateral_issuance,
Preservation::Expendable,
)?;
}
Pools::<T>::remove(&pool_id);
T::DepositCurrency::release(
&T::RuntimeHoldReason::from(HoldReason::Deposit),
&pool_details.owner,
Self::calculate_pool_deposit(n_currencies),
WithdrawalPrecision::Exact,
)?;
Self::deposit_event(Event::Destroyed { id: pool_id });
Ok(())
}
}
impl<T: Config> Pallet<T>
where
<CurveParameterTypeOf<T> as Fixed>::Bits: Copy + ToFixed + AddAssign + BitOrAssign + ShlAssign,
{
fn calculate_collateral(
low: CurveParameterTypeOf<T>,
high: CurveParameterTypeOf<T>,
passive_supply: PassiveSupply<CurveParameterTypeOf<T>>,
curve: &Curve<CurveParameterTypeOf<T>>,
collateral_currency_id: CollateralAssetIdOf<T>,
) -> Result<CollateralCurrenciesBalanceOf<T>, ArithmeticError> {
let normalized_costs = curve.calculate_costs(low, high, passive_supply)?;
let collateral_denomination = 10u128
.checked_pow(T::CollateralCurrencies::decimals(collateral_currency_id).into())
.ok_or(ArithmeticError::Overflow)?;
let real_costs = normalized_costs
.checked_mul(CurveParameterTypeOf::<T>::from_num(collateral_denomination))
.ok_or(ArithmeticError::Overflow)?
// should never fail
.checked_to_num::<u128>()
.ok_or(ArithmeticError::Overflow)?
.saturated_into();
Ok(real_costs)
}
fn calculate_normalized_passive_issuance(
bonded_currencies: &[FungiblesAssetIdOf<T>],
denomination: u8,
currency_idx: usize,
) -> Result<(CurveParameterTypeOf<T>, PassiveSupply<CurveParameterTypeOf<T>>), DispatchError> {
let currencies_total_supply = bonded_currencies
.iter()
.map(|currency_id| T::Fungibles::total_issuance(currency_id.to_owned()))
.collect::<Vec<_>>();
let mut normalized_total_issuances = currencies_total_supply
.into_iter()
.map(|x| convert_to_fixed::<T>(x.saturated_into::<u128>(), denomination))
.collect::<Result<Vec<CurveParameterTypeOf<T>>, ArithmeticError>>()?;
let active_issuance = normalized_total_issuances.swap_remove(currency_idx);
Ok((active_issuance, normalized_total_issuances))
}
fn do_start_refund(
pool_id: T::PoolId,
max_currencies: u32,
maybe_check_manager: Option<&AccountIdOf<T>>,
) -> Result<u32, DispatchError> {
let pool_details = Pools::<T>::get(&pool_id).ok_or(Error::<T>::PoolUnknown)?;
let n_currencies = Self::get_currencies_number(&pool_details);
ensure!(n_currencies <= max_currencies, Error::<T>::CurrencyCount);
// refunding can only be triggered on a live pool
ensure!(pool_details.state.is_live(), Error::<T>::PoolNotLive);
if let Some(caller) = maybe_check_manager {
// TODO: should the owner be authorized as well?
ensure!(pool_details.is_manager(caller), Error::<T>::NoPermission);
}
let total_collateral_issuance =
T::CollateralCurrencies::total_balance(pool_details.collateral_id.clone(), &pool_id.clone().into());
// nothing to distribute
ensure!(
total_collateral_issuance > CollateralCurrenciesBalanceOf::<T>::zero(),
Error::<T>::NothingToRefund
);
// cloning here lets us avoid cloning the pool details later
let bonded_currencies = pool_details.bonded_currencies.clone();
let has_holders = bonded_currencies
.iter()
.any(|asset_id| T::Fungibles::total_issuance(asset_id.clone()) > FungiblesBalanceOf::<T>::zero());
// no token holders to refund
ensure!(has_holders, Error::<T>::NothingToRefund);
// switch pool state to refunding
let mut new_pool_details = pool_details;
new_pool_details.state.start_refund();
Pools::<T>::set(&pool_id, Some(new_pool_details));
// reset team on currencies to avoid unexpected burns etc.
let pool_account = pool_id.clone().into();
for asset_id in bonded_currencies {
T::Fungibles::reset_team(
asset_id,
pool_account.clone(),
pool_account.clone(),
pool_account.clone(),
pool_account.clone(),
)?;
}
Self::deposit_event(Event::RefundingStarted { id: pool_id });
Ok(n_currencies)
}
fn do_start_destroy_pool(
pool_id: T::PoolId,
max_currencies: u32,
force_skip_refund: bool,
maybe_check_manager: Option<&AccountIdOf<T>>,
) -> Result<u32, DispatchError> {
let pool_details = Pools::<T>::get(&pool_id).ok_or(Error::<T>::PoolUnknown)?;
let n_currencies = Self::get_currencies_number(&pool_details);
ensure!(n_currencies <= max_currencies, Error::<T>::CurrencyCount);
ensure!(
pool_details.state.is_live() || pool_details.state.is_refunding(),
Error::<T>::PoolNotLive
);
if let Some(caller) = maybe_check_manager {
// TODO: should this be permissionless if the pool is in refunding state?
ensure!(
pool_details.is_owner(caller) || pool_details.is_manager(caller),
Error::<T>::NoPermission
);
}
if !force_skip_refund {
let total_collateral_issuance =
T::CollateralCurrencies::total_balance(pool_details.collateral_id.clone(), &pool_id.clone().into());
if total_collateral_issuance > CollateralCurrenciesBalanceOf::<T>::zero() {
let has_holders = pool_details.bonded_currencies.iter().any(|asset_id| {
T::Fungibles::total_issuance(asset_id.clone()) > FungiblesBalanceOf::<T>::zero()
});
// destruction is only allowed when there are no holders or no collateral to
// distribute
ensure!(!has_holders, Error::<T>::LivePool);
}
}
// cloning the currency ids now lets us avoid cloning the entire pool_details
let bonded_currencies = pool_details.bonded_currencies.clone();
// switch pool state to destroying
let mut new_pool_details = pool_details;
new_pool_details.state.start_destroy();
Pools::<T>::set(&pool_id, Some(new_pool_details));
// emit this event before the destruction started events are emitted by assets
// deactivation
Self::deposit_event(Event::DestructionStarted { id: pool_id });
for asset_id in bonded_currencies {
// Governance or other pallets using the fungibles trait can in theory destroy
// an asset without this pallet knowing, so we check if it's still around
if T::Fungibles::asset_exists(asset_id.clone()) {
T::Fungibles::start_destroy(asset_id, None)?;
}
}
Ok(n_currencies)
}
fn generate_sequential_asset_ids(
mut start_id: T::AssetId,
count: usize,
) -> Result<(BoundedCurrencyVec<T>, T::AssetId), Error<T>> {
let mut currency_ids_vec = Vec::new();
for _ in 0..count {
currency_ids_vec.push(start_id.clone());
start_id.saturating_inc();
}
let currency_array = BoundedVec::<FungiblesAssetIdOf<T>, T::MaxCurrencies>::try_from(currency_ids_vec)
.map_err(|_| Error::<T>::Internal)?;
Ok((currency_array, start_id))
}
fn get_currencies_number(pool_details: &PoolDetailsOf<T>) -> u32 {
// bonded_currencies is a BoundedVec with maximum length MaxCurrencies, which is
// a u32; conversion to u32 must thus be lossless.
pool_details.bonded_currencies.len().saturated_into()
}
fn calculate_pool_deposit<N: UniqueSaturatedInto<DepositCurrencyBalanceOf<T>>>(
n_currencies: N,
) -> DepositCurrencyBalanceOf<T> {
T::BaseDeposit::get()
.saturating_add(T::DepositPerCurrency::get().saturating_mul(n_currencies.saturated_into()))
}
}
}