-
Notifications
You must be signed in to change notification settings - Fork 416
/
Copy pathlib.rs
2071 lines (1783 loc) · 86.7 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
// This file is part of Astar.
// Copyright (C) 2019-2023 Stake Technologies Pte.Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later
// Astar is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Astar is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Astar. If not, see <http://www.gnu.org/licenses/>.
//! # dApp Staking v3 Pallet
//!
//! For detailed high level documentation, please refer to the attached README.md file.
//! The crate level docs will cover overall pallet structure & implementation details.
//!
//! ## Overview
//!
//! Pallet that implements the dApp staking v3 protocol.
//! It covers everything from locking, staking, tier configuration & assignment, reward calculation & payout.
//!
//! The `types` module contains all of the types used to implement the pallet.
//! All of these _types_ are extensively tested in their dedicated `test_types` module.
//!
//! Rest of the pallet logic is concentrated in the lib.rs file.
//! This logic is tested in the `tests` module, with the help of extensive `testing_utils`.
//!
#![cfg_attr(not(feature = "std"), no_std)]
use frame_support::{
pallet_prelude::*,
traits::{
fungible::{Inspect as FunInspect, MutateFreeze as FunMutateFreeze},
OnRuntimeUpgrade, StorageVersion,
},
weights::Weight,
};
use frame_system::pallet_prelude::*;
use sp_runtime::{
traits::{BadOrigin, One, Saturating, UniqueSaturatedInto, Zero},
Perbill, Permill,
};
pub use sp_std::vec::Vec;
use astar_primitives::{
dapp_staking::{
AccountCheck, CycleConfiguration, DAppId, EraNumber, Observer as DAppStakingObserver,
PeriodNumber, SmartContractHandle, StakingRewardHandler, TierId,
},
oracle::PriceProvider,
Balance, BlockNumber,
};
pub use pallet::*;
#[cfg(test)]
mod test;
#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
mod types;
pub use types::*;
pub mod migrations;
pub mod weights;
pub use weights::WeightInfo;
const LOG_TARGET: &str = "dapp-staking";
/// Helper enum for benchmarking.
pub(crate) enum TierAssignment {
/// Real tier assignment calculation should be done.
Real,
/// Dummy tier assignment calculation should be done, e.g. default value should be returned.
#[cfg(feature = "runtime-benchmarks")]
Dummy,
}
#[doc = include_str!("../README.md")]
#[frame_support::pallet]
pub mod pallet {
use super::*;
/// The current storage version.
pub const STORAGE_VERSION: StorageVersion = StorageVersion::new(5);
#[pallet::pallet]
#[pallet::storage_version(STORAGE_VERSION)]
pub struct Pallet<T>(_);
#[cfg(feature = "runtime-benchmarks")]
pub trait BenchmarkHelper<SmartContract, AccountId> {
fn get_smart_contract(id: u32) -> SmartContract;
fn set_balance(account: &AccountId, balance: Balance);
}
#[pallet::config]
pub trait Config: frame_system::Config<BlockNumber = BlockNumber> {
/// The overarching event type.
type RuntimeEvent: From<Event<Self>>
+ IsType<<Self as frame_system::Config>::RuntimeEvent>
+ TryInto<Event<Self>>;
/// The overarching freeze reason.
type RuntimeFreezeReason: From<FreezeReason>;
/// Currency used for staking.
/// Reference: <https://github.com/paritytech/substrate/pull/12951/>
type Currency: FunMutateFreeze<
Self::AccountId,
Id = Self::RuntimeFreezeReason,
Balance = Balance,
>;
/// Describes smart contract in the context required by dApp staking.
type SmartContract: Parameter
+ Member
+ MaxEncodedLen
+ SmartContractHandle<Self::AccountId>;
/// Privileged origin for managing dApp staking pallet.
type ManagerOrigin: EnsureOrigin<<Self as frame_system::Config>::RuntimeOrigin>;
/// Used to provide price information about the native token.
type NativePriceProvider: PriceProvider;
/// Used to handle reward payouts & reward pool amount fetching.
type StakingRewardHandler: StakingRewardHandler<Self::AccountId>;
/// Describes era length, subperiods & period length, as well as cycle length.
type CycleConfiguration: CycleConfiguration;
/// dApp staking event observers, notified when certain events occur.
type Observers: DAppStakingObserver;
/// Used to check whether an account is allowed to participate in dApp staking.
type AccountCheck: AccountCheck<Self::AccountId>;
/// Maximum length of a single era reward span length entry.
#[pallet::constant]
type EraRewardSpanLength: Get<u32>;
/// Number of periods for which we keep rewards available for claiming.
/// After that period, they are no longer claimable.
#[pallet::constant]
type RewardRetentionInPeriods: Get<PeriodNumber>;
/// Maximum number of contracts that can be integrated into dApp staking at once.
#[pallet::constant]
type MaxNumberOfContracts: Get<u32>;
/// Maximum number of unlocking chunks that can exist per account at a time.
#[pallet::constant]
type MaxUnlockingChunks: Get<u32>;
/// Minimum amount an account has to lock in dApp staking in order to participate.
#[pallet::constant]
type MinimumLockedAmount: Get<Balance>;
/// Number of standard eras that need to pass before unlocking chunk can be claimed.
/// Even though it's expressed in 'eras', it's actually measured in number of blocks.
#[pallet::constant]
type UnlockingPeriod: Get<EraNumber>;
/// Maximum amount of stake contract entries an account is allowed to have at once.
#[pallet::constant]
type MaxNumberOfStakedContracts: Get<u32>;
/// Minimum amount staker can stake on a contract.
#[pallet::constant]
type MinimumStakeAmount: Get<Balance>;
/// Number of different tiers.
#[pallet::constant]
type NumberOfTiers: Get<u32>;
/// Weight info for various calls & operations in the pallet.
type WeightInfo: WeightInfo;
/// Helper trait for benchmarks.
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper: BenchmarkHelper<Self::SmartContract, Self::AccountId>;
}
#[pallet::event]
#[pallet::generate_deposit(pub(crate) fn deposit_event)]
pub enum Event<T: Config> {
/// Maintenance mode has been either enabled or disabled.
MaintenanceMode { enabled: bool },
/// New era has started.
NewEra { era: EraNumber },
/// New subperiod has started.
NewSubperiod {
subperiod: Subperiod,
number: PeriodNumber,
},
/// A smart contract has been registered for dApp staking
DAppRegistered {
owner: T::AccountId,
smart_contract: T::SmartContract,
dapp_id: DAppId,
},
/// dApp reward destination has been updated.
DAppRewardDestinationUpdated {
smart_contract: T::SmartContract,
beneficiary: Option<T::AccountId>,
},
/// dApp owner has been changed.
DAppOwnerChanged {
smart_contract: T::SmartContract,
new_owner: T::AccountId,
},
/// dApp has been unregistered
DAppUnregistered {
smart_contract: T::SmartContract,
era: EraNumber,
},
/// Account has locked some amount into dApp staking.
Locked {
account: T::AccountId,
amount: Balance,
},
/// Account has started the unlocking process for some amount.
Unlocking {
account: T::AccountId,
amount: Balance,
},
/// Account has claimed unlocked amount, removing the lock from it.
ClaimedUnlocked {
account: T::AccountId,
amount: Balance,
},
/// Account has relocked all of the unlocking chunks.
Relock {
account: T::AccountId,
amount: Balance,
},
/// Account has staked some amount on a smart contract.
Stake {
account: T::AccountId,
smart_contract: T::SmartContract,
amount: Balance,
},
/// Account has unstaked some amount from a smart contract.
Unstake {
account: T::AccountId,
smart_contract: T::SmartContract,
amount: Balance,
},
/// Account has claimed some stake rewards.
Reward {
account: T::AccountId,
era: EraNumber,
amount: Balance,
},
/// Bonus reward has been paid out to a loyal staker.
BonusReward {
account: T::AccountId,
smart_contract: T::SmartContract,
period: PeriodNumber,
amount: Balance,
},
/// dApp reward has been paid out to a beneficiary.
DAppReward {
beneficiary: T::AccountId,
smart_contract: T::SmartContract,
tier_id: TierId,
era: EraNumber,
amount: Balance,
},
/// Account has unstaked funds from an unregistered smart contract
UnstakeFromUnregistered {
account: T::AccountId,
smart_contract: T::SmartContract,
amount: Balance,
},
/// Some expired stake entries have been removed from storage.
ExpiredEntriesRemoved { account: T::AccountId, count: u16 },
/// Privileged origin has forced a new era and possibly a subperiod to start from next block.
Force { forcing_type: ForcingType },
}
#[pallet::error]
pub enum Error<T> {
/// Pallet is disabled/in maintenance mode.
Disabled,
/// Smart contract already exists within dApp staking protocol.
ContractAlreadyExists,
/// Maximum number of smart contracts has been reached.
ExceededMaxNumberOfContracts,
/// Not possible to assign a new dApp Id.
/// This should never happen since current type can support up to 65536 - 1 unique dApps.
NewDAppIdUnavailable,
/// Specified smart contract does not exist in dApp staking.
ContractNotFound,
/// Call origin is not dApp owner.
OriginNotOwner,
/// Performing locking or staking with 0 amount.
ZeroAmount,
/// Total locked amount for staker is below minimum threshold.
LockedAmountBelowThreshold,
/// Account is not allowed to participate in dApp staking due to some external reason (e.g. account is already a collator).
AccountNotAvailableForDappStaking,
/// Cannot add additional unlocking chunks due to capacity limit.
TooManyUnlockingChunks,
/// Remaining stake prevents entire balance of starting the unlocking process.
RemainingStakePreventsFullUnlock,
/// There are no eligible unlocked chunks to claim. This can happen either if no eligible chunks exist, or if user has no chunks at all.
NoUnlockedChunksToClaim,
/// There are no unlocking chunks available to relock.
NoUnlockingChunks,
/// The amount being staked is too large compared to what's available for staking.
UnavailableStakeFunds,
/// There are unclaimed rewards remaining from past eras or periods. They should be claimed before attempting any stake modification again.
UnclaimedRewards,
/// An unexpected error occurred while trying to stake.
InternalStakeError,
/// Total staked amount on contract is below the minimum required value.
InsufficientStakeAmount,
/// Stake operation is rejected since period ends in the next era.
PeriodEndsInNextEra,
/// Unstaking is rejected since the period in which past stake was active has passed.
UnstakeFromPastPeriod,
/// Unstake amount is greater than the staked amount.
UnstakeAmountTooLarge,
/// Account has no staking information for the contract.
NoStakingInfo,
/// An unexpected error occurred while trying to unstake.
InternalUnstakeError,
/// Rewards are no longer claimable since they are too old.
RewardExpired,
/// Reward payout has failed due to an unexpected reason.
RewardPayoutFailed,
/// There are no claimable rewards.
NoClaimableRewards,
/// An unexpected error occurred while trying to claim staker rewards.
InternalClaimStakerError,
/// Account is has no eligible stake amount for bonus reward.
NotEligibleForBonusReward,
/// An unexpected error occurred while trying to claim bonus reward.
InternalClaimBonusError,
/// Claim era is invalid - it must be in history, and rewards must exist for it.
InvalidClaimEra,
/// No dApp tier info exists for the specified era. This can be because era has expired
/// or because during the specified era there were no eligible rewards or protocol wasn't active.
NoDAppTierInfo,
/// An unexpected error occurred while trying to claim dApp reward.
InternalClaimDAppError,
/// Contract is still active, not unregistered.
ContractStillActive,
/// There are too many contract stake entries for the account. This can be cleaned up by either unstaking or cleaning expired entries.
TooManyStakedContracts,
/// There are no expired entries to cleanup for the account.
NoExpiredEntries,
/// Force call is not allowed in production.
ForceNotAllowed,
}
/// General information about dApp staking protocol state.
#[pallet::storage]
#[pallet::whitelist_storage]
pub type ActiveProtocolState<T: Config> = StorageValue<_, ProtocolState, ValueQuery>;
/// Counter for unique dApp identifiers.
#[pallet::storage]
pub type NextDAppId<T: Config> = StorageValue<_, DAppId, ValueQuery>;
/// Map of all dApps integrated into dApp staking protocol.
///
/// Even though dApp is integrated, it does not mean it's still actively participating in dApp staking.
/// It might have been unregistered at some point in history.
#[pallet::storage]
pub type IntegratedDApps<T: Config> = CountedStorageMap<
Hasher = Blake2_128Concat,
Key = T::SmartContract,
Value = DAppInfo<T::AccountId>,
QueryKind = OptionQuery,
MaxValues = ConstU32<{ DAppId::MAX as u32 }>,
>;
/// General locked/staked information for each account.
#[pallet::storage]
pub type Ledger<T: Config> =
StorageMap<_, Blake2_128Concat, T::AccountId, AccountLedgerFor<T>, ValueQuery>;
/// Information about how much each staker has staked for each smart contract in some period.
#[pallet::storage]
pub type StakerInfo<T: Config> = StorageDoubleMap<
_,
Blake2_128Concat,
T::AccountId,
Blake2_128Concat,
T::SmartContract,
SingularStakingInfo,
OptionQuery,
>;
/// Information about how much has been staked on a smart contract in some era or period.
#[pallet::storage]
pub type ContractStake<T: Config> = StorageMap<
Hasher = Twox64Concat,
Key = DAppId,
Value = ContractStakeAmount,
QueryKind = ValueQuery,
MaxValues = ConstU32<{ DAppId::MAX as u32 }>,
>;
/// General information about the current era.
#[pallet::storage]
pub type CurrentEraInfo<T: Config> = StorageValue<_, EraInfo, ValueQuery>;
/// Information about rewards for each era.
///
/// Since each entry is a 'span', covering up to `T::EraRewardSpanLength` entries, only certain era value keys can exist in storage.
/// For the sake of simplicity, valid `era` keys are calculated as:
///
/// era_key = era - (era % T::EraRewardSpanLength)
///
/// This means that e.g. in case `EraRewardSpanLength = 8`, only era values 0, 8, 16, 24, etc. can exist in storage.
/// Eras 1-7 will be stored in the same entry as era 0, eras 9-15 will be stored in the same entry as era 8, etc.
#[pallet::storage]
pub type EraRewards<T: Config> =
StorageMap<_, Twox64Concat, EraNumber, EraRewardSpan<T::EraRewardSpanLength>, OptionQuery>;
/// Information about period's end.
#[pallet::storage]
pub type PeriodEnd<T: Config> =
StorageMap<_, Twox64Concat, PeriodNumber, PeriodEndInfo, OptionQuery>;
/// Static tier parameters used to calculate tier configuration.
#[pallet::storage]
pub type StaticTierParams<T: Config> =
StorageValue<_, TierParameters<T::NumberOfTiers>, ValueQuery>;
/// Tier configuration user for current & preceding eras.
#[pallet::storage]
pub type TierConfig<T: Config> =
StorageValue<_, TiersConfiguration<T::NumberOfTiers>, ValueQuery>;
/// Information about which tier a dApp belonged to in a specific era.
#[pallet::storage]
pub type DAppTiers<T: Config> =
StorageMap<_, Twox64Concat, EraNumber, DAppTierRewardsFor<T>, OptionQuery>;
/// History cleanup marker - holds information about which DB entries should be cleaned up next, when applicable.
#[pallet::storage]
pub type HistoryCleanupMarker<T: Config> = StorageValue<_, CleanupMarker, ValueQuery>;
#[pallet::type_value]
pub fn DefaultSafeguard<T: Config>() -> bool {
// In production, safeguard is enabled by default.
true
}
/// Safeguard to prevent unwanted operations in production.
/// Kept as a storage without extrinsic setter, so we can still enable it for some
/// chain-fork debugging if required.
#[pallet::storage]
pub type Safeguard<T: Config> = StorageValue<_, bool, ValueQuery, DefaultSafeguard<T>>;
#[pallet::genesis_config]
#[derive(frame_support::DefaultNoBound)]
pub struct GenesisConfig {
pub reward_portion: Vec<Permill>,
pub slot_distribution: Vec<Permill>,
pub tier_thresholds: Vec<TierThreshold>,
pub slots_per_tier: Vec<u16>,
}
#[pallet::genesis_build]
impl<T: Config> GenesisBuild<T> for GenesisConfig {
fn build(&self) {
// Prepare tier parameters & verify their correctness
let tier_params = TierParameters::<T::NumberOfTiers> {
reward_portion: BoundedVec::<Permill, T::NumberOfTiers>::try_from(
self.reward_portion.clone(),
)
.expect("Invalid number of reward portions provided."),
slot_distribution: BoundedVec::<Permill, T::NumberOfTiers>::try_from(
self.slot_distribution.clone(),
)
.expect("Invalid number of slot distributions provided."),
tier_thresholds: BoundedVec::<TierThreshold, T::NumberOfTiers>::try_from(
self.tier_thresholds.clone(),
)
.expect("Invalid number of tier thresholds provided."),
};
assert!(
tier_params.is_valid(),
"Invalid tier parameters values provided."
);
// Prepare tier configuration and verify its correctness
let number_of_slots = self.slots_per_tier.iter().fold(0_u16, |acc, &slots| {
acc.checked_add(slots).expect("Overflow")
});
let tier_config = TiersConfiguration::<T::NumberOfTiers> {
number_of_slots,
slots_per_tier: BoundedVec::<u16, T::NumberOfTiers>::try_from(
self.slots_per_tier.clone(),
)
.expect("Invalid number of slots per tier entries provided."),
reward_portion: tier_params.reward_portion.clone(),
tier_thresholds: tier_params.tier_thresholds.clone(),
};
assert!(
tier_params.is_valid(),
"Invalid tier config values provided."
);
// Prepare initial protocol state
let protocol_state = ProtocolState {
era: 1,
next_era_start: Pallet::<T>::blocks_per_voting_period()
.checked_add(1)
.expect("Must not overflow - especially not at genesis."),
period_info: PeriodInfo {
number: 1,
subperiod: Subperiod::Voting,
next_subperiod_start_era: 2,
},
maintenance: false,
};
// Initialize necessary storage items
ActiveProtocolState::<T>::put(protocol_state);
StaticTierParams::<T>::put(tier_params);
TierConfig::<T>::put(tier_config.clone());
}
}
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumber> for Pallet<T> {
fn on_initialize(now: BlockNumber) -> Weight {
Self::era_and_period_handler(now, TierAssignment::Real)
}
fn on_idle(_block: BlockNumberFor<T>, remaining_weight: Weight) -> Weight {
Self::expired_entry_cleanup(&remaining_weight)
}
fn integrity_test() {
// dApp staking params
// Sanity checks
assert!(T::EraRewardSpanLength::get() > 0);
assert!(T::RewardRetentionInPeriods::get() > 0);
assert!(T::MaxNumberOfContracts::get() > 0);
assert!(T::MaxUnlockingChunks::get() > 0);
assert!(T::UnlockingPeriod::get() > 0);
assert!(T::MaxNumberOfStakedContracts::get() > 0);
assert!(T::MinimumLockedAmount::get() > 0);
assert!(T::MinimumStakeAmount::get() > 0);
assert!(T::MinimumLockedAmount::get() >= T::MinimumStakeAmount::get());
// Cycle config
assert!(T::CycleConfiguration::periods_per_cycle() > 0);
assert!(T::CycleConfiguration::eras_per_voting_subperiod() > 0);
assert!(T::CycleConfiguration::eras_per_build_and_earn_subperiod() > 0);
assert!(T::CycleConfiguration::blocks_per_era() > 0);
}
}
/// A reason for freezing funds.
#[pallet::composite_enum]
pub enum FreezeReason {
/// Account is participating in dApp staking.
#[codec(index = 0)]
DAppStaking,
}
#[pallet::call]
impl<T: Config> Pallet<T> {
/// Wrapper around _legacy-like_ `unbond_and_unstake`.
///
/// Used to support legacy Ledger users so they can start the unlocking process for their funds.
#[pallet::call_index(4)]
#[pallet::weight(T::WeightInfo::unlock())]
pub fn unbond_and_unstake(
origin: OriginFor<T>,
_contract_id: T::SmartContract,
#[pallet::compact] value: Balance,
) -> DispatchResult {
// Once new period begins, all stakes are reset to zero, so all it remains to be done is the `unlock`
Self::unlock(origin, value)
}
/// Wrapper around _legacy-like_ `withdraw_unbonded`.
///
/// Used to support legacy Ledger users so they can reclaim unlocked chunks back into
/// their _transferable_ free balance.
#[pallet::call_index(5)]
#[pallet::weight(T::WeightInfo::claim_unlocked(T::MaxNumberOfStakedContracts::get()))]
pub fn withdraw_unbonded(origin: OriginFor<T>) -> DispatchResultWithPostInfo {
Self::claim_unlocked(origin)
}
/// Used to enable or disable maintenance mode.
/// Can only be called by manager origin.
#[pallet::call_index(0)]
#[pallet::weight(T::WeightInfo::maintenance_mode())]
pub fn maintenance_mode(origin: OriginFor<T>, enabled: bool) -> DispatchResult {
T::ManagerOrigin::ensure_origin(origin)?;
ActiveProtocolState::<T>::mutate(|state| state.maintenance = enabled);
Self::deposit_event(Event::<T>::MaintenanceMode { enabled });
Ok(())
}
/// Used to register a new contract for dApp staking.
///
/// If successful, smart contract will be assigned a simple, unique numerical identifier.
/// Owner is set to be initial beneficiary & manager of the dApp.
#[pallet::call_index(1)]
#[pallet::weight(T::WeightInfo::register())]
pub fn register(
origin: OriginFor<T>,
owner: T::AccountId,
smart_contract: T::SmartContract,
) -> DispatchResult {
Self::ensure_pallet_enabled()?;
T::ManagerOrigin::ensure_origin(origin)?;
ensure!(
!IntegratedDApps::<T>::contains_key(&smart_contract),
Error::<T>::ContractAlreadyExists,
);
ensure!(
IntegratedDApps::<T>::count() < T::MaxNumberOfContracts::get().into(),
Error::<T>::ExceededMaxNumberOfContracts
);
let dapp_id = NextDAppId::<T>::get();
// MAX value must never be assigned as a dApp Id since it serves as a sentinel value.
ensure!(dapp_id < DAppId::MAX, Error::<T>::NewDAppIdUnavailable);
IntegratedDApps::<T>::insert(
&smart_contract,
DAppInfo {
owner: owner.clone(),
id: dapp_id,
reward_beneficiary: None,
},
);
NextDAppId::<T>::put(dapp_id.saturating_add(1));
Self::deposit_event(Event::<T>::DAppRegistered {
owner,
smart_contract,
dapp_id,
});
Ok(())
}
/// Used to modify the reward beneficiary account for a dApp.
///
/// Caller has to be dApp owner.
/// If set to `None`, rewards will be deposited to the dApp owner.
/// After this call, all existing & future rewards will be paid out to the beneficiary.
#[pallet::call_index(2)]
#[pallet::weight(T::WeightInfo::set_dapp_reward_beneficiary())]
pub fn set_dapp_reward_beneficiary(
origin: OriginFor<T>,
smart_contract: T::SmartContract,
beneficiary: Option<T::AccountId>,
) -> DispatchResult {
Self::ensure_pallet_enabled()?;
let dev_account = ensure_signed(origin)?;
IntegratedDApps::<T>::try_mutate(
&smart_contract,
|maybe_dapp_info| -> DispatchResult {
let dapp_info = maybe_dapp_info
.as_mut()
.ok_or(Error::<T>::ContractNotFound)?;
ensure!(dapp_info.owner == dev_account, Error::<T>::OriginNotOwner);
dapp_info.reward_beneficiary = beneficiary.clone();
Ok(())
},
)?;
Self::deposit_event(Event::<T>::DAppRewardDestinationUpdated {
smart_contract,
beneficiary,
});
Ok(())
}
/// Used to change dApp owner.
///
/// Can be called by dApp owner or dApp staking manager origin.
/// This is useful in two cases:
/// 1. when the dApp owner account is compromised, manager can change the owner to a new account
/// 2. if project wants to transfer ownership to a new account (DAO, multisig, etc.).
#[pallet::call_index(3)]
#[pallet::weight(T::WeightInfo::set_dapp_owner())]
pub fn set_dapp_owner(
origin: OriginFor<T>,
smart_contract: T::SmartContract,
new_owner: T::AccountId,
) -> DispatchResult {
Self::ensure_pallet_enabled()?;
let origin = Self::ensure_signed_or_manager(origin)?;
IntegratedDApps::<T>::try_mutate(
&smart_contract,
|maybe_dapp_info| -> DispatchResult {
let dapp_info = maybe_dapp_info
.as_mut()
.ok_or(Error::<T>::ContractNotFound)?;
// If manager origin, `None`, no need to check if caller is the owner.
if let Some(caller) = origin {
ensure!(dapp_info.owner == caller, Error::<T>::OriginNotOwner);
}
dapp_info.owner = new_owner.clone();
Ok(())
},
)?;
Self::deposit_event(Event::<T>::DAppOwnerChanged {
smart_contract,
new_owner,
});
Ok(())
}
/// Unregister dApp from dApp staking protocol, making it ineligible for future rewards.
/// This doesn't remove the dApp completely from the system just yet, but it can no longer be used for staking.
///
/// Can be called by dApp staking manager origin.
#[pallet::call_index(6)]
#[pallet::weight(T::WeightInfo::unregister())]
pub fn unregister(
origin: OriginFor<T>,
smart_contract: T::SmartContract,
) -> DispatchResult {
Self::ensure_pallet_enabled()?;
T::ManagerOrigin::ensure_origin(origin)?;
let dapp_info =
IntegratedDApps::<T>::get(&smart_contract).ok_or(Error::<T>::ContractNotFound)?;
ContractStake::<T>::remove(&dapp_info.id);
IntegratedDApps::<T>::remove(&smart_contract);
let current_era = ActiveProtocolState::<T>::get().era;
Self::deposit_event(Event::<T>::DAppUnregistered {
smart_contract,
era: current_era,
});
Ok(())
}
/// Locks additional funds into dApp staking.
///
/// In case caller account doesn't have sufficient balance to cover the specified amount, everything is locked.
/// After adjustment, lock amount must be greater than zero and in total must be equal or greater than the minimum locked amount.
///
/// Locked amount can immediately be used for staking.
#[pallet::call_index(7)]
#[pallet::weight(T::WeightInfo::lock_new_account().max(T::WeightInfo::lock_existing_account()))]
pub fn lock(
origin: OriginFor<T>,
#[pallet::compact] amount: Balance,
) -> DispatchResultWithPostInfo {
Self::ensure_pallet_enabled()?;
let account = ensure_signed(origin)?;
let mut ledger = Ledger::<T>::get(&account);
// Only do the check for new accounts.
// External logic should ensure that accounts which are already participating in dApp staking aren't
// allowed to participate elsewhere where they shouldn't.
let is_new_account = ledger.is_empty();
if is_new_account {
ensure!(
T::AccountCheck::allowed_to_stake(&account),
Error::<T>::AccountNotAvailableForDappStaking
);
}
// Calculate & check amount available for locking
let available_balance =
T::Currency::total_balance(&account).saturating_sub(ledger.active_locked_amount());
let amount_to_lock = available_balance.min(amount);
ensure!(!amount_to_lock.is_zero(), Error::<T>::ZeroAmount);
ledger.add_lock_amount(amount_to_lock);
ensure!(
ledger.active_locked_amount() >= T::MinimumLockedAmount::get(),
Error::<T>::LockedAmountBelowThreshold
);
Self::update_ledger(&account, ledger)?;
CurrentEraInfo::<T>::mutate(|era_info| {
era_info.add_locked(amount_to_lock);
});
Self::deposit_event(Event::<T>::Locked {
account,
amount: amount_to_lock,
});
Ok(Some(if is_new_account {
T::WeightInfo::lock_new_account()
} else {
T::WeightInfo::lock_existing_account()
})
.into())
}
/// Attempts to start the unlocking process for the specified amount.
///
/// Only the amount that isn't actively used for staking can be unlocked.
/// If the amount is greater than the available amount for unlocking, everything is unlocked.
/// If the remaining locked amount would take the account below the minimum locked amount, everything is unlocked.
#[pallet::call_index(8)]
#[pallet::weight(T::WeightInfo::unlock())]
pub fn unlock(origin: OriginFor<T>, #[pallet::compact] amount: Balance) -> DispatchResult {
Self::ensure_pallet_enabled()?;
let account = ensure_signed(origin)?;
let state = ActiveProtocolState::<T>::get();
let mut ledger = Ledger::<T>::get(&account);
let available_for_unlocking = ledger.unlockable_amount(state.period_info.number);
let amount_to_unlock = available_for_unlocking.min(amount);
// Ensure we unlock everything if remaining amount is below threshold.
let remaining_amount = ledger
.active_locked_amount()
.saturating_sub(amount_to_unlock);
let amount_to_unlock = if remaining_amount < T::MinimumLockedAmount::get() {
ensure!(
ledger.staked_amount(state.period_info.number).is_zero(),
Error::<T>::RemainingStakePreventsFullUnlock
);
ledger.active_locked_amount()
} else {
amount_to_unlock
};
// Sanity check
ensure!(!amount_to_unlock.is_zero(), Error::<T>::ZeroAmount);
// Update ledger with new lock and unlocking amounts
ledger.subtract_lock_amount(amount_to_unlock);
let current_block = frame_system::Pallet::<T>::block_number();
let unlock_block = current_block.saturating_add(Self::unlocking_period());
ledger
.add_unlocking_chunk(amount_to_unlock, unlock_block)
.map_err(|_| Error::<T>::TooManyUnlockingChunks)?;
// Update storage
Self::update_ledger(&account, ledger)?;
CurrentEraInfo::<T>::mutate(|era_info| {
era_info.unlocking_started(amount_to_unlock);
});
Self::deposit_event(Event::<T>::Unlocking {
account,
amount: amount_to_unlock,
});
Ok(())
}
/// Claims all of fully unlocked chunks, removing the lock from them.
#[pallet::call_index(9)]
#[pallet::weight(T::WeightInfo::claim_unlocked(T::MaxNumberOfStakedContracts::get()))]
pub fn claim_unlocked(origin: OriginFor<T>) -> DispatchResultWithPostInfo {
Self::ensure_pallet_enabled()?;
let account = ensure_signed(origin)?;
let mut ledger = Ledger::<T>::get(&account);
let current_block = frame_system::Pallet::<T>::block_number();
let amount = ledger.claim_unlocked(current_block);
ensure!(amount > Zero::zero(), Error::<T>::NoUnlockedChunksToClaim);
// In case it's full unlock, account is exiting dApp staking, ensure all storage is cleaned up.
let removed_entries = if ledger.is_empty() {
let _ = StakerInfo::<T>::clear_prefix(&account, ledger.contract_stake_count, None);
ledger.contract_stake_count
} else {
0
};
Self::update_ledger(&account, ledger)?;
CurrentEraInfo::<T>::mutate(|era_info| {
era_info.unlocking_removed(amount);
});
Self::deposit_event(Event::<T>::ClaimedUnlocked { account, amount });
Ok(Some(T::WeightInfo::claim_unlocked(removed_entries)).into())
}
#[pallet::call_index(10)]
#[pallet::weight(T::WeightInfo::relock_unlocking())]
pub fn relock_unlocking(origin: OriginFor<T>) -> DispatchResult {
Self::ensure_pallet_enabled()?;
let account = ensure_signed(origin)?;
let mut ledger = Ledger::<T>::get(&account);
ensure!(!ledger.unlocking.is_empty(), Error::<T>::NoUnlockingChunks);
let amount = ledger.consume_unlocking_chunks();
ledger.add_lock_amount(amount);
ensure!(
ledger.active_locked_amount() >= T::MinimumLockedAmount::get(),
Error::<T>::LockedAmountBelowThreshold
);
Self::update_ledger(&account, ledger)?;
CurrentEraInfo::<T>::mutate(|era_info| {
era_info.add_locked(amount);
era_info.unlocking_removed(amount);
});
Self::deposit_event(Event::<T>::Relock { account, amount });
Ok(())
}
/// Stake the specified amount on a smart contract.
/// The precise `amount` specified **must** be available for staking.
/// The total amount staked on a dApp must be greater than the minimum required value.
///
/// Depending on the period type, appropriate stake amount will be updated. During `Voting` subperiod, `voting` stake amount is updated,
/// and same for `Build&Earn` subperiod.
///
/// Staked amount is only eligible for rewards from the next era onwards.
#[pallet::call_index(11)]
#[pallet::weight(T::WeightInfo::stake())]
pub fn stake(
origin: OriginFor<T>,
smart_contract: T::SmartContract,
#[pallet::compact] amount: Balance,
) -> DispatchResult {
Self::ensure_pallet_enabled()?;
let account = ensure_signed(origin)?;
ensure!(amount > 0, Error::<T>::ZeroAmount);
let dapp_info =
IntegratedDApps::<T>::get(&smart_contract).ok_or(Error::<T>::ContractNotFound)?;
let protocol_state = ActiveProtocolState::<T>::get();
let current_era = protocol_state.era;
ensure!(
!protocol_state
.period_info
.is_next_period(current_era.saturating_add(1)),
Error::<T>::PeriodEndsInNextEra
);
let mut ledger = Ledger::<T>::get(&account);
// In case old stake rewards are unclaimed & have expired, clean them up.
let threshold_period = Self::oldest_claimable_period(protocol_state.period_number());
let _ignore = ledger.maybe_cleanup_expired(threshold_period);
// 1.
// Increase stake amount for the next era & current period in staker's ledger
ledger
.add_stake_amount(amount, current_era, protocol_state.period_info)
.map_err(|err| match err {
AccountLedgerError::InvalidPeriod | AccountLedgerError::InvalidEra => {
Error::<T>::UnclaimedRewards
}
AccountLedgerError::UnavailableStakeFunds => Error::<T>::UnavailableStakeFunds,
// Defensive check, should never happen