-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathlib.rs
1789 lines (1610 loc) · 65.5 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
#![cfg_attr(not(feature = "std"), no_std)]
// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
#![recursion_limit = "256"]
// Make the WASM binary available.
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
pub use frame_support::{
construct_runtime,
genesis_builder_helper::{build_config, create_default_config},
parameter_types,
traits::{
Currency, EstimateNextNewSession, Imbalance, KeyOwnerProofSystem, LockIdentifier, Nothing,
OnUnbalanced, Randomness, ValidatorSet,
},
weights::{
constants::{
BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_REF_TIME_PER_SECOND,
},
IdentityFee, Weight,
},
StorageValue,
};
use frame_support::{
sp_runtime::Perquintill,
traits::{
tokens::{PayFromAccount, UnityAssetBalanceConversion},
ConstBool, ConstU32, Contains, EqualPrivilegeOnly, EstimateNextSessionRotation, InsideBoth,
InstanceFilter, SortedMembers, WithdrawReasons,
},
weights::{constants::WEIGHT_REF_TIME_PER_MILLIS, WeightToFee},
PalletId,
};
use frame_system::{EnsureRoot, EnsureRootWithSuccess, EnsureSignedBy};
#[cfg(feature = "try-runtime")]
use frame_try_runtime::UpgradeCheckSelect;
pub use pallet_balances::Call as BalancesCall;
use pallet_committee_management::SessionAndEraManager;
use pallet_identity::legacy::IdentityInfo;
use pallet_session::QueuedKeys;
pub use pallet_timestamp::Call as TimestampCall;
use pallet_transaction_payment::{CurrencyAdapter, Multiplier, TargetedFeeAdjustment};
use pallet_tx_pause::RuntimeCallNameOf;
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
use primitives::{
crypto::SignatureSet, staking::MAX_NOMINATORS_REWARDED_PER_VALIDATOR, wrap_methods, Address,
AlephNodeSessionKeys as SessionKeys, ApiError as AlephApiError, AuraId, AuthorityId as AlephId,
AuthoritySignature, BlockNumber as AlephBlockNumber, Header as AlephHeader, Score,
SessionAuthorityData, SessionCommittee, SessionIndex, SessionInfoProvider,
SessionValidatorError, TotalIssuanceProvider as TotalIssuanceProviderT,
Version as FinalityVersion, ADDRESSES_ENCODING, DEFAULT_BAN_REASON_LENGTH, DEFAULT_MAX_WINNERS,
DEFAULT_SESSIONS_PER_ERA, DEFAULT_SESSION_PERIOD, MAX_BLOCK_SIZE, MILLISECS_PER_BLOCK, TOKEN,
};
pub use primitives::{AccountId, AccountIndex, Balance, Hash, Nonce, Signature};
use sp_api::impl_runtime_apis;
use sp_application_crypto::key_types::AURA;
use sp_consensus_aura::SlotDuration;
use sp_core::{crypto::KeyTypeId, ConstU128, OpaqueMetadata};
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;
use sp_runtime::{
create_runtime_str, generic,
traits::{
AccountIdLookup, BlakeTwo256, Block as BlockT, Bounded, Convert, ConvertInto,
IdentityLookup, One, OpaqueKeys, Verify,
},
transaction_validity::{TransactionSource, TransactionValidity},
ApplyExtrinsicResult, FixedU128, RuntimeDebug, SaturatedConversion,
};
pub use sp_runtime::{FixedPointNumber, Perbill, Permill, Saturating};
use sp_staking::{currency_to_vote::U128CurrencyToVote, EraIndex};
use sp_std::prelude::*;
#[cfg(feature = "std")]
use sp_version::NativeVersion;
use sp_version::RuntimeVersion;
#[sp_version::runtime_version]
pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: create_runtime_str!("aleph-node"),
impl_name: create_runtime_str!("aleph-node"),
authoring_version: 1,
spec_version: 15_000_000,
impl_version: 1,
apis: RUNTIME_API_VERSIONS,
transaction_version: 19,
state_version: 0,
};
/// The version information used to identify this runtime when compiled natively.
#[cfg(feature = "std")]
pub fn native_version() -> NativeVersion {
NativeVersion {
runtime_version: VERSION,
can_author_with: Default::default(),
}
}
pub const DAYS: u32 = 24 * 60 * 60 * 1000 / (MILLISECS_PER_BLOCK as u32);
pub const BLOCKS_PER_HOUR: u32 = 60 * 60 * 1000 / (MILLISECS_PER_BLOCK as u32);
pub const MILLI_AZERO: Balance = TOKEN / 1000;
pub const MICRO_AZERO: Balance = MILLI_AZERO / 1000;
pub const NANO_AZERO: Balance = MICRO_AZERO / 1000;
pub const PICO_AZERO: Balance = NANO_AZERO / 1000;
// 99% block weight is dedicated to normal extrinsics leaving 1% reserved space for the operational
// extrinsics.
pub const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(99);
// The whole process for a single block should take 1s, of which 400ms is for creation,
// 200ms for propagation and 400ms for validation. Hence the block weight should be within 400ms.
pub const MAX_BLOCK_WEIGHT: Weight =
Weight::from_parts(WEIGHT_REF_TIME_PER_MILLIS.saturating_mul(400), 0);
// The storage deposit is roughly 1 TOKEN per 1kB -- this is the legacy value, used for pallet Identity and Multisig.
pub const LEGACY_DEPOSIT_PER_BYTE: Balance = MILLI_AZERO;
// The storage per one byte of contract storage: 4*10^{-5} AZERO per byte.
pub const CONTRACT_DEPOSIT_PER_BYTE: Balance = 4 * (TOKEN / 100_000);
parameter_types! {
pub const Version: RuntimeVersion = VERSION;
pub const BlockHashCount: AlephBlockNumber = 2400;
pub BlockWeights: frame_system::limits::BlockWeights = frame_system::limits::BlockWeights
::with_sensible_defaults(MAX_BLOCK_WEIGHT.set_proof_size(u64::MAX), NORMAL_DISPATCH_RATIO);
pub BlockLength: frame_system::limits::BlockLength = frame_system::limits::BlockLength
::max_with_normal_ratio(MAX_BLOCK_SIZE, NORMAL_DISPATCH_RATIO);
pub const SS58Prefix: u8 = ADDRESSES_ENCODING;
}
// Configure FRAME pallets to include in runtime.
impl frame_system::Config for Runtime {
/// The basic call filter to use in dispatchable.
type BaseCallFilter = InsideBoth<SafeMode, TxPause>;
/// Block & extrinsics weights: base values and limits.
type BlockWeights = BlockWeights;
/// The maximum length of a block (in bytes).
type BlockLength = BlockLength;
/// The identifier used to distinguish between accounts.
type AccountId = AccountId;
/// The aggregated dispatch type that is available for extrinsics.
type RuntimeCall = RuntimeCall;
/// The aggregated Task type.
type RuntimeTask = RuntimeTask;
/// The lookup mechanism to get account ID from whatever is passed in dispatchers.
type Lookup = AccountIdLookup<AccountId, ()>;
/// The type for storing how many extrinsics an account has signed.
type Nonce = Nonce;
/// The block type.
type Block = Block;
/// The type for hashing blocks and tries.
type Hash = Hash;
/// The hashing algorithm used.
type Hashing = BlakeTwo256;
/// The ubiquitous event type.
type RuntimeEvent = RuntimeEvent;
/// The ubiquitous origin type.
type RuntimeOrigin = RuntimeOrigin;
/// Maximum number of block number to block hash mappings to keep (oldest pruned first).
type BlockHashCount = BlockHashCount;
/// The weight of database operations that the runtime can invoke.
type DbWeight = RocksDbWeight;
/// Version of the runtime.
type Version = Version;
/// Converts a module to the index of the module in `construct_runtime!`.
///
/// This type is being generated by `construct_runtime!`.
type PalletInfo = PalletInfo;
/// What to do if a new account is created.
type OnNewAccount = ();
/// What to do if an account is fully reaped from the system.
type OnKilledAccount = ();
/// The data to be stored in an account.
type AccountData = pallet_balances::AccountData<Balance>;
/// Weight information for the extrinsics of this pallet.
type SystemWeightInfo = ();
/// This is used as an identifier of the chain. 42 is the generic substrate prefix.
type SS58Prefix = SS58Prefix;
type OnSetCode = ();
type MaxConsumers = frame_support::traits::ConstU32<16>;
}
parameter_types! {
// https://github.com/paritytech/polkadot/blob/9ce5f7ef5abb1a4291454e8c9911b304d80679f9/runtime/polkadot/src/lib.rs#L784
pub const MaxAuthorities: u32 = 100_000;
}
impl pallet_aura::Config for Runtime {
type MaxAuthorities = MaxAuthorities;
type AuthorityId = AuraId;
type DisabledValidators = ();
type AllowMultipleBlocksPerSlot = ConstBool<false>;
}
parameter_types! {
pub const UncleGenerations: AlephBlockNumber = 0;
}
impl pallet_authorship::Config for Runtime {
type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Aura>;
type EventHandler = (CommitteeManagement,);
}
parameter_types! {
pub const ExistentialDeposit: u128 = 500 * PICO_AZERO;
pub const MaxLocks: u32 = 50;
pub const MaxHolds: u32 = 50;
pub const MaxFreezes: u32 = 50;
pub const MaxReserves: u32 = 50;
}
impl pallet_balances::Config for Runtime {
type MaxLocks = MaxLocks;
type MaxReserves = MaxReserves;
type ReserveIdentifier = [u8; 8];
/// The type for recording an account's balance.
type Balance = Balance;
/// The ubiquitous event type.
type RuntimeEvent = RuntimeEvent;
type DustRemoval = ();
type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System;
type WeightInfo = pallet_balances::weights::SubstrateWeight<Runtime>;
type FreezeIdentifier = RuntimeFreezeReason;
type MaxHolds = MaxHolds;
type MaxFreezes = MaxFreezes;
type RuntimeHoldReason = RuntimeHoldReason;
type RuntimeFreezeReason = RuntimeFreezeReason;
}
type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;
pub struct EverythingToTheTreasury;
impl OnUnbalanced<NegativeImbalance> for EverythingToTheTreasury {
fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {
if let Some(fees) = fees_then_tips.next() {
Treasury::on_unbalanced(fees);
if let Some(tips) = fees_then_tips.next() {
Treasury::on_unbalanced(tips);
}
}
}
}
parameter_types! {
// This value increases the priority of `Operational` transactions by adding
// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.
// follows polkadot : https://github.com/paritytech/polkadot/blob/9ce5f7ef5abb1a4291454e8c9911b304d80679f9/runtime/polkadot/src/lib.rs#L369
pub const OperationalFeeMultiplier: u8 = 5;
// We expect that on average 50% of the normal capacity will be occupied with normal txs.
pub const TargetSaturationLevel: Perquintill = Perquintill::from_percent(50);
// During 20 blocks the fee may not change more than by 100%. This, together with the
// `TargetSaturationLevel` value, results in variability ~0.067. For the corresponding
// formulas please refer to Substrate code at `frame/transaction-payment/src/lib.rs`.
pub FeeVariability: Multiplier = Multiplier::saturating_from_rational(67, 1000);
// Fee should never be lower than the computational cost.
pub MinimumMultiplier: Multiplier = Multiplier::one();
pub MaximumMultiplier: Multiplier = Bounded::max_value();
}
pub struct DivideFeeBy<const N: Balance>;
impl<const N: Balance> WeightToFee for DivideFeeBy<N> {
type Balance = Balance;
fn weight_to_fee(weight: &Weight) -> Self::Balance {
Balance::saturated_from(weight.ref_time()).saturating_div(N)
}
}
impl pallet_transaction_payment::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type OnChargeTransaction = CurrencyAdapter<Balances, EverythingToTheTreasury>;
type LengthToFee = DivideFeeBy<10>;
type WeightToFee = DivideFeeBy<10>;
type FeeMultiplierUpdate = TargetedFeeAdjustment<
Self,
TargetSaturationLevel,
FeeVariability,
MinimumMultiplier,
MaximumMultiplier,
>;
type OperationalFeeMultiplier = OperationalFeeMultiplier;
}
parameter_types! {
pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * BlockWeights::get().max_block;
pub const MaxScheduledPerBlock: u32 = 50;
}
impl pallet_scheduler::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeOrigin = RuntimeOrigin;
type PalletsOrigin = OriginCaller;
type RuntimeCall = RuntimeCall;
type MaximumWeight = MaximumSchedulerWeight;
type ScheduleOrigin = frame_system::EnsureRoot<AccountId>;
type MaxScheduledPerBlock = MaxScheduledPerBlock;
type WeightInfo = pallet_scheduler::weights::SubstrateWeight<Runtime>;
type OriginPrivilegeCmp = EqualPrivilegeOnly;
type Preimages = ();
}
impl pallet_sudo::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
type WeightInfo = pallet_sudo::weights::SubstrateWeight<Runtime>;
}
pub struct SessionInfoImpl;
impl SessionInfoProvider<AlephBlockNumber> for SessionInfoImpl {
fn current_session() -> SessionIndex {
pallet_session::CurrentIndex::<Runtime>::get()
}
fn next_session_block_number(current_block: AlephBlockNumber) -> Option<AlephBlockNumber> {
<Runtime as pallet_session::Config>::NextSessionRotation::estimate_next_session_rotation(
current_block,
)
.0
}
}
pub struct TotalIssuanceProvider;
impl TotalIssuanceProviderT for TotalIssuanceProvider {
fn get() -> Balance {
pallet_balances::Pallet::<Runtime>::total_issuance()
}
}
impl pallet_aleph::Config for Runtime {
type AuthorityId = AlephId;
type RuntimeEvent = RuntimeEvent;
type SessionInfoProvider = SessionInfoImpl;
type SessionManager = SessionAndEraManager<
Staking,
Elections,
pallet_session::historical::NoteHistoricalRoot<Runtime, Staking>,
Runtime,
>;
type NextSessionAuthorityProvider = Session;
type TotalIssuanceProvider = TotalIssuanceProvider;
}
parameter_types! {
pub const SessionPeriod: u32 = DEFAULT_SESSION_PERIOD;
pub const MaximumBanReasonLength: u32 = DEFAULT_BAN_REASON_LENGTH;
pub const MaxWinners: u32 = DEFAULT_MAX_WINNERS;
}
impl pallet_elections::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type DataProvider = Staking;
type ValidatorProvider = Staking;
type MaxWinners = MaxWinners;
type BannedValidators = CommitteeManagement;
}
impl pallet_operations::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type AccountInfoProvider = System;
type BalancesProvider = Balances;
type NextKeysSessionProvider = Session;
type BondedStashProvider = Staking;
type ContractInfoProvider = Contracts;
}
impl pallet_committee_management::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type BanHandler = Elections;
type EraInfoProvider = Staking;
type ValidatorProvider = Elections;
type ValidatorRewardsHandler = Staking;
type ValidatorExtractor = Staking;
type FinalityCommitteeManager = Aleph;
type SessionPeriod = SessionPeriod;
type AbftScoresProvider = Aleph;
}
impl pallet_insecure_randomness_collective_flip::Config for Runtime {}
parameter_types! {
pub const Offset: u32 = 0;
}
impl pallet_session::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type ValidatorId = <Self as frame_system::Config>::AccountId;
type ValidatorIdOf = pallet_staking::StashOf<Self>;
type ShouldEndSession = pallet_session::PeriodicSessions<SessionPeriod, Offset>;
type NextSessionRotation = pallet_session::PeriodicSessions<SessionPeriod, Offset>;
type SessionManager = Aleph;
type SessionHandler = (Aura, Aleph);
type Keys = SessionKeys;
type WeightInfo = pallet_session::weights::SubstrateWeight<Runtime>;
}
impl pallet_session::historical::Config for Runtime {
type FullIdentification = pallet_staking::Exposure<AccountId, Balance>;
type FullIdentificationOf = pallet_staking::ExposureOf<Runtime>;
}
parameter_types! {
pub const PostUnbondPoolsWindow: u32 = 4;
pub const NominationPoolsPalletId: PalletId = PalletId(*b"py/nopls");
pub const MaxPointsToBalance: u8 = 10;
}
pub struct BalanceToU256;
impl Convert<Balance, sp_core::U256> for BalanceToU256 {
fn convert(balance: Balance) -> sp_core::U256 {
sp_core::U256::from(balance)
}
}
pub struct U256ToBalance;
impl Convert<sp_core::U256, Balance> for U256ToBalance {
fn convert(n: sp_core::U256) -> Balance {
n.try_into().unwrap_or(Balance::MAX)
}
}
impl pallet_nomination_pools::Config for Runtime {
type WeightInfo = ();
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type RewardCounter = FixedU128;
type BalanceToU256 = BalanceToU256;
type U256ToBalance = U256ToBalance;
type Staking = pallet_staking::Pallet<Self>;
type PostUnbondingPoolsWindow = PostUnbondPoolsWindow;
type MaxMetadataLen = ConstU32<256>;
type MaxUnbonding = ConstU32<8>;
type PalletId = NominationPoolsPalletId;
type MaxPointsToBalance = MaxPointsToBalance;
type RuntimeFreezeReason = RuntimeFreezeReason;
}
parameter_types! {
pub const BondingDuration: EraIndex = 14;
pub const SlashDeferDuration: EraIndex = 13;
// this is coupled with weights for payout_stakers() call
// see custom implementation of WeightInfo below
pub const MaxExposurePageSize: u32 = MAX_NOMINATORS_REWARDED_PER_VALIDATOR;
pub const OffendingValidatorsThreshold: Perbill = Perbill::from_percent(33);
pub const SessionsPerEra: EraIndex = DEFAULT_SESSIONS_PER_ERA;
pub HistoryDepth: u32 = 84;
}
pub struct ExponentialEraPayout;
impl ExponentialEraPayout {
fn era_payout(total_issuance: Balance, era_duration_millis: u64) -> (Balance, Balance) {
const VALIDATOR_REWARD: Perbill = Perbill::from_percent(90);
let azero_cap = pallet_aleph::AzeroCap::<Runtime>::get();
let horizon = pallet_aleph::ExponentialInflationHorizon::<Runtime>::get();
let total_payout: Balance =
exp_helper(Perbill::from_rational(era_duration_millis, horizon))
* (azero_cap.saturating_sub(total_issuance));
let validators_payout = VALIDATOR_REWARD * total_payout;
let rest = total_payout - validators_payout;
(validators_payout, rest)
}
}
/// Calculates 1 - exp(-x) for small positive x
fn exp_helper(x: Perbill) -> Perbill {
let x2 = x * x;
let x3 = x2 * x;
let x4 = x2 * x2;
let x5 = x4 * x;
(x - x2 / 2 + x3 / 6 - x4 / 24 + x5 / 120).min(x)
}
impl pallet_staking::EraPayout<Balance> for ExponentialEraPayout {
fn era_payout(
_: Balance,
total_issuance: Balance,
era_duration_millis: u64,
) -> (Balance, Balance) {
ExponentialEraPayout::era_payout(total_issuance, era_duration_millis)
}
}
type SubstrateStakingWeights = pallet_staking::weights::SubstrateWeight<Runtime>;
pub struct PayoutStakersDecreasedWeightInfo;
impl pallet_staking::WeightInfo for PayoutStakersDecreasedWeightInfo {
// To make possible to change nominators per validator we need to decrease weight for payout_stakers
fn payout_stakers_alive_staked(n: u32) -> Weight {
SubstrateStakingWeights::payout_stakers_alive_staked(n) / 2
}
wrap_methods!(
(bond(), SubstrateStakingWeights, Weight),
(bond_extra(), SubstrateStakingWeights, Weight),
(unbond(), SubstrateStakingWeights, Weight),
(
withdraw_unbonded_update(s: u32),
SubstrateStakingWeights,
Weight
),
(
withdraw_unbonded_kill(s: u32),
SubstrateStakingWeights,
Weight
),
(validate(), SubstrateStakingWeights, Weight),
(kick(k: u32), SubstrateStakingWeights, Weight),
(nominate(n: u32), SubstrateStakingWeights, Weight),
(chill(), SubstrateStakingWeights, Weight),
(set_payee(), SubstrateStakingWeights, Weight),
(update_payee(), SubstrateStakingWeights, Weight),
(set_controller(), SubstrateStakingWeights, Weight),
(set_validator_count(), SubstrateStakingWeights, Weight),
(force_no_eras(), SubstrateStakingWeights, Weight),
(force_new_era(), SubstrateStakingWeights, Weight),
(force_new_era_always(), SubstrateStakingWeights, Weight),
(set_invulnerables(v: u32), SubstrateStakingWeights, Weight),
(deprecate_controller_batch(i: u32), SubstrateStakingWeights, Weight),
(force_unstake(s: u32), SubstrateStakingWeights, Weight),
(
cancel_deferred_slash(s: u32),
SubstrateStakingWeights,
Weight
),
(rebond(l: u32), SubstrateStakingWeights, Weight),
(reap_stash(s: u32), SubstrateStakingWeights, Weight),
(new_era(v: u32, n: u32), SubstrateStakingWeights, Weight),
(
get_npos_voters(v: u32, n: u32),
SubstrateStakingWeights,
Weight
),
(get_npos_targets(v: u32), SubstrateStakingWeights, Weight),
(chill_other(), SubstrateStakingWeights, Weight),
(
set_staking_configs_all_set(),
SubstrateStakingWeights,
Weight
),
(
set_staking_configs_all_remove(),
SubstrateStakingWeights,
Weight
),
(
force_apply_min_commission(),
SubstrateStakingWeights,
Weight
),
(set_min_commission(), SubstrateStakingWeights, Weight)
);
}
pub struct StakingBenchmarkingConfig;
impl pallet_staking::BenchmarkingConfig for StakingBenchmarkingConfig {
type MaxValidators = ConstU32<1000>;
type MaxNominators = ConstU32<1000>;
}
const MAX_NOMINATORS: u32 = 1;
impl pallet_staking::Config for Runtime {
// Do not change this!!! It guarantees that we have DPoS instead of NPoS.
type Currency = Balances;
type UnixTime = Timestamp;
type CurrencyToVote = U128CurrencyToVote;
type ElectionProvider = Elections;
type GenesisElectionProvider = Elections;
type NominationsQuota = pallet_staking::FixedNominationsQuota<MAX_NOMINATORS>;
type RewardRemainder = Treasury;
type RuntimeEvent = RuntimeEvent;
type Slash = Treasury;
type Reward = ();
type SessionsPerEra = SessionsPerEra;
type BondingDuration = BondingDuration;
type SlashDeferDuration = SlashDeferDuration;
type SessionInterface = Self;
type EraPayout = ExponentialEraPayout;
type NextNewSession = Session;
type MaxExposurePageSize = MaxExposurePageSize;
type OffendingValidatorsThreshold = OffendingValidatorsThreshold;
type VoterList = pallet_staking::UseNominatorsAndValidatorsMap<Runtime>;
type MaxUnlockingChunks = ConstU32<16>;
type MaxControllersInDeprecationBatch = ConstU32<4084>;
type BenchmarkingConfig = StakingBenchmarkingConfig;
type WeightInfo = PayoutStakersDecreasedWeightInfo;
type CurrencyBalance = Balance;
type HistoryDepth = HistoryDepth;
type TargetList = pallet_staking::UseValidatorsMap<Self>;
type AdminOrigin = EnsureRoot<AccountId>;
type EventListeners = NominationPools;
}
parameter_types! {
pub const MinimumPeriod: u64 = MILLISECS_PER_BLOCK / 2;
}
impl pallet_timestamp::Config for Runtime {
/// A timestamp: milliseconds since the unix epoch.
type Moment = u64;
type OnTimestampSet = Aura;
type MinimumPeriod = MinimumPeriod;
type WeightInfo = ();
}
impl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime
where
RuntimeCall: From<C>,
{
type Extrinsic = UncheckedExtrinsic;
type OverarchingCall = RuntimeCall;
}
parameter_types! {
pub const MinVestedTransfer: Balance = MICRO_AZERO;
pub UnvestedFundsAllowedWithdrawReasons: WithdrawReasons = WithdrawReasons::except(WithdrawReasons::TRANSFER | WithdrawReasons::RESERVE);
}
impl pallet_vesting::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type BlockNumberToBalance = ConvertInto;
type MinVestedTransfer = MinVestedTransfer;
type WeightInfo = pallet_vesting::weights::SubstrateWeight<Runtime>;
type UnvestedFundsAllowedWithdrawReasons = UnvestedFundsAllowedWithdrawReasons;
type BlockNumberProvider = System;
// Maximum number of vesting schedules an account may have at a given moment
// follows polkadot https://github.com/paritytech/polkadot/blob/9ce5f7ef5abb1a4291454e8c9911b304d80679f9/runtime/polkadot/src/lib.rs#L980
const MAX_VESTING_SCHEDULES: u32 = 28;
}
parameter_types! {
// One storage item; key size is 32+32; value is size 4+4+16+32 bytes = 56 bytes.
pub const DepositBase: Balance = 120 * LEGACY_DEPOSIT_PER_BYTE;
// Additional storage item size of 32 bytes.
pub const DepositFactor: Balance = 32 * LEGACY_DEPOSIT_PER_BYTE;
pub const MaxSignatories: u16 = 100;
}
impl pallet_multisig::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
type Currency = Balances;
type DepositBase = DepositBase;
type DepositFactor = DepositFactor;
type MaxSignatories = MaxSignatories;
type WeightInfo = pallet_multisig::weights::SubstrateWeight<Runtime>;
}
#[cfg(not(feature = "enable_treasury_proposals"))]
// This value effectively disables treasury.
pub const TREASURY_PROPOSAL_BOND: Balance = 100_000_000_000 * TOKEN;
#[cfg(feature = "enable_treasury_proposals")]
pub const TREASURY_PROPOSAL_BOND: Balance = 100 * TOKEN;
parameter_types! {
// We do not burn any money within treasury.
pub const Burn: Permill = Permill::from_percent(0);
// The fraction of the proposal that the proposer should deposit.
// We agreed on non-progressive deposit.
pub const ProposalBond: Permill = Permill::from_percent(0);
// The minimal deposit for proposal.
pub const ProposalBondMinimum: Balance = TREASURY_PROPOSAL_BOND;
// The upper bound of the deposit for the proposal.
pub const ProposalBondMaximum: Balance = TREASURY_PROPOSAL_BOND;
// Maximum number of approvals that can wait in the spending queue.
pub const MaxApprovals: u32 = 20;
// Every 4 hours we fund accepted proposals.
pub const SpendPeriod: AlephBlockNumber = 4 * BLOCKS_PER_HOUR;
pub const TreasuryPalletId: PalletId = PalletId(*b"a0/trsry");
pub TreasuryAccount: AccountId = Treasury::account_id();
}
pub struct TreasuryGovernance;
impl SortedMembers<AccountId> for TreasuryGovernance {
fn sorted_members() -> Vec<AccountId> {
pallet_sudo::Pallet::<Runtime>::key().into_iter().collect()
}
}
impl pallet_treasury::Config for Runtime {
type ApproveOrigin = EnsureSignedBy<TreasuryGovernance, AccountId>;
type Burn = Burn;
type BurnDestination = ();
type Currency = Balances;
type RuntimeEvent = RuntimeEvent;
type MaxApprovals = MaxApprovals;
type OnSlash = ();
type PalletId = TreasuryPalletId;
type ProposalBond = ProposalBond;
type ProposalBondMinimum = ProposalBondMinimum;
type ProposalBondMaximum = ProposalBondMaximum;
type RejectOrigin = EnsureSignedBy<TreasuryGovernance, AccountId>;
type SpendFunds = ();
type SpendOrigin = frame_support::traits::NeverEnsureOrigin<u128>;
type SpendPeriod = SpendPeriod;
type WeightInfo = pallet_treasury::weights::SubstrateWeight<Runtime>;
type AssetKind = ();
type Beneficiary = Self::AccountId;
type BeneficiaryLookup = IdentityLookup<Self::AccountId>;
type Paymaster = PayFromAccount<Balances, TreasuryAccount>;
type BalanceConverter = UnityAssetBalanceConversion;
type PayoutPeriod = ConstU32<0>;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper = ();
}
impl pallet_utility::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
type WeightInfo = pallet_utility::weights::SubstrateWeight<Runtime>;
type PalletsOrigin = OriginCaller;
}
parameter_types! {
// Refundable deposit per storage item
pub const DepositPerItem: Balance = 32 * CONTRACT_DEPOSIT_PER_BYTE;
// Refundable deposit per byte of storage
pub const DepositPerByte: Balance = CONTRACT_DEPOSIT_PER_BYTE;
// How much weight of each block can be spent on the lazy deletion queue of terminated contracts
pub DeletionWeightLimit: Weight = Perbill::from_percent(10) * BlockWeights::get().max_block; // 40ms
// Maximum size of the lazy deletion queue of terminated contracts.
pub const DeletionQueueDepth: u32 = 128;
pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();
pub CodeHashLockupDepositPercent: Perbill = Perbill::from_percent(30);
}
// The filter for the runtime calls that are allowed to be executed by contracts.
// Currently we allow only staking and nomination pools calls.
pub enum ContractsCallRuntimeFilter {}
impl Contains<RuntimeCall> for ContractsCallRuntimeFilter {
fn contains(call: &RuntimeCall) -> bool {
matches!(
call,
RuntimeCall::Staking(_) | RuntimeCall::NominationPools(_)
)
}
}
impl pallet_contracts::Config for Runtime {
type Time = Timestamp;
type Randomness = RandomnessCollectiveFlip;
type Currency = Balances;
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
type CallFilter = ContractsCallRuntimeFilter;
type WeightPrice = pallet_transaction_payment::Pallet<Self>;
type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;
type ChainExtension = ();
type Schedule = Schedule;
type CallStack = [pallet_contracts::Frame<Self>; 16];
type DepositPerByte = DepositPerByte;
type DefaultDepositLimit = ConstU128<{ u128::MAX }>;
type DepositPerItem = DepositPerItem;
type AddressGenerator = pallet_contracts::DefaultAddressGenerator;
type MaxCodeLen = ConstU32<{ 256 * 1024 }>;
type MaxStorageKeyLen = ConstU32<128>;
type UnsafeUnstableInterface = ConstBool<false>;
type MaxDebugBufferLen = ConstU32<{ 2 * 1024 * 1024 }>;
type RuntimeHoldReason = RuntimeHoldReason;
type Migrations = ();
type MaxDelegateDependencies = ConstU32<32>;
type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent;
type Debug = ();
type Environment = ();
type Xcm = ();
}
parameter_types! {
// bytes count taken from:
// https://github.com/paritytech/polkadot/blob/016dc7297101710db0483ab6ef199e244dff711d/runtime/kusama/src/lib.rs#L995
pub const BasicDeposit: Balance = 258 * LEGACY_DEPOSIT_PER_BYTE;
pub const ByteDeposit: Balance = 66 * LEGACY_DEPOSIT_PER_BYTE;
pub const SubAccountDeposit: Balance = 53 * LEGACY_DEPOSIT_PER_BYTE;
pub const MaxSubAccounts: u32 = 100;
pub const MaxAdditionalFields: u32 = 100;
pub const MaxRegistrars: u32 = 20;
}
impl pallet_identity::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type BasicDeposit = BasicDeposit;
type ByteDeposit = ByteDeposit;
type SubAccountDeposit = SubAccountDeposit;
type MaxSubAccounts = MaxSubAccounts;
type MaxRegistrars = MaxRegistrars;
type Slashed = Treasury;
type ForceOrigin = EnsureRoot<AccountId>;
type RegistrarOrigin = EnsureRoot<AccountId>;
type OffchainSignature = Signature;
type SigningPublicKey = <Signature as Verify>::Signer;
type UsernameAuthorityOrigin = EnsureRoot<AccountId>;
type PendingUsernameExpiration = ConstU32<{ 7 * DAYS }>;
type MaxSuffixLength = ConstU32<7>;
type MaxUsernameLength = ConstU32<32>;
type WeightInfo = pallet_identity::weights::SubstrateWeight<Self>;
type IdentityInformation = IdentityInfo<MaxAdditionalFields>;
}
parameter_types! {
// Key size = 32, value size = 8
pub const ProxyDepositBase: Balance = 40 * LEGACY_DEPOSIT_PER_BYTE;
// One storage item (32) plus `ProxyType` (1) encode len.
pub const ProxyDepositFactor: Balance = 33 * LEGACY_DEPOSIT_PER_BYTE;
// Key size = 32, value size 8
pub const AnnouncementDepositBase: Balance = 40 * LEGACY_DEPOSIT_PER_BYTE;
// AccountId, Hash and BlockNumber sum up to 68
pub const AnnouncementDepositFactor: Balance = 68 * LEGACY_DEPOSIT_PER_BYTE;
}
#[derive(
Copy,
Clone,
Eq,
PartialEq,
Ord,
PartialOrd,
Encode,
Decode,
RuntimeDebug,
MaxEncodedLen,
scale_info::TypeInfo,
)]
pub enum ProxyType {
Any = 0,
NonTransfer = 1,
Staking = 2,
Nomination = 3,
}
impl Default for ProxyType {
fn default() -> Self {
Self::Any
}
}
impl InstanceFilter<RuntimeCall> for ProxyType {
fn filter(&self, c: &RuntimeCall) -> bool {
match self {
ProxyType::Any => true,
ProxyType::NonTransfer => matches!(
c,
RuntimeCall::Staking(..)
| RuntimeCall::Session(..)
| RuntimeCall::Treasury(..)
| RuntimeCall::Vesting(pallet_vesting::Call::vest { .. })
| RuntimeCall::Vesting(pallet_vesting::Call::vest_other { .. })
| RuntimeCall::Vesting(pallet_vesting::Call::merge_schedules { .. })
| RuntimeCall::Utility(..)
| RuntimeCall::Multisig(..)
| RuntimeCall::NominationPools(..)
),
ProxyType::Staking => {
matches!(
c,
RuntimeCall::Staking(..)
| RuntimeCall::Session(..)
| RuntimeCall::Utility(..)
| RuntimeCall::NominationPools(..)
)
}
ProxyType::Nomination => {
matches!(
c,
RuntimeCall::Staking(pallet_staking::Call::nominate { .. })
)
}
}
}
fn is_superset(&self, o: &Self) -> bool {
// ProxyType::Nomination ⊆ ProxyType::Staking ⊆ ProxyType::NonTransfer ⊆ ProxyType::Any
match self {
ProxyType::Any => true,
ProxyType::NonTransfer => match o {
ProxyType::Any => false,
ProxyType::NonTransfer | ProxyType::Staking | ProxyType::Nomination => true,
},
ProxyType::Staking => match o {
ProxyType::Any | ProxyType::NonTransfer => false,
ProxyType::Staking | ProxyType::Nomination => true,
},
ProxyType::Nomination => match o {
ProxyType::Any | ProxyType::NonTransfer | ProxyType::Staking => false,
ProxyType::Nomination => true,
},
}
}
}
impl pallet_proxy::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
type Currency = Balances;
type ProxyType = ProxyType;
type ProxyDepositBase = ProxyDepositBase;
type ProxyDepositFactor = ProxyDepositFactor;
type MaxProxies = ConstU32<32>;
type WeightInfo = pallet_proxy::weights::SubstrateWeight<Runtime>;
type MaxPending = ConstU32<32>;
type CallHasher = BlakeTwo256;
type AnnouncementDepositBase = AnnouncementDepositBase;
type AnnouncementDepositFactor = AnnouncementDepositFactor;
}
parameter_types! {
pub const DisallowPermissionlessEnterDuration: AlephBlockNumber = 0;
pub const DisallowPermissionlessExtendDuration: AlephBlockNumber = 0;
// Safe mode on enter will last 1 session
pub const RootEnterDuration: AlephBlockNumber = DEFAULT_SESSION_PERIOD;
// Safe mode on extend will 1 session
pub const RootExtendDuration: AlephBlockNumber = DEFAULT_SESSION_PERIOD;
pub const DisallowPermissionlessEntering: Option<Balance> = None;
pub const DisallowPermissionlessExtending: Option<Balance> = None;
pub const DisallowPermissionlessRelease: Option<AlephBlockNumber> = None;
}
/// Calls that can bypass the safe-mode pallet.
pub struct SafeModeWhitelistedCalls;
impl Contains<RuntimeCall> for SafeModeWhitelistedCalls {
fn contains(call: &RuntimeCall) -> bool {
matches!(
call,
RuntimeCall::Sudo(_)
| RuntimeCall::System(_)
| RuntimeCall::SafeMode(_)
| RuntimeCall::Timestamp(_)
)
}
}
impl pallet_safe_mode::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type RuntimeHoldReason = RuntimeHoldReason;
type WhitelistedCalls = SafeModeWhitelistedCalls;
type EnterDuration = DisallowPermissionlessEnterDuration;
type ExtendDuration = DisallowPermissionlessExtendDuration;
type EnterDepositAmount = DisallowPermissionlessEntering;
type ExtendDepositAmount = DisallowPermissionlessExtending;
type ForceEnterOrigin = EnsureRootWithSuccess<AccountId, RootEnterDuration>;
type ForceExtendOrigin = EnsureRootWithSuccess<AccountId, RootExtendDuration>;
type ForceExitOrigin = EnsureRoot<AccountId>;
type ForceDepositOrigin = EnsureRoot<AccountId>;
type Notify = ();
type ReleaseDelay = DisallowPermissionlessRelease;
type WeightInfo = pallet_safe_mode::weights::SubstrateWeight<Runtime>;
}
/// Calls that can bypass the tx-pause pallet.
/// We always allow system calls and timestamp since it is required for block production
pub struct TxPauseWhitelistedCalls;
impl Contains<RuntimeCallNameOf<Runtime>> for TxPauseWhitelistedCalls {
fn contains(full_name: &RuntimeCallNameOf<Runtime>) -> bool {
matches!(full_name.0.as_slice(), b"Sudo" | b"System" | b"Timestamp")
}
}
impl pallet_tx_pause::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
type PauseOrigin = EnsureRoot<AccountId>;
type UnpauseOrigin = EnsureRoot<AccountId>;
type WhitelistedCalls = TxPauseWhitelistedCalls;
type MaxNameLen = ConstU32<256>;
type WeightInfo = pallet_tx_pause::weights::SubstrateWeight<Runtime>;
}
// Create the runtime by composing the FRAME pallets that were previously configured.
construct_runtime!(
pub struct Runtime {
System: frame_system = 0,
RandomnessCollectiveFlip: pallet_insecure_randomness_collective_flip = 1,
Scheduler: pallet_scheduler = 2,
Aura: pallet_aura = 3,
Timestamp: pallet_timestamp = 4,
Balances: pallet_balances = 5,
TransactionPayment: pallet_transaction_payment = 6,
Authorship: pallet_authorship = 7,
Staking: pallet_staking = 8,
History: pallet_session::historical = 9,
Session: pallet_session = 10,
Aleph: pallet_aleph = 11,
Elections: pallet_elections = 12,
Treasury: pallet_treasury = 13,
Vesting: pallet_vesting = 14,
Utility: pallet_utility = 15,
Multisig: pallet_multisig = 16,