lib.rs 74 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
15
16
// 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
// along with Polkadot.  If not, see <http://www.gnu.org/licenses/>.

17
//! The Polkadot 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 runtime_common::{
25
26
27
28
29
30
31
32
33
34
35
36
	auctions, claims, crowdloan, impls::DealWithFees, paras_registrar, slots, BlockHashCount,
	BlockLength, BlockWeights, CurrencyToVote, OffchainSolutionLengthLimit,
	OffchainSolutionWeightLimit, RocksDbWeight, SlowAdjustingFeeUpdate,
};

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,
37
};
Gav Wood's avatar
Gav Wood committed
38

39
40
41
42
use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId;
use beefy_primitives::crypto::AuthorityId as BeefyId;
use frame_support::{
	construct_runtime, parameter_types,
43
	traits::{Contains, KeyOwnerProofSystem, LockIdentifier, OnRuntimeUpgrade},
44
	weights::{constants::WEIGHT_PER_MILLIS, Weight},
45
46
47
48
49
50
51
52
53
	PalletId, RuntimeDebug,
};
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};
use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
54
use primitives::v1::{
55
	AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt,
56
57
58
	CoreState, GroupRotationInfo, Hash, Id as ParaId, InboundDownwardMessage, InboundHrmpMessage,
	Moment, Nonce, OccupiedCoreAssumption, PersistedValidationData, SessionInfo, Signature,
	ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex,
59
60
61
62
};
use sp_core::{
	u32_trait::{_1, _2, _3, _4, _5},
	OpaqueMetadata,
63
64
};
use sp_runtime::{
65
66
67
	create_runtime_str,
	curve::PiecewiseLinear,
	generic, impl_opaque_keys,
68
	traits::{
69
70
		AccountIdLookup, BlakeTwo256, Block as BlockT, ConvertInto, Extrinsic as ExtrinsicT,
		OpaqueKeys, SaturatedConversion, Verify,
71
	},
72
73
	transaction_validity::{TransactionPriority, TransactionSource, TransactionValidity},
	ApplyExtrinsicResult, KeyTypeId, Perbill, Percent, Permill,
74
};
75
76
use sp_staking::SessionIndex;
use sp_std::{collections::btree_map::BTreeMap, prelude::*};
77
#[cfg(any(feature = "std", test))]
78
use sp_version::NativeVersion;
79
use sp_version::RuntimeVersion;
80
use static_assertions::const_assert;
81

82
83
pub use pallet_balances::Call as BalancesCall;
pub use pallet_election_provider_multi_phase::Call as EPMCall;
Gav Wood's avatar
Gav Wood committed
84
#[cfg(feature = "std")]
85
pub use pallet_staking::StakerStatus;
86
pub use pallet_timestamp::Call as TimestampCall;
87
#[cfg(any(feature = "std", test))]
88
pub use sp_runtime::BuildStorage;
89
90
91

/// Constant values used within the runtime.
pub mod constants;
92
use constants::{currency::*, fee::*, time::*};
93
use frame_support::traits::InstanceFilter;
94

95
96
97
// Weights used in the runtime.
mod weights;

98
99
100
101
// Make the WASM binary available.
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));

102
// Polkadot version identifier;
103
/// Runtime version (Polkadot).
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
104
pub const VERSION: RuntimeVersion = RuntimeVersion {
105
106
	spec_name: create_runtime_str!("polkadot"),
	impl_name: create_runtime_str!("parity-polkadot"),
Gavin Wood's avatar
Gavin Wood committed
107
	authoring_version: 0,
108
	spec_version: 9110,
109
	impl_version: 0,
110
	#[cfg(not(feature = "disable-runtime-api"))]
111
	apis: RUNTIME_API_VERSIONS,
112
	#[cfg(feature = "disable-runtime-api")]
113
	apis: version::create_apis_vec![[]],
114
	transaction_version: 8,
115
};
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
116

117
118
119
120
/// The BABE epoch configuration at genesis.
pub const BABE_GENESIS_EPOCH_CONFIG: babe_primitives::BabeEpochConfiguration =
	babe_primitives::BabeEpochConfiguration {
		c: PRIMARY_PROBABILITY,
121
		allowed_slots: babe_primitives::AllowedSlots::PrimaryAndSecondaryVRFSlots,
122
123
	};

124
125
126
/// Native version.
#[cfg(any(feature = "std", test))]
pub fn native_version() -> NativeVersion {
127
	NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
128
129
}

130
pub struct BaseFilter;
131
132
impl Contains<Call> for BaseFilter {
	fn contains(call: &Call) -> bool {
133
		match call {
Gavin Wood's avatar
Gavin Wood committed
134
			// These modules are all allowed to be called by transactions:
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
			Call::Democracy(_) |
			Call::Council(_) |
			Call::TechnicalCommittee(_) |
			Call::TechnicalMembership(_) |
			Call::Treasury(_) |
			Call::PhragmenElection(_) |
			Call::System(_) |
			Call::Scheduler(_) |
			Call::Indices(_) |
			Call::Babe(_) |
			Call::Timestamp(_) |
			Call::Balances(_) |
			Call::Authorship(_) |
			Call::Staking(_) |
			Call::Session(_) |
			Call::Grandpa(_) |
			Call::ImOnline(_) |
			Call::Utility(_) |
			Call::Claims(_) |
			Call::Vesting(_) |
			Call::Identity(_) |
			Call::Proxy(_) |
			Call::Multisig(_) |
			Call::Bounties(_) |
			Call::Tips(_) |
160
161
162
163
164
165
166
167
168
169
170
171
172
			Call::ElectionProviderMultiPhase(_) |
			Call::Configuration(_) |
			Call::ParasShared(_) |
			Call::ParaInclusion(_) |
			Call::Paras(_) |
			Call::Initializer(_) |
			Call::ParaInherent(_) |
			Call::Dmp(_) |
			Call::Ump(_) |
			Call::Hrmp(_) |
			Call::Slots(_) => true,
			// Disable paras registration, crowdloans, and auctions for now.
			Call::Registrar(_) | Call::Auctions(_) | Call::Crowdloan(_) => false,
173
174
175
176
		}
	}
}

Gavin Wood's avatar
Gavin Wood committed
177
178
179
type MoreThanHalfCouncil = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
180
	pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>,
Gavin Wood's avatar
Gavin Wood committed
181
182
>;

183
parameter_types! {
184
	pub const Version: RuntimeVersion = VERSION;
185
	pub const SS58Prefix: u8 = 0;
186
187
}

188
impl frame_system::Config for Runtime {
189
	type BaseCallFilter = BaseFilter;
190
191
	type BlockWeights = BlockWeights;
	type BlockLength = BlockLength;
192
	type Origin = Origin;
193
	type Call = Call;
Gav Wood's avatar
Gav Wood committed
194
	type Index = Nonce;
195
196
197
198
	type BlockNumber = BlockNumber;
	type Hash = Hash;
	type Hashing = BlakeTwo256;
	type AccountId = AccountId;
199
	type Lookup = AccountIdLookup<AccountId, ()>;
200
	type Header = generic::Header<BlockNumber, BlakeTwo256>;
Gav's avatar
Gav committed
201
	type Event = Event;
202
	type BlockHashCount = BlockHashCount;
203
	type DbWeight = RocksDbWeight;
204
	type Version = Version;
205
	type PalletInfo = PalletInfo;
206
	type AccountData = pallet_balances::AccountData<Balance>;
Gavin Wood's avatar
Gavin Wood committed
207
	type OnNewAccount = ();
208
	type OnKilledAccount = ();
209
	type SystemWeightInfo = weights::frame_system::WeightInfo<Runtime>;
210
	type SS58Prefix = SS58Prefix;
211
	type OnSetCode = ();
212
213
}

214
parameter_types! {
215
216
	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) *
		BlockWeights::get().max_block;
217
218
219
	pub const MaxScheduledPerBlock: u32 = 50;
}

220
221
222
type ScheduleOrigin = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
223
	pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>,
224
225
>;

226
impl pallet_scheduler::Config for Runtime {
Gavin Wood's avatar
Gavin Wood committed
227
228
	type Event = Event;
	type Origin = Origin;
229
	type PalletsOrigin = OriginCaller;
Gavin Wood's avatar
Gavin Wood committed
230
	type Call = Call;
231
	type MaximumWeight = MaximumSchedulerWeight;
232
	type ScheduleOrigin = ScheduleOrigin;
233
	type MaxScheduledPerBlock = MaxScheduledPerBlock;
234
	type WeightInfo = weights::pallet_scheduler::WeightInfo<Runtime>;
Gavin Wood's avatar
Gavin Wood committed
235
236
}

237
parameter_types! {
238
	pub const EpochDuration: u64 = EPOCH_DURATION_IN_SLOTS as u64;
239
	pub const ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK;
240
241
	pub const ReportLongevity: u64 =
		BondingDuration::get() as u64 * SessionsPerEra::get() as u64 * EpochDuration::get();
242
243
}

244
impl pallet_babe::Config for Runtime {
245
246
	type EpochDuration = EpochDuration;
	type ExpectedBlockTime = ExpectedBlockTime;
247
248

	// session module is the trigger
249
	type EpochChangeTrigger = pallet_babe::ExternalTrigger;
250

251
252
	type DisabledValidators = Session;

253
254
255
256
	type KeyOwnerProofSystem = Historical;

	type KeyOwnerProof = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
		KeyTypeId,
257
		pallet_babe::AuthorityId,
258
259
260
261
	)>>::Proof;

	type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
		KeyTypeId,
262
		pallet_babe::AuthorityId,
263
264
265
	)>>::IdentificationTuple;

	type HandleEquivocation =
266
		pallet_babe::EquivocationHandler<Self::KeyOwnerIdentification, Offences, ReportLongevity>;
267
268

	type WeightInfo = ();
269
270

	type MaxAuthorities = MaxAuthorities;
271
272
}

Gavin Wood's avatar
Gavin Wood committed
273
parameter_types! {
Gavin Wood's avatar
Gavin Wood committed
274
	pub const IndexDeposit: Balance = 10 * DOLLARS;
Gavin Wood's avatar
Gavin Wood committed
275
276
}

277
impl pallet_indices::Config for Runtime {
Gav Wood's avatar
Gav Wood committed
278
	type AccountIndex = AccountIndex;
279
280
	type Currency = Balances;
	type Deposit = IndexDeposit;
Gav Wood's avatar
Gav Wood committed
281
	type Event = Event;
282
	type WeightInfo = weights::pallet_indices::WeightInfo<Runtime>;
Gav Wood's avatar
Gav Wood committed
283
284
}

Gavin Wood's avatar
Gavin Wood committed
285
parameter_types! {
286
	pub const ExistentialDeposit: Balance = 100 * CENTS;
287
	pub const MaxLocks: u32 = 50;
Gavin Wood's avatar
Gavin Wood committed
288
	pub const MaxReserves: u32 = 50;
Gavin Wood's avatar
Gavin Wood committed
289
290
}

291
impl pallet_balances::Config for Runtime {
Gav's avatar
Gav committed
292
	type Balance = Balance;
293
	type DustRemoval = ();
Gavin Wood's avatar
Gavin Wood committed
294
	type Event = Event;
Gavin Wood's avatar
Gavin Wood committed
295
	type ExistentialDeposit = ExistentialDeposit;
296
	type AccountStore = System;
297
	type MaxLocks = MaxLocks;
Gavin Wood's avatar
Gavin Wood committed
298
299
	type MaxReserves = MaxReserves;
	type ReserveIdentifier = [u8; 8];
300
	type WeightInfo = weights::pallet_balances::WeightInfo<Runtime>;
301
302
303
304
}

parameter_types! {
	pub const TransactionByteFee: Balance = 10 * MILLICENTS;
305
306
307
	/// This value increases the priority of `Operational` transactions by adding
	/// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.
	pub const OperationalFeeMultiplier: u8 = 5;
308
309
}

310
impl pallet_transaction_payment::Config for Runtime {
Albrecht's avatar
Albrecht committed
311
	type OnChargeTransaction = CurrencyAdapter<Balances, DealWithFees<Runtime>>;
Gavin Wood's avatar
Gavin Wood committed
312
	type TransactionByteFee = TransactionByteFee;
313
	type OperationalFeeMultiplier = OperationalFeeMultiplier;
314
	type WeightToFee = WeightToFee;
315
	type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
Gav's avatar
Gav committed
316
317
}

318
parameter_types! {
319
	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;
320
}
321
impl pallet_timestamp::Config for Runtime {
322
	type Moment = u64;
323
	type OnTimestampSet = Babe;
324
	type MinimumPeriod = MinimumPeriod;
325
	type WeightInfo = weights::pallet_timestamp::WeightInfo<Runtime>;
326
327
}

Gavin Wood's avatar
Gavin Wood committed
328
parameter_types! {
329
	pub const UncleGenerations: u32 = 0;
Gavin Wood's avatar
Gavin Wood committed
330
331
332
}

// TODO: substrate#2986 implement this properly
333
impl pallet_authorship::Config for Runtime {
334
	type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Babe>;
Gavin Wood's avatar
Gavin Wood committed
335
336
	type UncleGenerations = UncleGenerations;
	type FilterUncle = ();
Gavin Wood's avatar
Gavin Wood committed
337
	type EventHandler = (Staking, ImOnline);
Gavin Wood's avatar
Gavin Wood committed
338
339
}

340
impl_opaque_keys! {
341
	pub struct SessionKeys {
Gavin Wood's avatar
Gavin Wood committed
342
343
344
		pub grandpa: Grandpa,
		pub babe: Babe,
		pub im_online: ImOnline,
345
346
		pub para_validator: Initializer,
		pub para_assignment: ParaSessionInfo,
Gavin Wood's avatar
Gavin Wood committed
347
		pub authority_discovery: AuthorityDiscovery,
348
	}
349
350
}

351
impl pallet_session::Config for Runtime {
Gav's avatar
Gav committed
352
	type Event = Event;
353
	type ValidatorId = AccountId;
354
	type ValidatorIdOf = pallet_staking::StashOf<Self>;
Gavin Wood's avatar
Gavin Wood committed
355
	type ShouldEndSession = Babe;
356
	type NextSessionRotation = Babe;
357
	type SessionManager = pallet_session::historical::NoteHistoricalRoot<Self, Staking>;
Gavin Wood's avatar
Gavin Wood committed
358
359
	type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
	type Keys = SessionKeys;
360
	type WeightInfo = weights::pallet_session::WeightInfo<Runtime>;
361
362
}

363
impl pallet_session::historical::Config for Runtime {
364
365
	type FullIdentification = pallet_staking::Exposure<AccountId, Balance>;
	type FullIdentificationOf = pallet_staking::ExposureOf<Runtime>;
366
367
}

368
parameter_types! {
369
370
	// phase durations. 1/4 of the last session for each.
	pub const SignedPhase: u32 = EPOCH_DURATION_IN_SLOTS / 4;
371
	pub const UnsignedPhase: u32 = EPOCH_DURATION_IN_SLOTS / 4;
372

373
374
	// signed config
	pub const SignedMaxSubmissions: u32 = 16;
375
376
377
378
	// 40 DOTs fixed deposit..
	pub const SignedDepositBase: Balance = deposit(2, 0);
	// 0.01 DOT per KB of solution data.
	pub const SignedDepositByte: Balance = deposit(0, 10) / 1024;
379
380
	// Each good submission will get 1 DOT as reward
	pub SignedRewardBase: Balance = 1 * UNITS;
381
	pub SolutionImprovementThreshold: Perbill = Perbill::from_rational(5u32, 10_000);
382

383
384
	// 4 hour session, 1 hour unsigned phase, 32 offchain executions.
	pub OffchainRepeat: BlockNumber = UnsignedPhase::get() / 32;
385
386
387
388
389

	/// 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;
390
391
}

392
393
sp_npos_elections::generate_solution_type!(
	#[compact]
394
395
396
397
398
	pub struct NposCompactSolution16::<
		VoterIndex = u32,
		TargetIndex = u16,
		Accuracy = sp_runtime::PerU16,
	>(16)
399
400
);

401
402
403
impl pallet_election_provider_multi_phase::Config for Runtime {
	type Event = Event;
	type Currency = Balances;
404
	type EstimateCallFee = TransactionPayment;
405
406
	type SignedPhase = SignedPhase;
	type UnsignedPhase = UnsignedPhase;
407
408
409
410
411
412
413
414
	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
415
	type SolutionImprovementThreshold = SolutionImprovementThreshold;
416
	type MinerMaxWeight = OffchainSolutionWeightLimit; // For now use the one from staking.
417
	type MinerMaxLength = OffchainSolutionLengthLimit;
418
	type OffchainRepeat = OffchainRepeat;
419
	type MinerTxPriority = NposSolutionPriority;
420
	type DataProvider = Staking;
421
	type Solution = NposCompactSolution16;
Kian Paimani's avatar
Kian Paimani committed
422
	type Fallback = pallet_election_provider_multi_phase::NoFallback<Self>;
423
424
	type Solver = frame_election_provider_support::SequentialPhragmen<
		AccountId,
Kian Paimani's avatar
Kian Paimani committed
425
		pallet_election_provider_multi_phase::SolutionAccuracyOf<Self>,
426
427
		runtime_common::elections::OffchainRandomBalancing,
	>;
428
	type BenchmarkingConfig = runtime_common::elections::BenchmarkConfig;
429
430
431
432
433
	type ForceOrigin = EnsureOneOf<
		AccountId,
		EnsureRoot<AccountId>,
		pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, CouncilCollective>,
	>;
Kian Paimani's avatar
Kian Paimani committed
434
	type WeightInfo = weights::pallet_election_provider_multi_phase::WeightInfo<Self>;
435
	type VoterSnapshotPerBlock = VoterSnapshotPerBlock;
436
437
}

438
439
440
// TODO #6469: This shouldn't be static, but a lazily cached value, not built unless needed, and
// re-built in case input parameters have changed. The `ideal_stake` should be determined by the
// amount of parachain slots being bid on: this should be around `(75 - 25.min(slots / 4))%`.
441
pallet_staking_reward_curve::build! {
thiolliere's avatar
thiolliere committed
442
443
444
	const REWARD_CURVE: PiecewiseLinear<'static> = curve!(
		min_inflation: 0_025_000,
		max_inflation: 0_100_000,
445
446
447
		// 3:2:1 staked : parachains : float.
		// while there's no parachains, then this is 75% staked : 25% float.
		ideal_stake: 0_750_000,
thiolliere's avatar
thiolliere committed
448
449
450
451
452
453
		falloff: 0_050_000,
		max_piece_count: 40,
		test_precision: 0_005_000,
	);
}

454
parameter_types! {
Gavin Wood's avatar
Gavin Wood committed
455
	// Six sessions in an era (24 hours).
456
	pub const SessionsPerEra: SessionIndex = 6;
Gavin Wood's avatar
Gavin Wood committed
457
	// 28 eras for unbonding (28 days).
458
459
	pub const BondingDuration: pallet_staking::EraIndex = 28;
	pub const SlashDeferDuration: pallet_staking::EraIndex = 27;
thiolliere's avatar
thiolliere committed
460
	pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE;
461
	pub const MaxNominatorRewardedPerValidator: u32 = 256;
462
	pub const OffendingValidatorsThreshold: Perbill = Perbill::from_percent(17);
463
}
464

Gavin Wood's avatar
Gavin Wood committed
465
466
467
type SlashCancelOrigin = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
468
	pallet_collective::EnsureProportionAtLeast<_3, _4, AccountId, CouncilCollective>,
Gavin Wood's avatar
Gavin Wood committed
469
470
>;

Kian Paimani's avatar
Kian Paimani committed
471
472
473
474
475
impl frame_election_provider_support::onchain::Config for Runtime {
	type Accuracy = runtime_common::elections::OnOnChainAccuracy;
	type DataProvider = Staking;
}

476
impl pallet_staking::Config for Runtime {
477
	const MAX_NOMINATIONS: u32 =
478
		<NposCompactSolution16 as sp_npos_elections::NposSolution>::LIMIT as u32;
Gavin Wood's avatar
Gavin Wood committed
479
	type Currency = Balances;
480
	type UnixTime = Timestamp;
481
	type CurrencyToVote = CurrencyToVote;
Gavin Wood's avatar
Gavin Wood committed
482
	type RewardRemainder = Treasury;
Gav's avatar
Gav committed
483
	type Event = Event;
484
	type Slash = Treasury;
485
	type Reward = ();
486
487
	type SessionsPerEra = SessionsPerEra;
	type BondingDuration = BondingDuration;
Gavin Wood's avatar
Gavin Wood committed
488
489
	type SlashDeferDuration = SlashDeferDuration;
	// A super-majority of the council can cancel the slash.
Gavin Wood's avatar
Gavin Wood committed
490
	type SlashCancelOrigin = SlashCancelOrigin;
491
	type SessionInterface = Self;
Kian Paimani's avatar
Kian Paimani committed
492
	type EraPayout = pallet_staking::ConvertCurve<RewardCurve>;
Gavin Wood's avatar
Gavin Wood committed
493
	type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator;
494
	type OffendingValidatorsThreshold = OffendingValidatorsThreshold;
495
	type NextNewSession = Session;
496
	type ElectionProvider = ElectionProviderMultiPhase;
Kian Paimani's avatar
Kian Paimani committed
497
	type GenesisElectionProvider = runtime_common::elections::GenesisElectionOf<Self>;
498
499
500
	// Use the nominator map to iter voter AND no-ops for all SortedListProvider hooks. The migration
	// to bags-list is a no-op, but the storage version will be updated.
	type SortedListProvider = pallet_staking::UseNominatorsMap<Runtime>;
501
	type WeightInfo = weights::pallet_staking::WeightInfo<Runtime>;
502
503
}

Gavin Wood's avatar
Gavin Wood committed
504
505
506
507
508
509
510
511
512
513
parameter_types! {
	// Minimum 4 CENTS/byte
	pub const BasicDeposit: Balance = deposit(1, 258);
	pub const FieldDeposit: Balance = deposit(0, 66);
	pub const SubAccountDeposit: Balance = deposit(1, 53);
	pub const MaxSubAccounts: u32 = 100;
	pub const MaxAdditionalFields: u32 = 100;
	pub const MaxRegistrars: u32 = 20;
}

514
impl pallet_identity::Config for Runtime {
Gavin Wood's avatar
Gavin Wood committed
515
516
517
518
519
520
521
522
523
	type Event = Event;
	type Currency = Balances;
	type BasicDeposit = BasicDeposit;
	type FieldDeposit = FieldDeposit;
	type SubAccountDeposit = SubAccountDeposit;
	type MaxSubAccounts = MaxSubAccounts;
	type MaxAdditionalFields = MaxAdditionalFields;
	type MaxRegistrars = MaxRegistrars;
	type Slashed = Treasury;
Gavin Wood's avatar
Gavin Wood committed
524
525
	type ForceOrigin = MoreThanHalfCouncil;
	type RegistrarOrigin = MoreThanHalfCouncil;
526
	type WeightInfo = weights::pallet_identity::WeightInfo<Runtime>;
Gavin Wood's avatar
Gavin Wood committed
527
528
}

529
parameter_types! {
530
531
	pub const LaunchPeriod: BlockNumber = 28 * DAYS;
	pub const VotingPeriod: BlockNumber = 28 * DAYS;
532
	pub const FastTrackVotingPeriod: BlockNumber = 3 * HOURS;
533
	pub const MinimumDeposit: Balance = 100 * DOLLARS;
Gav Wood's avatar
Gav Wood committed
534
	pub const EnactmentPeriod: BlockNumber = 28 * DAYS;
535
	pub const CooloffPeriod: BlockNumber = 7 * DAYS;
Gavin Wood's avatar
Gavin Wood committed
536
537
	// One cent: $10,000 / MB
	pub const PreimageByteDeposit: Balance = 1 * CENTS;
Gavin Wood's avatar
Gavin Wood committed
538
	pub const InstantAllowed: bool = true;
539
	pub const MaxVotes: u32 = 100;
540
	pub const MaxProposals: u32 = 100;
541
542
}

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

613
614
parameter_types! {
	pub const CouncilMotionDuration: BlockNumber = 7 * DAYS;
615
	pub const CouncilMaxProposals: u32 = 100;
616
	pub const CouncilMaxMembers: u32 = 100;
617
618
}

619
pub type CouncilCollective = pallet_collective::Instance1;
620
impl pallet_collective::Config<CouncilCollective> for Runtime {
621
622
623
	type Origin = Origin;
	type Proposal = Call;
	type Event = Event;
624
	type MotionDuration = CouncilMotionDuration;
625
	type MaxProposals = CouncilMaxProposals;
626
	type MaxMembers = CouncilMaxMembers;
Wei Tang's avatar
Wei Tang committed
627
	type DefaultVote = pallet_collective::PrimeDefaultVote;
628
	type WeightInfo = weights::pallet_collective_council::WeightInfo<Runtime>;
629
630
}

Gavin Wood's avatar
Gavin Wood committed
631
parameter_types! {
632
	pub const CandidacyBond: Balance = 100 * DOLLARS;
Kian Paimani's avatar
Kian Paimani committed
633
634
635
636
	// 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);
Gavin Wood's avatar
Gavin Wood committed
637
638
	/// Weekly council elections; scaling up to monthly eventually.
	pub const TermDuration: BlockNumber = 7 * DAYS;
639
	/// 13 members initially, to be increased to 23 eventually.
640
	pub const DesiredMembers: u32 = 13;
641
	pub const DesiredRunnersUp: u32 = 20;
642
	pub const PhragmenElectionPalletId: LockIdentifier = *b"phrelect";
643
}
644
645
// Make sure that there are no more than `MaxMembers` members elected via phragmen.
const_assert!(DesiredMembers::get() <= CouncilMaxMembers::get());
646

647
impl pallet_elections_phragmen::Config for Runtime {
648
	type Event = Event;
649
	type PalletId = PhragmenElectionPalletId;
650
651
	type Currency = Balances;
	type ChangeMembers = Council;
652
	type InitializeMembers = Council;
653
	type CurrencyToVote = frame_support::traits::U128CurrencyToVote;
Gavin Wood's avatar
Gavin Wood committed
654
	type CandidacyBond = CandidacyBond;
Kian Paimani's avatar
Kian Paimani committed
655
656
	type VotingBondBase = VotingBondBase;
	type VotingBondFactor = VotingBondFactor;
657
658
	type LoserCandidate = Treasury;
	type KickedMember = Treasury;
Gavin Wood's avatar
Gavin Wood committed
659
660
661
	type DesiredMembers = DesiredMembers;
	type DesiredRunnersUp = DesiredRunnersUp;
	type TermDuration = TermDuration;
662
	type WeightInfo = weights::pallet_elections_phragmen::WeightInfo<Runtime>;
663
664
}

665
666
parameter_types! {
	pub const TechnicalMotionDuration: BlockNumber = 7 * DAYS;
667
	pub const TechnicalMaxProposals: u32 = 100;
668
	pub const TechnicalMaxMembers: u32 = 100;
669
670
}

671
pub type TechnicalCollective = pallet_collective::Instance2;
672
impl pallet_collective::Config<TechnicalCollective> for Runtime {
673
674
675
	type Origin = Origin;
	type Proposal = Call;
	type Event = Event;
676
	type MotionDuration = TechnicalMotionDuration;
677
	type MaxProposals = TechnicalMaxProposals;
678
	type MaxMembers = TechnicalMaxMembers;
Wei Tang's avatar
Wei Tang committed
679
	type DefaultVote = pallet_collective::PrimeDefaultVote;
680
	type WeightInfo = weights::pallet_collective_technical_committee::WeightInfo<Runtime>;
681
682
}

683
impl pallet_membership::Config<pallet_membership::Instance1> for Runtime {
684
	type Event = Event;
Gavin Wood's avatar
Gavin Wood committed
685
686
687
688
689
	type AddOrigin = MoreThanHalfCouncil;
	type RemoveOrigin = MoreThanHalfCouncil;
	type SwapOrigin = MoreThanHalfCouncil;
	type ResetOrigin = MoreThanHalfCouncil;
	type PrimeOrigin = MoreThanHalfCouncil;
690
691
	type MembershipInitialized = TechnicalCommittee;
	type MembershipChanged = TechnicalCommittee;
692
	type MaxMembers = TechnicalMaxMembers;
Kian Paimani's avatar
Kian Paimani committed
693
	type WeightInfo = weights::pallet_membership::WeightInfo<Runtime>;
694
695
}

Gavin Wood's avatar
Gavin Wood committed
696
697
parameter_types! {
	pub const ProposalBond: Permill = Permill::from_percent(5);
698
699
700
	pub const ProposalBondMinimum: Balance = 100 * DOLLARS;
	pub const SpendPeriod: BlockNumber = 24 * DAYS;
	pub const Burn: Permill = Permill::from_percent(1);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
701
	pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry");
Gavin Wood's avatar
Gavin Wood committed
702
703
704
705

	pub const TipCountdown: BlockNumber = 1 * DAYS;
	pub const TipFindersFee: Percent = Percent::from_percent(20);
	pub const TipReportDepositBase: Balance = 1 * DOLLARS;
706
707
708
709
710
711
712
	pub const DataDepositPerByte: Balance = 1 * CENTS;
	pub const BountyDepositBase: Balance = 1 * DOLLARS;
	pub const BountyDepositPayoutDelay: BlockNumber = 8 * DAYS;
	pub const BountyUpdatePeriod: BlockNumber = 90 * DAYS;
	pub const MaximumReasonLength: u32 = 16384;
	pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);
	pub const BountyValueMinimum: Balance = 10 * DOLLARS;
713
	pub const MaxApprovals: u32 = 100;
714
	pub const MaxAuthorities: u32 = 100_000;
715
716
717
	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
718
719
}

Gavin Wood's avatar
Gavin Wood committed
720
721
722
type ApproveOrigin = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
723
	pallet_collective::EnsureProportionAtLeast<_3, _5, AccountId, CouncilCollective>,
Gavin Wood's avatar
Gavin Wood committed
724
725
>;

726
impl pallet_treasury::Config for Runtime {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
727
	type PalletId = TreasuryPalletId;
Gavin Wood's avatar
Gavin Wood committed
728
	type Currency = Balances;
Gavin Wood's avatar
Gavin Wood committed
729
730
	type ApproveOrigin = ApproveOrigin;
	type RejectOrigin = MoreThanHalfCouncil;
731
	type Event = Event;
732
	type OnSlash = Treasury;
Gavin Wood's avatar
Gavin Wood committed
733
734
735
736
	type ProposalBond = ProposalBond;
	type ProposalBondMinimum = ProposalBondMinimum;
	type SpendPeriod = SpendPeriod;
	type Burn = Burn;
737
738
	type BurnDestination = ();
	type SpendFunds = Bounties;
739
	type MaxApprovals = MaxApprovals;
740
741
742
743
744
	type WeightInfo = weights::pallet_treasury::WeightInfo<Runtime>;
}

impl pallet_bounties::Config for Runtime {
	type Event = Event;
745
746
747
748
749
	type BountyDepositBase = BountyDepositBase;
	type BountyDepositPayoutDelay = BountyDepositPayoutDelay;
	type BountyUpdatePeriod = BountyUpdatePeriod;
	type BountyCuratorDeposit = BountyCuratorDeposit;
	type BountyValueMinimum = BountyValueMinimum;
750
751
752
753
754
755
756
757
758
	type DataDepositPerByte = DataDepositPerByte;
	type MaximumReasonLength = MaximumReasonLength;
	type WeightInfo = weights::pallet_bounties::WeightInfo<Runtime>;
}

impl pallet_tips::Config for Runtime {
	type Event = Event;
	type DataDepositPerByte = DataDepositPerByte;
	type MaximumReasonLength = MaximumReasonLength;
759
	type Tippers = PhragmenElection;
760
761
762
763
	type TipCountdown = TipCountdown;
	type TipFindersFee = TipFindersFee;
	type TipReportDepositBase = TipReportDepositBase;
	type WeightInfo = weights::pallet_tips::WeightInfo<Runtime>;
764
}
765

766
impl pallet_offences::Config for Runtime {
767
	type Event = Event;
768
	type IdentificationTuple = pallet_session::historical::IdentificationTuple<Self>;
769
770
771
	type OnOffenceHandler = Staking;
}

772
773
774
impl pallet_authority_discovery::Config for Runtime {
	type MaxAuthorities = MaxAuthorities;
}
Gavin Wood's avatar
Gavin Wood committed
775

776
parameter_types! {
777
	pub NposSolutionPriority: TransactionPriority =
778
		Perbill::from_percent(90) * TransactionPriority::max_value();
779
780
781
	pub const ImOnlineUnsignedPriority: TransactionPriority = TransactionPriority::max_value();
}

782
impl pallet_im_online::Config for Runtime {
thiolliere's avatar
thiolliere committed
783
	type AuthorityId = ImOnlineId;
784
	type Event = Event;
785
	type ValidatorSet = Historical;
786
	type NextSessionRotation = Babe;
Gavin Wood's avatar
Gavin Wood committed
787
	type ReportUnresponsiveness = Offences;
788
	type UnsignedPriority = ImOnlineUnsignedPriority;
789
	type WeightInfo = weights::pallet_im_online::WeightInfo<Runtime>;
790
791
792
	type MaxKeys = MaxKeys;
	type MaxPeerInHeartbeats = MaxPeerInHeartbeats;
	type MaxPeerDataEncodingSize = MaxPeerDataEncodingSize;
793
794
}

795
impl pallet_grandpa::Config for Runtime {
796
	type Event = Event;
797
798
799
	type Call = Call;

	type KeyOwnerProof =
800
		<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;