lib.rs 77.6 KB
Newer Older
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1
// Copyright 2017-2020 Parity Technologies (UK) Ltd.
Gav's avatar
Gav committed
2
3
4
5
6
7
8
9
10
11
12
13
14
// This file is part of Polkadot.

// Polkadot 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.

// Polkadot 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
15
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
Gav's avatar
Gav committed
16

17
//! The Kusama runtime. This can be compiled with `#[no_std]`, ready for Wasm.
Gav's avatar
Gav committed
18
19

#![cfg_attr(not(feature = "std"), no_std)]
20
// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
21
#![recursion_limit = "256"]
Gav Wood's avatar
Gav Wood committed
22

Albrecht's avatar
Albrecht committed
23
use pallet_transaction_payment::CurrencyAdapter;
24
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
25
use primitives::v1::{
26
	AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt,
27
28
29
	CoreState, GroupRotationInfo, Hash, Id as ParaId, InboundDownwardMessage, InboundHrmpMessage,
	Moment, Nonce, OccupiedCoreAssumption, PersistedValidationData, SessionInfo, Signature,
	ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex,
30
};
31
use runtime_common::{
32
33
34
35
36
37
38
39
40
41
42
43
44
45
	auctions, claims, crowdloan, impls::DealWithFees, paras_registrar, slots, xcm_sender,
	BlockHashCount, BlockLength, BlockWeights, CurrencyToVote, OffchainSolutionLengthLimit,
	OffchainSolutionWeightLimit, RocksDbWeight, SlowAdjustingFeeUpdate, ToAuthor,
};
use sp_core::u32_trait::{_1, _2, _3, _5};
use sp_std::{collections::btree_map::BTreeMap, prelude::*};

use runtime_parachains::{
	configuration as parachains_configuration, dmp as parachains_dmp, hrmp as parachains_hrmp,
	inclusion as parachains_inclusion, initializer as parachains_initializer,
	origin as parachains_origin, paras as parachains_paras,
	paras_inherent as parachains_paras_inherent, reward_points as parachains_reward_points,
	runtime_api_impl::v1 as parachains_runtime_api_impl, scheduler as parachains_scheduler,
	session_info as parachains_session_info, shared as parachains_shared, ump as parachains_ump,
46
};
47

48
49
50
51
use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId;
use beefy_primitives::crypto::AuthorityId as BeefyId;
use frame_support::{
	construct_runtime, parameter_types,
52
53
54
55
	traits::{
		Contains, Everything, InstanceFilter, KeyOwnerProofSystem, LockIdentifier, Nothing,
		OnRuntimeUpgrade,
	},
56
57
	weights::Weight,
	PalletId, RuntimeDebug,
58
};
59
60
61
62
63
64
use frame_system::{EnsureOneOf, EnsureRoot};
use pallet_grandpa::{fg_primitives, AuthorityId as GrandpaId};
use pallet_im_online::sr25519::AuthorityId as ImOnlineId;
use pallet_mmr_primitives as mmr;
use pallet_session::historical as session_historical;
use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo};
65
use sp_arithmetic::Perquintill;
66
use sp_core::OpaqueMetadata;
67
use sp_runtime::{
68
	create_runtime_str, generic, impl_opaque_keys,
69
	traits::{
70
71
		AccountIdLookup, BlakeTwo256, Block as BlockT, ConvertInto, Extrinsic as ExtrinsicT,
		OpaqueKeys, SaturatedConversion, Verify,
72
	},
73
74
	transaction_validity::{TransactionPriority, TransactionSource, TransactionValidity},
	ApplyExtrinsicResult, KeyTypeId, Perbill, Percent, Permill,
Gav Wood's avatar
Gav Wood committed
75
};
76
use sp_staking::SessionIndex;
77
#[cfg(any(feature = "std", test))]
78
use sp_version::NativeVersion;
79
use sp_version::RuntimeVersion;
80
use static_assertions::const_assert;
Gavin Wood's avatar
Gavin Wood committed
81
use xcm::latest::prelude::*;
82
83
84
85
86
87
88
89
use xcm_builder::{
	AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom,
	BackingToPlurality, ChildParachainAsNative, ChildParachainConvertsVia,
	ChildSystemParachainAsSuperuser, CurrencyAdapter as XcmCurrencyAdapter, FixedWeightBounds,
	IsChildSystemParachain, IsConcrete, LocationInverter, SignedAccountId32AsNative,
	SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, UsingComponents,
};
use xcm_executor::XcmExecutor;
90

91
92
pub use pallet_balances::Call as BalancesCall;
pub use pallet_election_provider_multi_phase::Call as EPMCall;
Gav Wood's avatar
Gav Wood committed
93
#[cfg(feature = "std")]
94
pub use pallet_staking::StakerStatus;
95
pub use pallet_timestamp::Call as TimestampCall;
96
#[cfg(any(feature = "std", test))]
97
pub use sp_runtime::BuildStorage;
98
99
100

/// Constant values used within the runtime.
pub mod constants;
101
use constants::{currency::*, fee::*, time::*};
102

103
104
105
// Weights used in the runtime.
mod weights;

106
107
108
// Voter bag threshold definitions.
mod voter_bags;

109
110
111
#[cfg(test)]
mod tests;

112
113
114
115
// Make the WASM binary available.
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));

116
117
118
119
/// Runtime version (Kusama).
pub const VERSION: RuntimeVersion = RuntimeVersion {
	spec_name: create_runtime_str!("kusama"),
	impl_name: create_runtime_str!("parity-kusama"),
120
	authoring_version: 2,
121
	spec_version: 9110,
122
	impl_version: 0,
123
	#[cfg(not(feature = "disable-runtime-api"))]
124
	apis: RUNTIME_API_VERSIONS,
125
	#[cfg(feature = "disable-runtime-api")]
126
	apis: version::create_apis_vec![[]],
127
	transaction_version: 7,
128
};
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
129

130
131
132
133
/// The BABE epoch configuration at genesis.
pub const BABE_GENESIS_EPOCH_CONFIG: babe_primitives::BabeEpochConfiguration =
	babe_primitives::BabeEpochConfiguration {
		c: PRIMARY_PROBABILITY,
134
		allowed_slots: babe_primitives::AllowedSlots::PrimaryAndSecondaryVRFSlots,
135
136
	};

137
138
139
/// Native version.
#[cfg(any(feature = "std", test))]
pub fn native_version() -> NativeVersion {
140
	NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
141
142
}

143
/// Don't allow swaps until parathread story is more mature.
144
pub struct BaseFilter;
145
146
impl Contains<Call> for BaseFilter {
	fn contains(c: &Call) -> bool {
147
		!matches!(c, Call::Registrar(paras_registrar::Call::swap { .. }))
148
149
150
	}
}

Gavin Wood's avatar
Gavin Wood committed
151
152
153
type MoreThanHalfCouncil = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
154
	pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>,
Gavin Wood's avatar
Gavin Wood committed
155
156
>;

157
parameter_types! {
158
	pub const Version: RuntimeVersion = VERSION;
159
	pub const SS58Prefix: u8 = 2;
160
161
}

162
impl frame_system::Config for Runtime {
163
	type BaseCallFilter = BaseFilter;
164
165
	type BlockWeights = BlockWeights;
	type BlockLength = BlockLength;
166
	type Origin = Origin;
167
	type Call = Call;
Gav Wood's avatar
Gav Wood committed
168
	type Index = Nonce;
169
170
171
172
	type BlockNumber = BlockNumber;
	type Hash = Hash;
	type Hashing = BlakeTwo256;
	type AccountId = AccountId;
173
	type Lookup = AccountIdLookup<AccountId, ()>;
174
	type Header = generic::Header<BlockNumber, BlakeTwo256>;
Gav's avatar
Gav committed
175
	type Event = Event;
176
	type BlockHashCount = BlockHashCount;
177
	type DbWeight = RocksDbWeight;
178
	type Version = Version;
179
	type PalletInfo = PalletInfo;
180
	type AccountData = pallet_balances::AccountData<Balance>;
181
	type OnNewAccount = ();
182
	type OnKilledAccount = ();
183
	type SystemWeightInfo = weights::frame_system::WeightInfo<Runtime>;
184
	type SS58Prefix = SS58Prefix;
185
	type OnSetCode = ();
186
187
}

188
parameter_types! {
189
190
	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) *
		BlockWeights::get().max_block;
191
192
193
	pub const MaxScheduledPerBlock: u32 = 50;
}

194
195
196
type ScheduleOrigin = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
197
	pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>,
198
199
>;

200
impl pallet_scheduler::Config for Runtime {
Gavin Wood's avatar
Gavin Wood committed
201
202
	type Event = Event;
	type Origin = Origin;
203
	type PalletsOrigin = OriginCaller;
Gavin Wood's avatar
Gavin Wood committed
204
	type Call = Call;
205
	type MaximumWeight = MaximumSchedulerWeight;
206
	type ScheduleOrigin = ScheduleOrigin;
207
	type MaxScheduledPerBlock = MaxScheduledPerBlock;
208
	type WeightInfo = weights::pallet_scheduler::WeightInfo<Runtime>;
Gavin Wood's avatar
Gavin Wood committed
209
210
}

211
parameter_types! {
212
	pub const EpochDuration: u64 = EPOCH_DURATION_IN_SLOTS as u64;
213
	pub const ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK;
214
215
	pub const ReportLongevity: u64 =
		BondingDuration::get() as u64 * SessionsPerEra::get() as u64 * EpochDuration::get();
216
217
}

218
impl pallet_babe::Config for Runtime {
219
220
	type EpochDuration = EpochDuration;
	type ExpectedBlockTime = ExpectedBlockTime;
221
222

	// session module is the trigger
223
	type EpochChangeTrigger = pallet_babe::ExternalTrigger;
224

225
226
	type DisabledValidators = Session;

227
228
	type KeyOwnerProof = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
		KeyTypeId,
229
		pallet_babe::AuthorityId,
230
231
232
233
	)>>::Proof;

	type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
		KeyTypeId,
234
		pallet_babe::AuthorityId,
235
236
	)>>::IdentificationTuple;

237
238
	type KeyOwnerProofSystem = Historical;

239
	type HandleEquivocation =
240
		pallet_babe::EquivocationHandler<Self::KeyOwnerIdentification, Offences, ReportLongevity>;
241
242

	type WeightInfo = ();
243
244

	type MaxAuthorities = MaxAuthorities;
245
246
}

Gavin Wood's avatar
Gavin Wood committed
247
parameter_types! {
248
	pub const IndexDeposit: Balance = 100 * CENTS;
Gavin Wood's avatar
Gavin Wood committed
249
250
}

251
impl pallet_indices::Config for Runtime {
Gav Wood's avatar
Gav Wood committed
252
	type AccountIndex = AccountIndex;
253
254
	type Currency = Balances;
	type Deposit = IndexDeposit;
Gav Wood's avatar
Gav Wood committed
255
	type Event = Event;
256
	type WeightInfo = weights::pallet_indices::WeightInfo<Runtime>;
Gav Wood's avatar
Gav Wood committed
257
258
}

Gavin Wood's avatar
Gavin Wood committed
259
parameter_types! {
Gavin Wood's avatar
Gavin Wood committed
260
	pub const ExistentialDeposit: Balance = 1 * CENTS;
261
	pub const MaxLocks: u32 = 50;
Gavin Wood's avatar
Gavin Wood committed
262
	pub const MaxReserves: u32 = 50;
Gavin Wood's avatar
Gavin Wood committed
263
264
}

265
impl pallet_balances::Config for Runtime {
Gav's avatar
Gav committed
266
	type Balance = Balance;
267
	type DustRemoval = ();
Gavin Wood's avatar
Gavin Wood committed
268
	type Event = Event;
Gavin Wood's avatar
Gavin Wood committed
269
	type ExistentialDeposit = ExistentialDeposit;
270
	type AccountStore = System;
271
	type MaxLocks = MaxLocks;
Gavin Wood's avatar
Gavin Wood committed
272
273
274
	type MaxReserves = MaxReserves;
	type ReserveIdentifier = [u8; 8];
	type WeightInfo = weights::pallet_balances::WeightInfo<Runtime>;
275
276
277
278
279
280
}

parameter_types! {
	pub const TransactionByteFee: Balance = 10 * MILLICENTS;
}

281
impl pallet_transaction_payment::Config for Runtime {
Albrecht's avatar
Albrecht committed
282
	type OnChargeTransaction = CurrencyAdapter<Balances, DealWithFees<Self>>;
Gavin Wood's avatar
Gavin Wood committed
283
	type TransactionByteFee = TransactionByteFee;
284
	type WeightToFee = WeightToFee;
285
	type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
Gav's avatar
Gav committed
286
287
}

288
parameter_types! {
289
	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;
290
}
291
impl pallet_timestamp::Config for Runtime {
292
	type Moment = u64;
293
	type OnTimestampSet = Babe;
294
	type MinimumPeriod = MinimumPeriod;
295
	type WeightInfo = weights::pallet_timestamp::WeightInfo<Runtime>;
296
297
}

Gavin Wood's avatar
Gavin Wood committed
298
parameter_types! {
299
	pub const UncleGenerations: u32 = 0;
Gavin Wood's avatar
Gavin Wood committed
300
301
}

302
impl pallet_authorship::Config for Runtime {
303
	type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Babe>;
Gavin Wood's avatar
Gavin Wood committed
304
305
	type UncleGenerations = UncleGenerations;
	type FilterUncle = ();
Gavin Wood's avatar
Gavin Wood committed
306
	type EventHandler = (Staking, ImOnline);
Gavin Wood's avatar
Gavin Wood committed
307
308
}

309
310
311
312
313
314
parameter_types! {
	pub const Period: BlockNumber = 10 * MINUTES;
	pub const Offset: BlockNumber = 0;
}

impl_opaque_keys! {
315
	pub struct SessionKeys {
Gavin Wood's avatar
Gavin Wood committed
316
317
318
		pub grandpa: Grandpa,
		pub babe: Babe,
		pub im_online: ImOnline,
319
		pub para_validator: Initializer,
320
		pub para_assignment: ParaSessionInfo,
Gavin Wood's avatar
Gavin Wood committed
321
		pub authority_discovery: AuthorityDiscovery,
322
	}
323
324
}

thiolliere's avatar
thiolliere committed
325
326
327
328
parameter_types! {
	pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(17);
}

329
impl pallet_session::Config for Runtime {
Gav's avatar
Gav committed
330
	type Event = Event;
331
	type ValidatorId = AccountId;
332
	type ValidatorIdOf = pallet_staking::StashOf<Self>;
Gavin Wood's avatar
Gavin Wood committed
333
	type ShouldEndSession = Babe;
334
	type NextSessionRotation = Babe;
335
	type SessionManager = pallet_session::historical::NoteHistoricalRoot<Self, Staking>;
Gavin Wood's avatar
Gavin Wood committed
336
337
	type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
	type Keys = SessionKeys;
thiolliere's avatar
thiolliere committed
338
	type DisabledValidatorsThreshold = DisabledValidatorsThreshold;
339
	type WeightInfo = weights::pallet_session::WeightInfo<Runtime>;
340
341
}

342
impl pallet_session::historical::Config for Runtime {
343
344
	type FullIdentification = pallet_staking::Exposure<AccountId, Balance>;
	type FullIdentificationOf = pallet_staking::ExposureOf<Runtime>;
345
346
}

347
parameter_types! {
348
349
	// phase durations. 1/4 of the last session for each.
	pub const SignedPhase: u32 = EPOCH_DURATION_IN_SLOTS / 4;
350
	pub const UnsignedPhase: u32 = EPOCH_DURATION_IN_SLOTS / 4;
351

352
353
	// signed config
	pub const SignedMaxSubmissions: u32 = 16;
354
355
	pub const SignedDepositBase: Balance = deposit(2, 0);
	pub const SignedDepositByte: Balance = deposit(0, 10) / 1024;
356
357
	// Each good submission will get 1/10 KSM as reward
	pub SignedRewardBase: Balance =  UNITS / 10;
358
	pub SolutionImprovementThreshold: Perbill = Perbill::from_rational(5u32, 10_000);
359
360

	// miner configs
361
	pub OffchainRepeat: BlockNumber = 5;
362
363
364
365
366

	/// Whilst `UseNominatorsAndUpdateBagsList` or `UseNominatorsMap` is in use, this can still be a
	/// very large value. Once the `BagsList` is in full motion, staking might open its door to many
	/// more nominators, and this value should instead be what is a "safe" number (e.g. 22500).
	pub const VoterSnapshotPerBlock: u32 = 22_500;
367
368
}

369
370
sp_npos_elections::generate_solution_type!(
	#[compact]
Kian Paimani's avatar
Kian Paimani committed
371
	pub struct NposCompactSolution24::<
372
373
374
		VoterIndex = u32,
		TargetIndex = u16,
		Accuracy = sp_runtime::PerU16,
Kian Paimani's avatar
Kian Paimani committed
375
	>(24)
376
377
);

378
379
380
impl pallet_election_provider_multi_phase::Config for Runtime {
	type Event = Event;
	type Currency = Balances;
381
	type EstimateCallFee = TransactionPayment;
382
	type UnsignedPhase = UnsignedPhase;
383
384
385
386
387
388
389
390
	type SignedMaxSubmissions = SignedMaxSubmissions;
	type SignedRewardBase = SignedRewardBase;
	type SignedDepositBase = SignedDepositBase;
	type SignedDepositByte = SignedDepositByte;
	type SignedDepositWeight = ();
	type SignedMaxWeight = Self::MinerMaxWeight;
	type SlashHandler = (); // burn slashes
	type RewardHandler = (); // nothing to do upon rewards
391
	type SignedPhase = SignedPhase;
392
	type SolutionImprovementThreshold = SolutionImprovementThreshold;
393
	type MinerMaxWeight = OffchainSolutionWeightLimit; // For now use the one from staking.
394
	type MinerMaxLength = OffchainSolutionLengthLimit;
395
	type OffchainRepeat = OffchainRepeat;
396
	type MinerTxPriority = NposSolutionPriority;
397
	type DataProvider = Staking;
398
	type Solution = NposCompactSolution24;
Kian Paimani's avatar
Kian Paimani committed
399
	type Fallback = pallet_election_provider_multi_phase::NoFallback<Self>;
400
401
	type Solver = frame_election_provider_support::SequentialPhragmen<
		AccountId,
Kian Paimani's avatar
Kian Paimani committed
402
		pallet_election_provider_multi_phase::SolutionAccuracyOf<Self>,
403
404
		runtime_common::elections::OffchainRandomBalancing,
	>;
405
	type BenchmarkingConfig = runtime_common::elections::BenchmarkConfig;
406
407
408
409
410
	type ForceOrigin = EnsureOneOf<
		AccountId,
		EnsureRoot<AccountId>,
		pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, CouncilCollective>,
	>;
Kian Paimani's avatar
Kian Paimani committed
411
	type WeightInfo = weights::pallet_election_provider_multi_phase::WeightInfo<Self>;
412
413
414
415
416
417
418
419
420
421
422
423
	type VoterSnapshotPerBlock = VoterSnapshotPerBlock;
}

parameter_types! {
	pub const BagThresholds: &'static [u64] = &voter_bags::THRESHOLDS;
}

impl pallet_bags_list::Config for Runtime {
	type Event = Event;
	type VoteWeightProvider = Staking;
	type WeightInfo = weights::pallet_bags_list::WeightInfo<Runtime>;
	type BagThresholds = BagThresholds;
424
425
}

426
427
428
429
430
431
432
433
fn era_payout(
	total_staked: Balance,
	non_gilt_issuance: Balance,
	max_annual_inflation: Perquintill,
	period_fraction: Perquintill,
	auctioned_slots: u64,
) -> (Balance, Balance) {
	use pallet_staking_reward_fn::compute_inflation;
434
	use sp_arithmetic::traits::Saturating;
435
436
437
438
439
440
441
442
443

	let min_annual_inflation = Perquintill::from_rational(25u64, 1000u64);
	let delta_annual_inflation = max_annual_inflation.saturating_sub(min_annual_inflation);

	// 30% reserved for up to 60 slots.
	let auction_proportion = Perquintill::from_rational(auctioned_slots.min(60), 200u64);

	// Therefore the ideal amount at stake (as a percentage of total issuance) is 75% less the amount that we expect
	// to be taken up with auctions.
444
	let ideal_stake = Perquintill::from_percent(75).saturating_sub(auction_proportion);
445
446
447
448

	let stake = Perquintill::from_rational(total_staked, non_gilt_issuance);
	let falloff = Perquintill::from_percent(5);
	let adjustment = compute_inflation(stake, ideal_stake, falloff);
449
450
	let staking_inflation =
		min_annual_inflation.saturating_add(delta_annual_inflation * adjustment);
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471

	let max_payout = period_fraction * max_annual_inflation * non_gilt_issuance;
	let staking_payout = (period_fraction * staking_inflation) * non_gilt_issuance;
	let rest = max_payout.saturating_sub(staking_payout);

	let other_issuance = non_gilt_issuance.saturating_sub(total_staked);
	if total_staked > other_issuance {
		let _cap_rest = Perquintill::from_rational(other_issuance, total_staked) * staking_payout;
		// We don't do anything with this, but if we wanted to, we could introduce a cap on the treasury amount
		// with: `rest = rest.min(cap_rest);`
	}
	(staking_payout, rest)
}

pub struct EraPayout;
impl pallet_staking::EraPayout<Balance> for EraPayout {
	fn era_payout(
		total_staked: Balance,
		_total_issuance: Balance,
		era_duration_millis: u64,
	) -> (Balance, Balance) {
472
473
474
		// TODO: #3011 Update with proper auctioned slots tracking.
		// This should be fine for the first year of parachains.
		let auctioned_slots: u64 = auctions::Pallet::<Runtime>::auction_counter().into();
475
476
477
478
479
480
481
482
		const MAX_ANNUAL_INFLATION: Perquintill = Perquintill::from_percent(10);
		const MILLISECONDS_PER_YEAR: u64 = 1000 * 3600 * 24 * 36525 / 100;

		era_payout(
			total_staked,
			Gilt::issuance().non_gilt,
			MAX_ANNUAL_INFLATION,
			Perquintill::from_rational(era_duration_millis, MILLISECONDS_PER_YEAR),
483
			auctioned_slots,
484
485
		)
	}
thiolliere's avatar
thiolliere committed
486
487
}

488
parameter_types! {
Gavin Wood's avatar
Gavin Wood committed
489
	// Six sessions in an era (6 hours).
490
	pub const SessionsPerEra: SessionIndex = 6;
Gavin Wood's avatar
Gavin Wood committed
491
	// 28 eras for unbonding (7 days).
492
	pub const BondingDuration: pallet_staking::EraIndex = 28;
493
	// 27 eras in which slashes can be cancelled (slightly less than 7 days).
494
	pub const SlashDeferDuration: pallet_staking::EraIndex = 27;
495
	pub const MaxNominatorRewardedPerValidator: u32 = 256;
496
}
497

Gavin Wood's avatar
Gavin Wood committed
498
499
500
type SlashCancelOrigin = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
501
	pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>,
Gavin Wood's avatar
Gavin Wood committed
502
503
>;

Kian Paimani's avatar
Kian Paimani committed
504
505
506
507
508
impl frame_election_provider_support::onchain::Config for Runtime {
	type Accuracy = runtime_common::elections::OnOnChainAccuracy;
	type DataProvider = Staking;
}

509
impl pallet_staking::Config for Runtime {
510
	const MAX_NOMINATIONS: u32 =
511
		<NposCompactSolution24 as sp_npos_elections::NposSolution>::LIMIT as u32;
Gavin Wood's avatar
Gavin Wood committed
512
	type Currency = Balances;
513
	type UnixTime = Timestamp;
514
	type CurrencyToVote = CurrencyToVote;
515
	type ElectionProvider = ElectionProviderMultiPhase;
Kian Paimani's avatar
Kian Paimani committed
516
	type GenesisElectionProvider = runtime_common::elections::GenesisElectionOf<Self>;
Gavin Wood's avatar
Gavin Wood committed
517
	type RewardRemainder = Treasury;
Gav's avatar
Gav committed
518
	type Event = Event;
519
	type Slash = Treasury;
520
	type Reward = ();
521
522
	type SessionsPerEra = SessionsPerEra;
	type BondingDuration = BondingDuration;
Gavin Wood's avatar
Gavin Wood committed
523
	type SlashDeferDuration = SlashDeferDuration;
Gavin Wood's avatar
Gavin Wood committed
524
525
	// A majority of the council or root can cancel the slash.
	type SlashCancelOrigin = SlashCancelOrigin;
526
	type SessionInterface = Self;
527
	type EraPayout = EraPayout;
528
	type NextNewSession = Session;
529
	type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator;
530
531
532
	// Use the nominators map to iter voters, but also perform the bags-list migration and keep
	// it up-to-date.
	type SortedListProvider = runtime_common::elections::UseNominatorsAndUpdateBagsList<Runtime>;
533
	type WeightInfo = weights::pallet_staking::WeightInfo<Runtime>;
534
535
}

536
parameter_types! {
537
538
	pub const LaunchPeriod: BlockNumber = 7 * DAYS;
	pub const VotingPeriod: BlockNumber = 7 * DAYS;
539
	pub const FastTrackVotingPeriod: BlockNumber = 3 * HOURS;
540
	pub const MinimumDeposit: Balance = 100 * CENTS;
541
542
	pub const EnactmentPeriod: BlockNumber = 8 * DAYS;
	pub const CooloffPeriod: BlockNumber = 7 * DAYS;
Gavin Wood's avatar
Gavin Wood committed
543
	// One cent: $10,000 / MB
Gavin Wood's avatar
Gavin Wood committed
544
	pub const PreimageByteDeposit: Balance = 10 * MILLICENTS;
545
	pub const InstantAllowed: bool = true;
546
	pub const MaxVotes: u32 = 100;
547
	pub const MaxProposals: u32 = 100;
548
549
}

550
impl pallet_democracy::Config for Runtime {
551
552
	type Proposal = Call;
	type Event = Event;
553
	type Currency = Balances;
554
	type EnactmentPeriod = EnactmentPeriod;
Xiliang Chen's avatar
Xiliang Chen committed
555
	type VoteLockingPeriod = EnactmentPeriod;
556
557
558
	type LaunchPeriod = LaunchPeriod;
	type VotingPeriod = VotingPeriod;
	type MinimumDeposit = MinimumDeposit;
559
	/// A straight majority of the council can decide what their next motion is.
560
561
	type ExternalOrigin =
		pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>;
562
	/// A majority can have the next scheduled referendum be a straight majority-carries vote.
563
564
	type ExternalMajorityOrigin =
		pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>;
565
566
	/// A unanimous council can have the next scheduled referendum be a straight default-carries
	/// (NTB) vote.
567
568
	type ExternalDefaultOrigin =
		pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, CouncilCollective>;
Denis_P's avatar
Denis_P committed
569
	/// Two thirds of the technical committee can have an `ExternalMajority/ExternalDefault` vote
570
	/// be tabled immediately and with a shorter voting/enactment period.
571
572
573
574
	type FastTrackOrigin =
		pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, TechnicalCollective>;
	type InstantOrigin =
		pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, TechnicalCollective>;
575
576
	type InstantAllowed = InstantAllowed;
	type FastTrackVotingPeriod = FastTrackVotingPeriod;
577
	// To cancel a proposal which has been passed, 2/3 of the council must agree to it.
578
579
580
581
582
	type CancellationOrigin = EnsureOneOf<
		AccountId,
		EnsureRoot<AccountId>,
		pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, CouncilCollective>,
	>;
583
	type BlacklistOrigin = EnsureRoot<AccountId>;
584
585
586
587
588
589
590
	// To cancel a proposal before it has been passed, the technical committee must be unanimous or
	// Root must agree.
	type CancelProposalOrigin = EnsureOneOf<
		AccountId,
		EnsureRoot<AccountId>,
		pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, TechnicalCollective>,
	>;
591
592
	// Any single technical committee member may veto a coming council proposal, however they can
	// only do it once and it lasts only for the cooloff period.
593
	type VetoOrigin = pallet_collective::EnsureMember<AccountId, TechnicalCollective>;
594
	type CooloffPeriod = CooloffPeriod;
Gavin Wood's avatar
Gavin Wood committed
595
	type PreimageByteDeposit = PreimageByteDeposit;
596
	type OperationalPreimageOrigin = pallet_collective::EnsureMember<AccountId, CouncilCollective>;
Gavin Wood's avatar
Gavin Wood committed
597
	type Slash = Treasury;
Gavin Wood's avatar
Gavin Wood committed
598
	type Scheduler = Scheduler;
599
	type PalletsOrigin = OriginCaller;
600
	type MaxVotes = MaxVotes;
601
602
	type WeightInfo = weights::pallet_democracy::WeightInfo<Runtime>;
	type MaxProposals = MaxProposals;
603
}
604

605
606
parameter_types! {
	pub const CouncilMotionDuration: BlockNumber = 3 * DAYS;
607
	pub const CouncilMaxProposals: u32 = 100;
608
	pub const CouncilMaxMembers: u32 = 100;
609
610
}

611
type CouncilCollective = pallet_collective::Instance1;
612
impl pallet_collective::Config<CouncilCollective> for Runtime {
613
614
615
	type Origin = Origin;
	type Proposal = Call;
	type Event = Event;
616
	type MotionDuration = CouncilMotionDuration;
617
	type MaxProposals = CouncilMaxProposals;
618
	type MaxMembers = CouncilMaxMembers;
Wei Tang's avatar
Wei Tang committed
619
	type DefaultVote = pallet_collective::PrimeDefaultVote;
620
	type WeightInfo = weights::pallet_collective_council::WeightInfo<Runtime>;
621
622
}

Gavin Wood's avatar
Gavin Wood committed
623
parameter_types! {
624
	pub const CandidacyBond: Balance = 100 * CENTS;
Kian Paimani's avatar
Kian Paimani committed
625
626
627
628
629
	// 1 storage item created, key size is 32 bytes, value size is 16+16.
	pub const VotingBondBase: Balance = deposit(1, 64);
	// additional data per vote is 32 bytes (account id).
	pub const VotingBondFactor: Balance = deposit(0, 32);
	/// Daily council elections
Gavin Wood's avatar
Gavin Wood committed
630
	pub const TermDuration: BlockNumber = 24 * HOURS;
631
632
	pub const DesiredMembers: u32 = 19;
	pub const DesiredRunnersUp: u32 = 19;
633
	pub const PhragmenElectionPalletId: LockIdentifier = *b"phrelect";
634
}
Kian Paimani's avatar
Kian Paimani committed
635

636
637
// Make sure that there are no more than MaxMembers members elected via phragmen.
const_assert!(DesiredMembers::get() <= CouncilMaxMembers::get());
638

639
impl pallet_elections_phragmen::Config for Runtime {
640
	type Event = Event;
641
642
	type Currency = Balances;
	type ChangeMembers = Council;
643
	type InitializeMembers = Council;
644
	type CurrencyToVote = frame_support::traits::U128CurrencyToVote;
Gavin Wood's avatar
Gavin Wood committed
645
	type CandidacyBond = CandidacyBond;
Kian Paimani's avatar
Kian Paimani committed
646
647
	type VotingBondBase = VotingBondBase;
	type VotingBondFactor = VotingBondFactor;
648
649
	type LoserCandidate = Treasury;
	type KickedMember = Treasury;
Gavin Wood's avatar
Gavin Wood committed
650
651
652
	type DesiredMembers = DesiredMembers;
	type DesiredRunnersUp = DesiredRunnersUp;
	type TermDuration = TermDuration;
653
	type PalletId = PhragmenElectionPalletId;
654
	type WeightInfo = weights::pallet_elections_phragmen::WeightInfo<Runtime>;
655
656
}

657
658
parameter_types! {
	pub const TechnicalMotionDuration: BlockNumber = 3 * DAYS;
659
	pub const TechnicalMaxProposals: u32 = 100;
660
	pub const TechnicalMaxMembers: u32 = 100;
661
662
}

663
type TechnicalCollective = pallet_collective::Instance2;
664
impl pallet_collective::Config<TechnicalCollective> for Runtime {
665
666
667
	type Origin = Origin;
	type Proposal = Call;
	type Event = Event;
668
	type MotionDuration = TechnicalMotionDuration;
669
	type MaxProposals = TechnicalMaxProposals;
670
	type MaxMembers = TechnicalMaxMembers;
Wei Tang's avatar
Wei Tang committed
671
	type DefaultVote = pallet_collective::PrimeDefaultVote;
672
	type WeightInfo = weights::pallet_collective_technical_committee::WeightInfo<Runtime>;
673
674
}

675
impl pallet_membership::Config<pallet_membership::Instance1> for Runtime {
676
	type Event = Event;
Gavin Wood's avatar
Gavin Wood committed
677
678
679
680
681
	type AddOrigin = MoreThanHalfCouncil;
	type RemoveOrigin = MoreThanHalfCouncil;
	type SwapOrigin = MoreThanHalfCouncil;
	type ResetOrigin = MoreThanHalfCouncil;
	type PrimeOrigin = MoreThanHalfCouncil;
682
683
	type MembershipInitialized = TechnicalCommittee;
	type MembershipChanged = TechnicalCommittee;
684
	type MaxMembers = TechnicalMaxMembers;
Kian Paimani's avatar
Kian Paimani committed
685
	type WeightInfo = weights::pallet_membership::WeightInfo<Runtime>;
686
687
}

Gavin Wood's avatar
Gavin Wood committed
688
689
parameter_types! {
	pub const ProposalBond: Permill = Permill::from_percent(5);
690
	pub const ProposalBondMinimum: Balance = 2000 * CENTS;
691
	pub const SpendPeriod: BlockNumber = 6 * DAYS;
692
	pub const Burn: Permill = Permill::from_perthousand(2);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
693
	pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry");
Gavin Wood's avatar
Gavin Wood committed
694
695
696

	pub const TipCountdown: BlockNumber = 1 * DAYS;
	pub const TipFindersFee: Percent = Percent::from_percent(20);
697
	pub const TipReportDepositBase: Balance = 100 * CENTS;
698
	pub const DataDepositPerByte: Balance = 1 * CENTS;
699
	pub const BountyDepositBase: Balance = 100 * CENTS;
700
701
702
703
	pub const BountyDepositPayoutDelay: BlockNumber = 4 * DAYS;
	pub const BountyUpdatePeriod: BlockNumber = 90 * DAYS;
	pub const MaximumReasonLength: u32 = 16384;
	pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);
704
	pub const BountyValueMinimum: Balance = 200 * CENTS;
705
	pub const MaxApprovals: u32 = 100;
706
	pub const MaxAuthorities: u32 = 100_000;
707
708
709
	pub const MaxKeys: u32 = 10_000;
	pub const MaxPeerInHeartbeats: u32 = 10_000;
	pub const MaxPeerDataEncodingSize: u32 = 1_000;
Gavin Wood's avatar
Gavin Wood committed
710
711
}

Gavin Wood's avatar
Gavin Wood committed
712
713
714
type ApproveOrigin = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
715
	pallet_collective::EnsureProportionAtLeast<_3, _5, AccountId, CouncilCollective>,
Gavin Wood's avatar
Gavin Wood committed
716
717
>;

718
impl pallet_treasury::Config for Runtime {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
719
	type PalletId = TreasuryPalletId;
Gavin Wood's avatar
Gavin Wood committed
720
	type Currency = Balances;
Gavin Wood's avatar
Gavin Wood committed
721
722
	type ApproveOrigin = ApproveOrigin;
	type RejectOrigin = MoreThanHalfCouncil;
723
	type Event = Event;
724
	type OnSlash = Treasury;
Gavin Wood's avatar
Gavin Wood committed
725
726
727
728
	type ProposalBond = ProposalBond;
	type ProposalBondMinimum = ProposalBondMinimum;
	type SpendPeriod = SpendPeriod;
	type Burn = Burn;
729
	type BurnDestination = Society;
730
	type MaxApprovals = MaxApprovals;
731
	type WeightInfo = weights::pallet_treasury::WeightInfo<Runtime>;
732
	type SpendFunds = Bounties;
733
734
735
}

impl pallet_bounties::Config for Runtime {
736
737
738
739
740
	type BountyDepositBase = BountyDepositBase;
	type BountyDepositPayoutDelay = BountyDepositPayoutDelay;
	type BountyUpdatePeriod = BountyUpdatePeriod;
	type BountyCuratorDeposit = BountyCuratorDeposit;
	type BountyValueMinimum = BountyValueMinimum;
741
	type DataDepositPerByte = DataDepositPerByte;
742
	type Event = Event;
743
744
745
746
747
748
	type MaximumReasonLength = MaximumReasonLength;
	type WeightInfo = weights::pallet_bounties::WeightInfo<Runtime>;
}

impl pallet_tips::Config for Runtime {
	type MaximumReasonLength = MaximumReasonLength;
749
	type DataDepositPerByte = DataDepositPerByte;
750
	type Tippers = PhragmenElection;
751
752
753
	type TipCountdown = TipCountdown;
	type TipFindersFee = TipFindersFee;
	type TipReportDepositBase = TipReportDepositBase;
754
	type Event = Event;
755
	type WeightInfo = weights::pallet_tips::WeightInfo<Runtime>;
756
}
757

758
impl pallet_offences::Config for Runtime {
759
	type Event = Event;
760
	type IdentificationTuple = pallet_session::historical::IdentificationTuple<Self>;
761
762
763
	type OnOffenceHandler = Staking;
}

764
765
766
impl pallet_authority_discovery::Config for Runtime {
	type MaxAuthorities = MaxAuthorities;
}
Gavin Wood's avatar
Gavin Wood committed
767

768
parameter_types! {
769
	pub NposSolutionPriority: TransactionPriority =
770
		Perbill::from_percent(90) * TransactionPriority::max_value();
771
772
773
	pub const ImOnlineUnsignedPriority: TransactionPriority = TransactionPriority::max_value();
}

774
impl pallet_im_online::Config for Runtime {
thiolliere's avatar
thiolliere committed
775
	type AuthorityId = ImOnlineId;
776
	type Event = Event;
777
	type ValidatorSet = Historical;
778
	type NextSessionRotation = Babe;
779
	type ReportUnresponsiveness = Offences;
780
	type UnsignedPriority = ImOnlineUnsignedPriority;
781
	type WeightInfo = weights::pallet_im_online::WeightInfo<Runtime>;
782
783
784
	type MaxKeys = MaxKeys;
	type MaxPeerInHeartbeats = MaxPeerInHeartbeats;
	type MaxPeerDataEncodingSize = MaxPeerDataEncodingSize;
785
786
}

787
impl pallet_grandpa::Config for Runtime {
788
	type Event = Event;
789
790
791
792
793
794