forked from ComposableFi/composable
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.rs
2107 lines (1817 loc) · 61.8 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
// Copyright 2021 Composable Finance Developer.
// This file is part of Composable Finance
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # Liquid staking pallet
//!
//! ## Overview
//!
//! This pallet manages the NPoS operations for relay chain asset.
#![cfg_attr(not(feature = "std"), no_std)]
use frame_support::traits::{tokens::Balance as BalanceT, Get};
use sp_runtime::{
traits::{One, Zero},
FixedPointNumber, FixedPointOperand,
};
pub use pallet::*;
use pallet_xcm_helper::ump::RewardDestination;
// mod benchmarking;
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
pub mod distribution;
// pub mod migrations;
pub mod types;
pub mod weights;
pub use weights::WeightInfo;
#[frame_support::pallet]
pub mod pallet {
use frame_support::{
dispatch::{DispatchResult, DispatchResultWithPostInfo},
ensure,
error::BadOrigin,
log,
pallet_prelude::*,
require_transactional,
storage::{storage_prefix, with_transaction},
traits::{
fungibles::{Inspect, Mutate},
tokens::{Fortitude, Precision, Preservation},
IsType, SortedMembers,
},
transactional, PalletId, StorageHasher,
};
use frame_system::{
ensure_signed,
pallet_prelude::{BlockNumberFor, OriginFor},
};
use pallet_xcm::ensure_response;
use parity_scale_codec::Encode;
use polkadot_parachain::primitives::Id as ParaId;
use sp_runtime::{
traits::{
AccountIdConversion, BlakeTwo256, BlockNumberProvider, CheckedDiv, CheckedSub,
Saturating, StaticLookup,
},
ArithmeticError, FixedPointNumber, TransactionOutcome,
};
use sp_std::{borrow::Borrow, boxed::Box, result::Result, vec::Vec};
use sp_trie::StorageProof;
use xcm::latest::prelude::*;
use crate::distribution::*;
use primitives::currency::CurrencyId;
pub type Balance = u128;
use pallet_xcm_helper::XcmHelper;
use super::{types::*, *};
pub const MAX_UNLOCKING_CHUNKS: usize = 32;
pub type AccountIdOf<T> = <T as frame_system::Config>::AccountId;
pub type AssetIdOf<T> =
<<T as Config>::Assets as Inspect<<T as frame_system::Config>::AccountId>>::AssetId;
pub type BalanceOf<T> =
<<T as Config>::Assets as Inspect<<T as frame_system::Config>::AccountId>>::Balance;
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
#[pallet::without_storage_info]
pub struct Pallet<T>(PhantomData<T>);
/// Utility type for managing upgrades/migrations.
#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)]
pub enum Versions {
V1,
V2,
V3,
}
#[pallet::config]
pub trait Config: frame_system::Config + pallet_utility::Config + pallet_xcm::Config {
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
type RuntimeOrigin: IsType<<Self as frame_system::Config>::RuntimeOrigin>
+ Into<Result<pallet_xcm::Origin, <Self as Config>::RuntimeOrigin>>;
type RuntimeCall: IsType<<Self as pallet_xcm::Config>::RuntimeCall> + From<Call<Self>>;
/// Assets for deposit/withdraw assets to/from pallet account
type Assets: Mutate<Self::AccountId, AssetId = CurrencyId, Balance = Balance>
+ Inspect<Self::AccountId, AssetId = CurrencyId, Balance = Balance>;
/// The origin which can do operation on relaychain using parachain's sovereign account
type RelayOrigin: EnsureOrigin<<Self as frame_system::Config>::RuntimeOrigin>;
/// The origin which can update liquid currency, staking currency and other parameters
type UpdateOrigin: EnsureOrigin<<Self as frame_system::Config>::RuntimeOrigin>;
/// Approved accouts which can call `withdraw_unbonded` and `settlement`
type Members: SortedMembers<Self::AccountId>;
/// The pallet id of liquid staking, keeps all the staking assets
#[pallet::constant]
type PalletId: Get<PalletId>;
/// Returns the parachain ID we are running with.
#[pallet::constant]
type SelfParaId: Get<ParaId>;
/// Derivative index list
#[pallet::constant]
type DerivativeIndexList: Get<Vec<DerivativeIndex>>;
/// Xcm fees
#[pallet::constant]
type XcmFees: Get<BalanceOf<Self>>;
/// MatchingPool fast unstake fee
#[pallet::constant]
type MatchingPoolFastUnstakeFee: Get<Rate>;
/// Staking currency
#[pallet::constant]
type StakingCurrency: Get<AssetIdOf<Self>>;
/// Liquid currency
#[pallet::constant]
type LiquidCurrency: Get<AssetIdOf<Self>>;
/// Minimum stake amount
#[pallet::constant]
type MinStake: Get<BalanceOf<Self>>;
/// Minimum unstake amount
#[pallet::constant]
type MinUnstake: Get<BalanceOf<Self>>;
/// Weight information
type WeightInfo: WeightInfo;
/// Number of unbond indexes for unlocking.
#[pallet::constant]
type BondingDuration: Get<EraIndex>;
/// The minimum active bond to become and maintain the role of a nominator.
#[pallet::constant]
type MinNominatorBond: Get<BalanceOf<Self>>;
/// Number of blocknumbers that each period contains.
/// SessionsPerEra * EpochDuration / MILLISECS_PER_BLOCK
#[pallet::constant]
type EraLength: Get<BlockNumberFor<Self>>;
#[pallet::constant]
type NumSlashingSpans: Get<u32>;
/// The relay's validation data provider
type RelayChainValidationDataProvider: ValidationDataProvider
+ BlockNumberProvider<BlockNumber = BlockNumberFor<Self>>;
/// To expose XCM helper functions
type XCM: XcmHelper<Self, BalanceOf<Self>, Self::AccountId>;
/// Current strategy for distributing assets to multi-accounts
type DistributionStrategy: DistributionStrategy<BalanceOf<Self>>;
/// Number of blocknumbers that do_matching after each era updated.
/// Need to do_bond before relaychain store npos solution
#[pallet::constant]
type ElectionSolutionStoredOffset: Get<BlockNumberFor<Self>>;
/// Who/where to send the protocol fees
#[pallet::constant]
type ProtocolFeeReceiver: Get<Self::AccountId>;
/// Decimal provider.
type Decimal: DecimalProvider<CurrencyId>;
/// The asset id for native currency.
#[pallet::constant]
type NativeCurrency: Get<AssetIdOf<Self>>;
}
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
/// The assets get staked successfully
Staked(T::AccountId, BalanceOf<T>),
/// The derivative get unstaked successfully
Unstaked(T::AccountId, BalanceOf<T>, BalanceOf<T>),
/// Staking ledger updated
StakingLedgerUpdated(DerivativeIndex, StakingLedger<T::AccountId, BalanceOf<T>>),
/// Sent staking.bond call to relaychain
Bonding(DerivativeIndex, T::AccountId, BalanceOf<T>, RewardDestination<T::AccountId>),
/// Sent staking.bond_extra call to relaychain
BondingExtra(DerivativeIndex, BalanceOf<T>),
/// Sent staking.unbond call to relaychain
Unbonding(DerivativeIndex, BalanceOf<T>),
/// Sent staking.rebond call to relaychain
Rebonding(DerivativeIndex, BalanceOf<T>),
/// Sent staking.withdraw_unbonded call to relaychain
WithdrawingUnbonded(DerivativeIndex, u32),
/// Sent staking.nominate call to relaychain
Nominating(DerivativeIndex, Vec<T::AccountId>),
/// Staking ledger's cap was updated
StakingLedgerCapUpdated(BalanceOf<T>),
/// Reserve_factor was updated
ReserveFactorUpdated(Ratio),
/// Exchange rate was updated
ExchangeRateUpdated(Rate),
/// Notification received
/// [multi_location, query_id, res]
NotificationReceived(Box<MultiLocation>, QueryId, Option<(u32, XcmError)>),
/// Claim user's unbonded staking assets
/// [account_id, amount]
ClaimedFor(T::AccountId, BalanceOf<T>),
/// New era
/// [era_index]
NewEra(EraIndex),
/// Matching stakes & unstakes for optimizing operations to be done
/// on relay chain
/// [bond_amount, rebond_amount, unbond_amount]
Matching(BalanceOf<T>, BalanceOf<T>, BalanceOf<T>),
/// Event emitted when the reserves are reduced
/// [receiver, reduced_amount]
ReservesReduced(T::AccountId, BalanceOf<T>),
/// Unstake cancelled
/// [account_id, amount, liquid_amount]
UnstakeCancelled(T::AccountId, BalanceOf<T>, BalanceOf<T>),
/// Commission rate was updated
CommissionRateUpdated(Rate),
/// Fast Unstake Matched
/// [unstaker, received_staking_amount, matched_liquid_amount, fee_in_liquid_currency]
FastUnstakeMatched(T::AccountId, BalanceOf<T>, BalanceOf<T>, BalanceOf<T>),
/// Incentive amount was updated
IncentiveUpdated(BalanceOf<T>),
/// Not the ideal staking ledger
NonIdealStakingLedger(DerivativeIndex),
RelaychainStorageProofKey(DerivativeIndex, Vec<u8>, T::AccountId),
SetStakingLedgerTry {
origin: T::AccountId,
derivative_index: DerivativeIndex,
staking_ledger: StakingLedger<T::AccountId, BalanceOf<T>>,
proof: Vec<Vec<u8>>,
},
OnInitializeHook {
relay_block_number: BlockNumberFor<T>,
era: u32,
},
SetMembers {
members: Vec<T::AccountId>,
},
}
#[pallet::error]
pub enum Error<T> {
/// Exchange rate is invalid.
InvalidExchangeRate,
/// The stake was below the minimum, `MinStake`.
StakeTooSmall,
/// The unstake was below the minimum, `MinUnstake`.
UnstakeTooSmall,
/// Invalid liquid currency
InvalidLiquidCurrency,
/// Invalid staking currency
InvalidStakingCurrency,
/// Invalid derivative index
InvalidDerivativeIndex,
/// Invalid staking ledger
InvalidStakingLedger,
/// Exceeded liquid currency's market cap
CapExceeded,
/// Invalid market cap
InvalidCap,
/// The factor should be bigger than 0% and smaller than 100%
InvalidFactor,
/// Nothing to claim yet
NothingToClaim,
/// Stash wasn't bonded yet
NotBonded,
/// Stash is already bonded.
AlreadyBonded,
/// Can not schedule more unlock chunks.
NoMoreChunks,
/// Staking ledger is locked due to mutation in notification_received
StakingLedgerLocked,
/// Not withdrawn unbonded yet
NotWithdrawn,
/// Cannot have a nominator role with value less than the minimum defined by
/// `MinNominatorBond`
InsufficientBond,
/// The merkle proof is invalid
InvalidProof,
/// No unlocking items
NoUnlockings,
/// Invalid commission rate
InvalidCommissionRate,
InvalidOrigin,
}
/// The exchange rate between relaychain native asset and the voucher.
#[pallet::storage]
#[pallet::getter(fn exchange_rate)]
#[allow(clippy::disallowed_types)]
pub type ExchangeRate<T: Config> = StorageValue<_, Rate, ValueQuery>;
/// The commission rate charge for staking total rewards.
#[pallet::storage]
#[pallet::getter(fn commission_rate)]
#[allow(clippy::disallowed_types)]
pub type CommissionRate<T: Config> = StorageValue<_, Rate, ValueQuery>;
/// ValidationData of previous block
///
/// This is needed since validation data from cumulus_pallet_parachain_system
/// will be updated in set_validation_data Inherent which happens before external
/// extrinsics
#[pallet::storage]
#[pallet::getter(fn validation_data)]
pub type ValidationData<T: Config> = StorageValue<_, PersistedValidationData, OptionQuery>;
/// Fraction of reward currently set aside for reserves.
#[pallet::storage]
#[pallet::getter(fn reserve_factor)]
#[allow(clippy::disallowed_types)]
pub type ReserveFactor<T: Config> = StorageValue<_, Ratio, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn total_reserves)]
#[allow(clippy::disallowed_types)]
pub type TotalReserves<T: Config> = StorageValue<_, BalanceOf<T>, ValueQuery>;
/// Store total stake amount and unstake amount in each era,
/// And will update when stake/unstake occurred.
#[pallet::storage]
#[pallet::getter(fn matching_pool)]
#[allow(clippy::disallowed_types)]
pub type MatchingPool<T: Config> = StorageValue<_, MatchingLedger<BalanceOf<T>>, ValueQuery>;
/// Staking ledger's cap
#[pallet::storage]
#[pallet::getter(fn staking_ledger_cap)]
#[allow(clippy::disallowed_types)]
pub type StakingLedgerCap<T: Config> = StorageValue<_, BalanceOf<T>, ValueQuery>;
/// Flying & failed xcm requests
#[pallet::storage]
#[pallet::getter(fn xcm_request)]
pub type XcmRequests<T> = StorageMap<_, Blake2_128Concat, QueryId, XcmRequest<T>, OptionQuery>;
/// Users' fast unstake requests in liquid currency
#[pallet::storage]
#[pallet::getter(fn fast_unstake_requests)]
#[allow(clippy::disallowed_types)]
pub type FastUnstakeRequests<T: Config> =
StorageMap<_, Blake2_128Concat, T::AccountId, BalanceOf<T>, ValueQuery>;
/// Current era index
/// Users can come to claim their unbonded staking assets back once this value arrived
/// at certain height decided by `BondingDuration` and `EraLength`
#[pallet::storage]
#[pallet::getter(fn current_era)]
#[allow(clippy::disallowed_types)]
pub type CurrentEra<T: Config> = StorageValue<_, EraIndex, ValueQuery>;
/// Current era's start relaychain block
#[pallet::storage]
#[pallet::getter(fn era_start_block)]
#[allow(clippy::disallowed_types)]
pub type EraStartBlock<T: Config> = StorageValue<_, BlockNumberFor<T>, ValueQuery>;
/// Unbonding requests to be handled after arriving at target era
#[pallet::storage]
#[pallet::getter(fn unlockings)]
pub type Unlockings<T: Config> =
StorageMap<_, Blake2_128Concat, T::AccountId, Vec<UnlockChunk<BalanceOf<T>>>, OptionQuery>;
#[pallet::storage]
#[pallet::getter(fn members)]
#[allow(clippy::disallowed_types)]
pub type Members<T: Config> = StorageValue<_, Vec<T::AccountId>, ValueQuery>;
/// Platform's staking ledgers
#[pallet::storage]
#[pallet::getter(fn staking_ledger)]
pub type StakingLedgers<T: Config> = StorageMap<
_,
Blake2_128Concat,
DerivativeIndex,
StakingLedger<T::AccountId, BalanceOf<T>>,
OptionQuery,
>;
/// Set to true if staking ledger has been modified in this block
#[pallet::storage]
#[pallet::getter(fn is_updated)]
#[allow(clippy::disallowed_types)]
pub type IsUpdated<T: Config> = StorageMap<_, Twox64Concat, DerivativeIndex, bool, ValueQuery>;
/// DefaultVersion is using for initialize the StorageVersion
#[pallet::type_value]
pub(super) fn DefaultVersion() -> Versions {
Versions::V2
}
/// Storage version of the pallet.
#[pallet::storage]
#[allow(clippy::disallowed_types)]
pub(crate) type StorageVersion<T: Config> =
StorageValue<_, Versions, ValueQuery, DefaultVersion>;
/// Set to true if already do matching in current era
/// clear after arriving at next era
#[pallet::storage]
#[pallet::getter(fn is_matched)]
#[allow(clippy::disallowed_types)]
pub type IsMatched<T: Config> = StorageValue<_, bool, ValueQuery>;
/// Incentive for users who successfully update era/ledger
#[pallet::storage]
#[pallet::getter(fn incentive)]
#[allow(clippy::disallowed_types)]
pub type Incentive<T: Config> = StorageValue<_, BalanceOf<T>, ValueQuery>;
#[derive(Default)]
#[pallet::genesis_config]
pub struct GenesisConfig {
pub exchange_rate: Rate,
pub reserve_factor: Ratio,
}
#[pallet::genesis_build]
impl<T: Config> GenesisBuild<T> for GenesisConfig {
fn build(&self) {
ExchangeRate::<T>::put(self.exchange_rate);
ReserveFactor::<T>::put(self.reserve_factor);
}
}
#[pallet::call]
impl<T: Config> Pallet<T> {
/// Put assets under staking, the native assets will be transferred to the account
/// owned by the pallet, user receive derivative in return, such derivative can be
/// further used as collateral for lending.
///
/// - `amount`: the amount of staking assets
#[pallet::call_index(0)]
#[pallet::weight(<T as Config>::WeightInfo::stake())]
#[transactional]
pub fn stake(
origin: OriginFor<T>,
#[pallet::compact] amount: BalanceOf<T>,
) -> DispatchResultWithPostInfo {
let who = ensure_signed(origin)?;
ensure!(amount >= T::MinStake::get(), Error::<T>::StakeTooSmall);
let reserves = Self::reserve_factor().mul_floor(amount);
let xcm_fees = T::XcmFees::get();
let amount = amount.checked_sub(xcm_fees).ok_or(ArithmeticError::Underflow)?;
use frame_support::traits::tokens::Preservation;
let keep_alive = false;
let keep_alive =
if keep_alive { Preservation::Preserve } else { Preservation::Expendable };
T::Assets::transfer(
Self::staking_currency()?,
&who,
&Self::account_id(),
amount,
keep_alive,
)?;
T::XCM::add_xcm_fees(&who, xcm_fees)?;
let amount = amount.checked_sub(reserves).ok_or(ArithmeticError::Underflow)?;
let liquid_amount =
Self::staking_to_liquid(amount).ok_or(Error::<T>::InvalidExchangeRate)?;
let liquid_currency = Self::liquid_currency()?;
Self::ensure_market_cap(amount)?;
T::Assets::mint_into(liquid_currency, &who, liquid_amount)?;
log::trace!(
target: "liquidStaking::stake",
"stake_amount: {:?}, liquid_amount: {:?}, reserved: {:?}",
&amount,
&liquid_amount,
&reserves
);
MatchingPool::<T>::try_mutate(|p| -> DispatchResult { p.add_stake_amount(amount) })?;
TotalReserves::<T>::try_mutate(|b| -> DispatchResult {
*b = b.checked_add(reserves).ok_or(ArithmeticError::Overflow)?;
Ok(())
})?;
Self::deposit_event(Event::<T>::Staked(who, amount));
Ok(().into())
}
/// Unstake by exchange derivative for assets, the assets will not be available immediately.
/// Instead, the request is recorded and pending for the nomination accounts on relaychain
/// chain to do the `unbond` operation.
///
/// - `amount`: the amount of derivative
#[pallet::call_index(1)]
#[pallet::weight(<T as Config>::WeightInfo::unstake())]
#[transactional]
pub fn unstake(
origin: OriginFor<T>,
#[pallet::compact] liquid_amount: BalanceOf<T>,
unstake_provider: UnstakeProvider,
) -> DispatchResultWithPostInfo {
let who = ensure_signed(origin)?;
ensure!(liquid_amount >= T::MinUnstake::get(), Error::<T>::UnstakeTooSmall);
if unstake_provider.is_matching_pool() {
use frame_support::traits::tokens::{Fortitude, Preservation};
let keep_alive = false;
let keep_alive =
if keep_alive { Preservation::Preserve } else { Preservation::Expendable };
FastUnstakeRequests::<T>::try_mutate(&who, |b| -> DispatchResult {
let balance = T::Assets::reducible_balance(
Self::liquid_currency()?,
&who,
keep_alive,
Fortitude::Polite,
);
*b = b.saturating_add(liquid_amount).min(balance);
Ok(())
})?;
return Ok(().into())
}
let amount =
Self::liquid_to_staking(liquid_amount).ok_or(Error::<T>::InvalidExchangeRate)?;
let unlockings_key = who.clone();
Unlockings::<T>::try_mutate(&unlockings_key, |b| -> DispatchResult {
let mut chunks = b.take().unwrap_or_default();
let target_era = Self::target_era();
if let Some(mut chunk) = chunks.last_mut().filter(|chunk| chunk.era == target_era) {
chunk.value = chunk.value.saturating_add(amount);
} else {
chunks.push(UnlockChunk { value: amount, era: target_era });
}
ensure!(chunks.len() <= MAX_UNLOCKING_CHUNKS, Error::<T>::NoMoreChunks);
*b = Some(chunks);
Ok(())
})?;
T::Assets::burn_from(
Self::liquid_currency()?,
&who,
liquid_amount,
Precision::Exact,
Fortitude::Polite,
)?;
MatchingPool::<T>::try_mutate(|p| p.add_unstake_amount(amount))?;
log::trace!(
target: "liquidStaking::unstake",
"unstake_amount: {:?}, liquid_amount: {:?}",
&amount,
&liquid_amount,
);
Self::deposit_event(Event::<T>::Unstaked(who, liquid_amount, amount));
Ok(().into())
}
/// Update insurance pool's reserve_factor
#[pallet::call_index(2)]
#[pallet::weight(<T as Config>::WeightInfo::update_reserve_factor())]
#[transactional]
pub fn update_reserve_factor(
origin: OriginFor<T>,
reserve_factor: Ratio,
) -> DispatchResultWithPostInfo {
T::UpdateOrigin::ensure_origin(origin)?;
ensure!(
reserve_factor > Ratio::zero() && reserve_factor < Ratio::one(),
Error::<T>::InvalidFactor,
);
log::trace!(
target: "liquidStaking::update_reserve_factor",
"reserve_factor: {:?}",
&reserve_factor,
);
ReserveFactor::<T>::mutate(|v| *v = reserve_factor);
Self::deposit_event(Event::<T>::ReserveFactorUpdated(reserve_factor));
Ok(().into())
}
/// Update ledger's max bonded cap
#[pallet::call_index(3)]
#[pallet::weight(<T as Config>::WeightInfo::update_staking_ledger_cap())]
#[transactional]
pub fn update_staking_ledger_cap(
origin: OriginFor<T>,
#[pallet::compact] cap: BalanceOf<T>,
) -> DispatchResultWithPostInfo {
T::UpdateOrigin::ensure_origin(origin)?;
ensure!(!cap.is_zero(), Error::<T>::InvalidCap);
log::trace!(
target: "liquidStaking::update_staking_ledger_cap",
"cap: {:?}",
&cap,
);
StakingLedgerCap::<T>::mutate(|v| *v = cap);
Self::deposit_event(Event::<T>::StakingLedgerCapUpdated(cap));
Ok(().into())
}
/// Bond on relaychain via xcm.transact
#[pallet::call_index(4)]
#[pallet::weight(<T as Config>::WeightInfo::bond())]
#[transactional]
pub fn bond(
origin: OriginFor<T>,
derivative_index: DerivativeIndex,
#[pallet::compact] amount: BalanceOf<T>,
payee: RewardDestination<T::AccountId>,
) -> DispatchResult {
T::RelayOrigin::ensure_origin(origin)?;
Self::do_bond(derivative_index, amount, payee)?;
Ok(())
}
/// Bond_extra on relaychain via xcm.transact
#[pallet::call_index(5)]
#[pallet::weight(<T as Config>::WeightInfo::bond_extra())]
#[transactional]
pub fn bond_extra(
origin: OriginFor<T>,
derivative_index: DerivativeIndex,
#[pallet::compact] amount: BalanceOf<T>,
) -> DispatchResult {
T::RelayOrigin::ensure_origin(origin)?;
Self::do_bond_extra(derivative_index, amount)?;
Ok(())
}
/// Unbond on relaychain via xcm.transact
#[pallet::call_index(6)]
#[pallet::weight(<T as Config>::WeightInfo::unbond())]
#[transactional]
pub fn unbond(
origin: OriginFor<T>,
derivative_index: DerivativeIndex,
#[pallet::compact] amount: BalanceOf<T>,
) -> DispatchResult {
T::RelayOrigin::ensure_origin(origin)?;
Self::do_unbond(derivative_index, amount)?;
Ok(())
}
/// Rebond on relaychain via xcm.transact
#[pallet::call_index(7)]
#[pallet::weight(<T as Config>::WeightInfo::rebond())]
#[transactional]
pub fn rebond(
origin: OriginFor<T>,
derivative_index: DerivativeIndex,
#[pallet::compact] amount: BalanceOf<T>,
) -> DispatchResult {
T::RelayOrigin::ensure_origin(origin)?;
Self::do_rebond(derivative_index, amount)?;
Ok(())
}
/// Withdraw unbonded on relaychain via xcm.transact
#[pallet::call_index(8)]
#[pallet::weight(<T as Config>::WeightInfo::withdraw_unbonded())]
#[transactional]
pub fn withdraw_unbonded(
origin: OriginFor<T>,
derivative_index: DerivativeIndex,
num_slashing_spans: u32,
) -> DispatchResult {
Self::ensure_origin(origin)?;
Self::do_withdraw_unbonded(derivative_index, num_slashing_spans)?;
Ok(())
}
/// Nominate on relaychain via xcm.transact
#[pallet::call_index(9)]
#[pallet::weight(<T as Config>::WeightInfo::nominate())]
#[transactional]
pub fn nominate(
origin: OriginFor<T>,
derivative_index: DerivativeIndex,
targets: Vec<T::AccountId>,
) -> DispatchResult {
Self::ensure_origin(origin)?;
Self::do_nominate(derivative_index, targets)?;
Ok(())
}
/// Internal call which is expected to be triggered only by xcm instruction
#[pallet::call_index(10)]
#[pallet::weight(<T as Config>::WeightInfo::notification_received())]
#[transactional]
pub fn notification_received(
origin: OriginFor<T>,
query_id: QueryId,
response: Response,
) -> DispatchResultWithPostInfo {
let responder = ensure_response(<T as Config>::RuntimeOrigin::from(origin.clone()))
.or_else(|_| {
T::UpdateOrigin::ensure_origin(origin).map(|_| MultiLocation::here())
})?;
if let Response::ExecutionResult(res) = response {
Self::deposit_event(Event::<T>::NotificationReceived(
Box::new(responder),
query_id,
res,
));
if let Some(request) = Self::xcm_request(query_id) {
Self::do_notification_received(query_id, request, res)?;
}
Self::deposit_event(Event::<T>::NotificationReceived(
Box::new(responder),
query_id,
res,
));
}
Ok(().into())
}
/// Claim assets back when current era index arrived
/// at target era
#[pallet::call_index(11)]
#[pallet::weight(<T as Config>::WeightInfo::claim_for())]
#[transactional]
pub fn claim_for(
origin: OriginFor<T>,
dest: <T::Lookup as StaticLookup>::Source,
) -> DispatchResultWithPostInfo {
Self::ensure_origin(origin)?;
let who = T::Lookup::lookup(dest)?;
let current_era = Self::current_era();
Unlockings::<T>::try_mutate_exists(&who, |b| -> DispatchResult {
let mut amount: BalanceOf<T> = Zero::zero();
let chunks = b.as_mut().ok_or(Error::<T>::NoUnlockings)?;
chunks.retain(|chunk| {
if chunk.era > current_era {
true
} else {
amount += chunk.value;
false
}
});
let total_unclaimed = Self::get_total_unclaimed(Self::staking_currency()?);
log::trace!(
target: "liquidStaking::claim_for",
"current_era: {:?}, beneficiary: {:?}, total_unclaimed: {:?}, amount: {:?}",
¤t_era,
&who,
&total_unclaimed,
amount
);
if amount.is_zero() {
return Err(Error::<T>::NothingToClaim.into())
}
if total_unclaimed < amount {
return Err(Error::<T>::NotWithdrawn.into())
}
Self::do_claim_for(&who, amount)?;
if chunks.is_empty() {
*b = None;
}
Self::deposit_event(Event::<T>::ClaimedFor(who.clone(), amount));
Ok(())
})?;
Ok(().into())
}
/// Force set era start block
#[pallet::call_index(12)]
#[pallet::weight(<T as Config>::WeightInfo::force_set_era_start_block())]
#[transactional]
pub fn force_set_era_start_block(
origin: OriginFor<T>,
block_number: BlockNumberFor<T>,
) -> DispatchResult {
T::UpdateOrigin::ensure_origin(origin)?;
EraStartBlock::<T>::put(block_number);
Ok(())
}
/// Force set current era
#[pallet::call_index(13)]
#[pallet::weight(<T as Config>::WeightInfo::force_set_current_era())]
#[transactional]
pub fn force_set_current_era(origin: OriginFor<T>, era: EraIndex) -> DispatchResult {
T::UpdateOrigin::ensure_origin(origin)?;
IsMatched::<T>::put(false);
CurrentEra::<T>::put(era);
Ok(())
}
/// Force advance era
#[pallet::call_index(14)]
#[pallet::weight(<T as Config>::WeightInfo::force_advance_era())]
#[transactional]
pub fn force_advance_era(
origin: OriginFor<T>,
offset: EraIndex,
) -> DispatchResultWithPostInfo {
T::UpdateOrigin::ensure_origin(origin)?;
Self::do_advance_era(offset)?;
Ok(().into())
}
/// Force matching
#[pallet::call_index(15)]
#[pallet::weight(<T as Config>::WeightInfo::force_matching())]
#[transactional]
pub fn force_matching(origin: OriginFor<T>) -> DispatchResultWithPostInfo {
T::UpdateOrigin::ensure_origin(origin)?;
Self::do_matching()?;
Ok(().into())
}
/// Force set staking_ledger
#[pallet::call_index(16)]
#[pallet::weight(<T as Config>::WeightInfo::force_set_staking_ledger())]
#[transactional]
pub fn force_set_staking_ledger(
origin: OriginFor<T>,
derivative_index: DerivativeIndex,
staking_ledger: StakingLedger<T::AccountId, BalanceOf<T>>,
) -> DispatchResultWithPostInfo {
T::UpdateOrigin::ensure_origin(origin)?;
Self::do_update_ledger(derivative_index, |ledger| {
ensure!(
!Self::is_updated(derivative_index) &&
XcmRequests::<T>::iter().count().is_zero(),
Error::<T>::StakingLedgerLocked
);
*ledger = staking_ledger;
Ok(())
})?;
Ok(().into())
}
/// Set current era by providing storage proof
#[pallet::call_index(17)]
#[pallet::weight(<T as Config>::WeightInfo::force_set_current_era())]
#[transactional]
pub fn set_current_era(
origin: OriginFor<T>,
era: EraIndex,
proof: Vec<Vec<u8>>,
) -> DispatchResultWithPostInfo {
let who = ensure_signed(origin)?;
let offset = era.saturating_sub(Self::current_era());
let key = Self::get_current_era_key();
let value = era.encode();
ensure!(Self::verify_merkle_proof(key, value, proof), Error::<T>::InvalidProof);
Self::do_advance_era(offset)?;
if !offset.is_zero() {
use frame_support::traits::tokens::Preservation;
let keep_alive = false;
let keep_alive =
if keep_alive { Preservation::Preserve } else { Preservation::Expendable };
let _ = T::Assets::transfer(
T::NativeCurrency::get(),
&Self::account_id(),
&who,
Self::incentive(),
keep_alive,
);
}
Ok(().into())
}
/// Set staking_ledger by providing storage proof
#[pallet::call_index(18)]
#[pallet::weight(<T as Config>::WeightInfo::force_set_staking_ledger())]
#[transactional]
pub fn set_staking_ledger(
origin: OriginFor<T>,
derivative_index: DerivativeIndex,
staking_ledger: StakingLedger<T::AccountId, BalanceOf<T>>,
proof: Vec<Vec<u8>>,
) -> DispatchResultWithPostInfo {
let who = ensure_signed(origin)?;
Self::deposit_event(Event::<T>::SetStakingLedgerTry {
origin: who.clone(),
derivative_index,
staking_ledger: staking_ledger.clone(),
proof: proof.clone(),
});
Self::do_update_ledger(derivative_index, |ledger| {
ensure!(!Self::is_updated(derivative_index), Error::<T>::StakingLedgerLocked);
let requests = XcmRequests::<T>::iter().count();
if staking_ledger.total < ledger.total ||
staking_ledger.active < ledger.active ||
staking_ledger.unlocking != ledger.unlocking ||
!requests.is_zero()
{
log::trace!(
target: "liquidStaking::set_staking_ledger::invalidStakingLedger",
"index: {:?}, staking_ledger: {:?}, xcm_request: {:?}",
&derivative_index,
&staking_ledger,
requests,
);
Self::deposit_event(Event::<T>::NonIdealStakingLedger(derivative_index));
}
let key = Self::get_staking_ledger_key(derivative_index);
let value = staking_ledger.encode();
ensure!(Self::verify_merkle_proof(key, value, proof), Error::<T>::InvalidProof);
let rewards = staking_ledger.total.saturating_sub(ledger.total);
let inflate_liquid_amount = Self::get_inflate_liquid_amount(rewards)?;
if !inflate_liquid_amount.is_zero() {
T::Assets::mint_into(
Self::liquid_currency()?,
&T::ProtocolFeeReceiver::get(),
inflate_liquid_amount,
)?;
}
log::trace!(
target: "liquidStaking::set_staking_ledger",
"index: {:?}, staking_ledger: {:?}, inflate_liquid_amount: {:?}",
&derivative_index,
&staking_ledger,
inflate_liquid_amount,
);
use frame_support::traits::tokens::Preservation;
let keep_alive = false;
let keep_alive =