lib.rs 54.9 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
	claims, SlowAdjustingFeeUpdate, CurrencyToVote,
26
	impls::DealWithFees,
27
28
	BlockHashCount, RocksDbWeight, BlockWeights, BlockLength,
	OffchainSolutionWeightLimit, OffchainSolutionLengthLimit,
29
	elections::fee_for_submit_call,
30
	ParachainSessionKeyPlaceholder, AssignmentSessionKeyPlaceholder,
31
};
Gav Wood's avatar
Gav Wood committed
32

33
use sp_std::prelude::*;
Sergey Pepyakin's avatar
Sergey Pepyakin committed
34
use sp_std::collections::btree_map::BTreeMap;
35
use sp_core::u32_trait::{_1, _2, _3, _4, _5};
36
use parity_scale_codec::{Encode, Decode, MaxEncodedLen};
37
use primitives::v1::{
38
39
	AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt,
	CoreState, GroupRotationInfo, Hash, Id, Moment, Nonce, OccupiedCoreAssumption,
40
41
	PersistedValidationData, Signature, ValidationCode, ValidationCodeHash, ValidatorId,
	ValidatorIndex, InboundDownwardMessage, InboundHrmpMessage, SessionInfo,
42
43
};
use sp_runtime::{
Kian Paimani's avatar
Kian Paimani committed
44
	create_runtime_str, generic, impl_opaque_keys, ApplyExtrinsicResult, FixedPointNumber,
45
46
47
	KeyTypeId, Percent, Permill, Perbill, curve::PiecewiseLinear,
	transaction_validity::{TransactionValidity, TransactionSource, TransactionPriority},
	traits::{
48
		BlakeTwo256, Block as BlockT, OpaqueKeys, ConvertInto, AccountIdLookup,
49
50
		Extrinsic as ExtrinsicT, SaturatedConversion, Verify,
	},
51
};
52
53
use sp_version::RuntimeVersion;
use pallet_grandpa::{AuthorityId as GrandpaId, fg_primitives};
54
#[cfg(any(feature = "std", test))]
55
use sp_version::NativeVersion;
56
57
use sp_core::OpaqueMetadata;
use sp_staking::SessionIndex;
58
use frame_support::{
Shawn Tabrizi's avatar
Shawn Tabrizi committed
59
	parameter_types, construct_runtime, RuntimeDebug, PalletId,
60
	traits::{KeyOwnerProofSystem, LockIdentifier, Filter},
61
	weights::Weight,
Gavin Wood's avatar
Gavin Wood committed
62
};
63
use frame_system::{EnsureRoot, EnsureOneOf};
64
use pallet_im_online::sr25519::AuthorityId as ImOnlineId;
Gavin Wood's avatar
Gavin Wood committed
65
use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId;
66
use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo};
67
use pallet_session::historical as session_historical;
68
use static_assertions::const_assert;
Andreas Doerr's avatar
Andreas Doerr committed
69
use beefy_primitives::crypto::AuthorityId as BeefyId;
70
use pallet_mmr_primitives as mmr;
71

Gav Wood's avatar
Gav Wood committed
72
#[cfg(feature = "std")]
73
pub use pallet_staking::StakerStatus;
74
#[cfg(any(feature = "std", test))]
75
pub use sp_runtime::BuildStorage;
76
77
pub use pallet_timestamp::Call as TimestampCall;
pub use pallet_balances::Call as BalancesCall;
Kian Paimani's avatar
Kian Paimani committed
78
pub use pallet_election_provider_multi_phase::Call as EPMCall;
79
80
81

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

85
86
87
// Weights used in the runtime.
mod weights;

88
89
90
91
// Make the WASM binary available.
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));

92
// Polkadot version identifier;
93
/// Runtime version (Polkadot).
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
94
pub const VERSION: RuntimeVersion = RuntimeVersion {
95
96
	spec_name: create_runtime_str!("polkadot"),
	impl_name: create_runtime_str!("parity-polkadot"),
Gavin Wood's avatar
Gavin Wood committed
97
	authoring_version: 0,
98
	spec_version: 9090,
99
	impl_version: 0,
100
	#[cfg(not(feature = "disable-runtime-api"))]
101
	apis: RUNTIME_API_VERSIONS,
102
	#[cfg(feature = "disable-runtime-api")]
103
	apis: version::create_apis_vec![[]],
104
	transaction_version: 7,
105
};
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
106

107
108
109
110
111
112
113
/// The BABE epoch configuration at genesis.
pub const BABE_GENESIS_EPOCH_CONFIG: babe_primitives::BabeEpochConfiguration =
	babe_primitives::BabeEpochConfiguration {
		c: PRIMARY_PROBABILITY,
		allowed_slots: babe_primitives::AllowedSlots::PrimaryAndSecondaryVRFSlots
	};

114
115
116
117
118
119
120
121
122
/// Native version.
#[cfg(any(feature = "std", test))]
pub fn native_version() -> NativeVersion {
	NativeVersion {
		runtime_version: VERSION,
		can_author_with: Default::default(),
	}
}

123
124
pub struct BaseFilter;
impl Filter<Call> for BaseFilter {
Gavin Wood's avatar
Gavin Wood committed
125
	fn filter(call: &Call) -> bool {
126
		match call {
Gavin Wood's avatar
Gavin Wood committed
127
			// These modules are all allowed to be called by transactions:
128
			Call::Democracy(_) | Call::Council(_) | Call::TechnicalCommittee(_) |
129
			Call::TechnicalMembership(_) | Call::Treasury(_) | Call::PhragmenElection(_) |
Gavin Wood's avatar
Gavin Wood committed
130
			Call::System(_) | Call::Scheduler(_) | Call::Indices(_) |
Gavin Wood's avatar
Gavin Wood committed
131
			Call::Babe(_) | Call::Timestamp(_) | Call::Balances(_) |
Keith Yeung's avatar
Keith Yeung committed
132
			Call::Authorship(_) | Call::Staking(_) |
133
			Call::Session(_) | Call::Grandpa(_) | Call::ImOnline(_) |
Gavin Wood's avatar
Gavin Wood committed
134
			Call::Utility(_) | Call::Claims(_) | Call::Vesting(_) |
135
			Call::Identity(_) | Call::Proxy(_) | Call::Multisig(_) |
136
			Call::Bounties(_) | Call::Tips(_) | Call::ElectionProviderMultiPhase(_)
137
			=> true,
138
139
140
141
		}
	}
}

Gavin Wood's avatar
Gavin Wood committed
142
143
144
type MoreThanHalfCouncil = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
145
	pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>
Gavin Wood's avatar
Gavin Wood committed
146
147
>;

148
parameter_types! {
149
	pub const Version: RuntimeVersion = VERSION;
150
	pub const SS58Prefix: u8 = 0;
151
152
}

153
impl frame_system::Config for Runtime {
154
	type BaseCallFilter = BaseFilter;
155
156
	type BlockWeights = BlockWeights;
	type BlockLength = BlockLength;
157
	type Origin = Origin;
158
	type Call = Call;
Gav Wood's avatar
Gav Wood committed
159
	type Index = Nonce;
160
161
162
163
	type BlockNumber = BlockNumber;
	type Hash = Hash;
	type Hashing = BlakeTwo256;
	type AccountId = AccountId;
164
	type Lookup = AccountIdLookup<AccountId, ()>;
165
	type Header = generic::Header<BlockNumber, BlakeTwo256>;
Gav's avatar
Gav committed
166
	type Event = Event;
167
	type BlockHashCount = BlockHashCount;
168
	type DbWeight = RocksDbWeight;
169
	type Version = Version;
170
	type PalletInfo = PalletInfo;
171
	type AccountData = pallet_balances::AccountData<Balance>;
Gavin Wood's avatar
Gavin Wood committed
172
	type OnNewAccount = ();
173
	type OnKilledAccount = ();
174
	type SystemWeightInfo = weights::frame_system::WeightInfo<Runtime>;
175
	type SS58Prefix = SS58Prefix;
176
	type OnSetCode = ();
177
178
}

179
parameter_types! {
180
181
	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) *
		BlockWeights::get().max_block;
182
183
184
	pub const MaxScheduledPerBlock: u32 = 50;
}

185
186
187
188
189
190
type ScheduleOrigin = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
	pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>
>;

191
impl pallet_scheduler::Config for Runtime {
Gavin Wood's avatar
Gavin Wood committed
192
193
	type Event = Event;
	type Origin = Origin;
194
	type PalletsOrigin = OriginCaller;
Gavin Wood's avatar
Gavin Wood committed
195
	type Call = Call;
196
	type MaximumWeight = MaximumSchedulerWeight;
197
	type ScheduleOrigin = ScheduleOrigin;
198
	type MaxScheduledPerBlock = MaxScheduledPerBlock;
199
	type WeightInfo = weights::pallet_scheduler::WeightInfo<Runtime>;
Gavin Wood's avatar
Gavin Wood committed
200
201
}

202
parameter_types! {
203
	pub const EpochDuration: u64 = EPOCH_DURATION_IN_SLOTS as u64;
204
	pub const ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK;
205
206
	pub const ReportLongevity: u64 =
		BondingDuration::get() as u64 * SessionsPerEra::get() as u64 * EpochDuration::get();
207
208
}

209
impl pallet_babe::Config for Runtime {
210
211
	type EpochDuration = EpochDuration;
	type ExpectedBlockTime = ExpectedBlockTime;
212
213

	// session module is the trigger
214
	type EpochChangeTrigger = pallet_babe::ExternalTrigger;
215
216
217
218
219

	type KeyOwnerProofSystem = Historical;

	type KeyOwnerProof = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
		KeyTypeId,
220
		pallet_babe::AuthorityId,
221
222
223
224
	)>>::Proof;

	type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
		KeyTypeId,
225
		pallet_babe::AuthorityId,
226
227
228
	)>>::IdentificationTuple;

	type HandleEquivocation =
229
		pallet_babe::EquivocationHandler<Self::KeyOwnerIdentification, Offences, ReportLongevity>;
230
231

	type WeightInfo = ();
232
233
}

Gavin Wood's avatar
Gavin Wood committed
234
parameter_types! {
Gavin Wood's avatar
Gavin Wood committed
235
	pub const IndexDeposit: Balance = 10 * DOLLARS;
Gavin Wood's avatar
Gavin Wood committed
236
237
}

238
impl pallet_indices::Config for Runtime {
Gav Wood's avatar
Gav Wood committed
239
	type AccountIndex = AccountIndex;
240
241
	type Currency = Balances;
	type Deposit = IndexDeposit;
Gav Wood's avatar
Gav Wood committed
242
	type Event = Event;
243
	type WeightInfo = weights::pallet_indices::WeightInfo<Runtime>;
Gav Wood's avatar
Gav Wood committed
244
245
}

Gavin Wood's avatar
Gavin Wood committed
246
parameter_types! {
247
	pub const ExistentialDeposit: Balance = 100 * CENTS;
248
	pub const MaxLocks: u32 = 50;
Gavin Wood's avatar
Gavin Wood committed
249
	pub const MaxReserves: u32 = 50;
Gavin Wood's avatar
Gavin Wood committed
250
251
}

252
impl pallet_balances::Config for Runtime {
Gav's avatar
Gav committed
253
	type Balance = Balance;
254
	type DustRemoval = ();
Gavin Wood's avatar
Gavin Wood committed
255
	type Event = Event;
Gavin Wood's avatar
Gavin Wood committed
256
	type ExistentialDeposit = ExistentialDeposit;
257
	type AccountStore = System;
258
	type MaxLocks = MaxLocks;
Gavin Wood's avatar
Gavin Wood committed
259
260
	type MaxReserves = MaxReserves;
	type ReserveIdentifier = [u8; 8];
261
	type WeightInfo = weights::pallet_balances::WeightInfo<Runtime>;
262
263
264
265
266
267
}

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

268
impl pallet_transaction_payment::Config for Runtime {
Albrecht's avatar
Albrecht committed
269
	type OnChargeTransaction = CurrencyAdapter<Balances, DealWithFees<Runtime>>;
Gavin Wood's avatar
Gavin Wood committed
270
	type TransactionByteFee = TransactionByteFee;
271
	type WeightToFee = WeightToFee;
272
	type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
Gav's avatar
Gav committed
273
274
}

275
parameter_types! {
276
	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;
277
}
278
impl pallet_timestamp::Config for Runtime {
279
	type Moment = u64;
280
	type OnTimestampSet = Babe;
281
	type MinimumPeriod = MinimumPeriod;
282
	type WeightInfo = weights::pallet_timestamp::WeightInfo<Runtime>;
283
284
}

Gavin Wood's avatar
Gavin Wood committed
285
parameter_types! {
286
	pub const UncleGenerations: u32 = 0;
Gavin Wood's avatar
Gavin Wood committed
287
288
289
}

// TODO: substrate#2986 implement this properly
290
impl pallet_authorship::Config for Runtime {
291
	type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Babe>;
Gavin Wood's avatar
Gavin Wood committed
292
293
	type UncleGenerations = UncleGenerations;
	type FilterUncle = ();
Gavin Wood's avatar
Gavin Wood committed
294
	type EventHandler = (Staking, ImOnline);
Gavin Wood's avatar
Gavin Wood committed
295
296
}

297
impl_opaque_keys! {
298
	pub struct SessionKeys {
Gavin Wood's avatar
Gavin Wood committed
299
300
301
		pub grandpa: Grandpa,
		pub babe: Babe,
		pub im_online: ImOnline,
302
303
		pub para_validator: ParachainSessionKeyPlaceholder<Runtime>,
		pub para_assignment: AssignmentSessionKeyPlaceholder<Runtime>,
Gavin Wood's avatar
Gavin Wood committed
304
		pub authority_discovery: AuthorityDiscovery,
305
	}
306
307
}

thiolliere's avatar
thiolliere committed
308
309
310
311
parameter_types! {
	pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(17);
}

312
impl pallet_session::Config for Runtime {
Gav's avatar
Gav committed
313
	type Event = Event;
314
	type ValidatorId = AccountId;
315
	type ValidatorIdOf = pallet_staking::StashOf<Self>;
Gavin Wood's avatar
Gavin Wood committed
316
	type ShouldEndSession = Babe;
317
	type NextSessionRotation = Babe;
318
	type SessionManager = pallet_session::historical::NoteHistoricalRoot<Self, Staking>;
Gavin Wood's avatar
Gavin Wood committed
319
320
	type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
	type Keys = SessionKeys;
thiolliere's avatar
thiolliere committed
321
	type DisabledValidatorsThreshold = DisabledValidatorsThreshold;
322
	type WeightInfo = weights::pallet_session::WeightInfo<Runtime>;
323
324
}

325
impl pallet_session::historical::Config for Runtime {
326
327
	type FullIdentification = pallet_staking::Exposure<AccountId, Balance>;
	type FullIdentificationOf = pallet_staking::ExposureOf<Runtime>;
328
329
}

Kian Paimani's avatar
Kian Paimani committed
330
use pallet_election_provider_multi_phase::WeightInfo;
331
parameter_types! {
332
333
	// phase durations. 1/4 of the last session for each.
	pub const SignedPhase: u32 = EPOCH_DURATION_IN_SLOTS / 4;
334
	pub const UnsignedPhase: u32 = EPOCH_DURATION_IN_SLOTS / 4;
335

336
337
338
339
340
341
342
	// signed config
	pub const SignedMaxSubmissions: u32 = 16;
	pub const SignedDepositBase: Balance = deposit(1, 0);
	// A typical solution occupies within an order of magnitude of 50kb.
	// This formula is currently adjusted such that a typical solution will spend an amount equal
	// to the base deposit for every 50 kb.
	pub const SignedDepositByte: Balance = deposit(1, 0) / (50 * 1024);
Kian Paimani's avatar
Kian Paimani committed
343
344
345
346
347
348
349
350
	pub SignedRewardBase: Balance = fee_for_submit_call::<Runtime>(
		// give 20% threshold.
		sp_runtime::FixedU128::saturating_from_rational(12, 10),
		// maximum weight possible.
		weights::pallet_election_provider_multi_phase::WeightInfo::<Runtime>::submit(SignedMaxSubmissions::get()),
		// assume a solution of 200kb length.
		200 * 1024
	);
351
352

	// fallback: emergency phase.
353
	pub const Fallback: pallet_election_provider_multi_phase::FallbackStrategy =
354
		pallet_election_provider_multi_phase::FallbackStrategy::Nothing;
355
	pub SolutionImprovementThreshold: Perbill = Perbill::from_rational(5u32, 10_000);
356
357
358

	// miner configs
	pub const MinerMaxIterations: u32 = 10;
359
	pub OffchainRepeat: BlockNumber = 5;
360
361
}

362
363
sp_npos_elections::generate_solution_type!(
	#[compact]
364
365
366
367
368
	pub struct NposCompactSolution16::<
		VoterIndex = u32,
		TargetIndex = u16,
		Accuracy = sp_runtime::PerU16,
	>(16)
369
370
);

371
372
373
374
375
impl pallet_election_provider_multi_phase::Config for Runtime {
	type Event = Event;
	type Currency = Balances;
	type SignedPhase = SignedPhase;
	type UnsignedPhase = UnsignedPhase;
376
377
378
379
380
381
382
383
	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
384
	type SolutionImprovementThreshold = SolutionImprovementThreshold;
385
	type MinerMaxIterations = MinerMaxIterations;
386
	type MinerMaxWeight = OffchainSolutionWeightLimit; // For now use the one from staking.
387
	type MinerMaxLength = OffchainSolutionLengthLimit;
388
	type OffchainRepeat = OffchainRepeat;
389
	type MinerTxPriority = NposSolutionPriority;
390
391
	type DataProvider = Staking;
	type OnChainAccuracy = Perbill;
392
	type CompactSolution = NposCompactSolution16;
393
	type Fallback = Fallback;
394
	type BenchmarkingConfig = runtime_common::elections::BenchmarkConfig;
395
396
397
398
399
	type ForceOrigin = EnsureOneOf<
		AccountId,
		EnsureRoot<AccountId>,
		pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, CouncilCollective>,
	>;
400
	type WeightInfo = weights::pallet_election_provider_multi_phase::WeightInfo<Runtime>;
401
402
}

403
404
405
// 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))%`.
406
pallet_staking_reward_curve::build! {
thiolliere's avatar
thiolliere committed
407
408
409
	const REWARD_CURVE: PiecewiseLinear<'static> = curve!(
		min_inflation: 0_025_000,
		max_inflation: 0_100_000,
410
411
412
		// 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
413
414
415
416
417
418
		falloff: 0_050_000,
		max_piece_count: 40,
		test_precision: 0_005_000,
	);
}

419
parameter_types! {
Gavin Wood's avatar
Gavin Wood committed
420
	// Six sessions in an era (24 hours).
421
	pub const SessionsPerEra: SessionIndex = 6;
Gavin Wood's avatar
Gavin Wood committed
422
	// 28 eras for unbonding (28 days).
423
424
	pub const BondingDuration: pallet_staking::EraIndex = 28;
	pub const SlashDeferDuration: pallet_staking::EraIndex = 27;
thiolliere's avatar
thiolliere committed
425
	pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE;
426
	pub const MaxNominatorRewardedPerValidator: u32 = 256;
427
}
428

Gavin Wood's avatar
Gavin Wood committed
429
430
431
type SlashCancelOrigin = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
432
	pallet_collective::EnsureProportionAtLeast<_3, _4, AccountId, CouncilCollective>
Gavin Wood's avatar
Gavin Wood committed
433
434
>;

435
impl pallet_staking::Config for Runtime {
436
	const MAX_NOMINATIONS: u32 = <NposCompactSolution16 as sp_npos_elections::CompactSolution>::LIMIT as u32;
Gavin Wood's avatar
Gavin Wood committed
437
	type Currency = Balances;
438
	type UnixTime = Timestamp;
439
	type CurrencyToVote = CurrencyToVote;
Gavin Wood's avatar
Gavin Wood committed
440
	type RewardRemainder = Treasury;
Gav's avatar
Gav committed
441
	type Event = Event;
442
	type Slash = Treasury;
443
	type Reward = ();
444
445
	type SessionsPerEra = SessionsPerEra;
	type BondingDuration = BondingDuration;
Gavin Wood's avatar
Gavin Wood committed
446
447
	type SlashDeferDuration = SlashDeferDuration;
	// A super-majority of the council can cancel the slash.
Gavin Wood's avatar
Gavin Wood committed
448
	type SlashCancelOrigin = SlashCancelOrigin;
449
	type SessionInterface = Self;
Kian Paimani's avatar
Kian Paimani committed
450
	type EraPayout = pallet_staking::ConvertCurve<RewardCurve>;
Gavin Wood's avatar
Gavin Wood committed
451
	type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator;
452
	type NextNewSession = Session;
453
	type ElectionProvider = ElectionProviderMultiPhase;
454
455
456
457
	type GenesisElectionProvider =
		frame_election_provider_support::onchain::OnChainSequentialPhragmen<
			pallet_election_provider_multi_phase::OnChainConfig<Self>
		>;
458
	type WeightInfo = weights::pallet_staking::WeightInfo<Runtime>;
459
460
}

Gavin Wood's avatar
Gavin Wood committed
461
462
463
464
465
466
467
468
469
470
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;
}

471
impl pallet_identity::Config for Runtime {
Gavin Wood's avatar
Gavin Wood committed
472
473
474
475
476
477
478
479
480
	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
481
482
	type ForceOrigin = MoreThanHalfCouncil;
	type RegistrarOrigin = MoreThanHalfCouncil;
483
	type WeightInfo = weights::pallet_identity::WeightInfo<Runtime>;
Gavin Wood's avatar
Gavin Wood committed
484
485
}

486
parameter_types! {
487
488
	pub const LaunchPeriod: BlockNumber = 28 * DAYS;
	pub const VotingPeriod: BlockNumber = 28 * DAYS;
489
	pub const FastTrackVotingPeriod: BlockNumber = 3 * HOURS;
490
	pub const MinimumDeposit: Balance = 100 * DOLLARS;
Gav Wood's avatar
Gav Wood committed
491
	pub const EnactmentPeriod: BlockNumber = 28 * DAYS;
492
	pub const CooloffPeriod: BlockNumber = 7 * DAYS;
Gavin Wood's avatar
Gavin Wood committed
493
494
	// One cent: $10,000 / MB
	pub const PreimageByteDeposit: Balance = 1 * CENTS;
Gavin Wood's avatar
Gavin Wood committed
495
	pub const InstantAllowed: bool = true;
496
	pub const MaxVotes: u32 = 100;
497
	pub const MaxProposals: u32 = 100;
498
499
}

500
impl pallet_democracy::Config for Runtime {
501
502
	type Proposal = Call;
	type Event = Event;
503
	type Currency = Balances;
504
505
506
507
	type EnactmentPeriod = EnactmentPeriod;
	type LaunchPeriod = LaunchPeriod;
	type VotingPeriod = VotingPeriod;
	type MinimumDeposit = MinimumDeposit;
508
	/// A straight majority of the council can decide what their next motion is.
509
510
511
	type ExternalOrigin = frame_system::EnsureOneOf<AccountId,
		pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>,
		frame_system::EnsureRoot<AccountId>,
Gavin Wood's avatar
Gavin Wood committed
512
	>;
513
	/// A 60% super-majority can have the next scheduled referendum be a straight majority-carries vote.
514
515
516
	type ExternalMajorityOrigin = frame_system::EnsureOneOf<AccountId,
		pallet_collective::EnsureProportionAtLeast<_3, _5, AccountId, CouncilCollective>,
		frame_system::EnsureRoot<AccountId>,
Gavin Wood's avatar
Gavin Wood committed
517
	>;
518
519
	/// A unanimous council can have the next scheduled referendum be a straight default-carries
	/// (NTB) vote.
520
521
522
	type ExternalDefaultOrigin = frame_system::EnsureOneOf<AccountId,
		pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, CouncilCollective>,
		frame_system::EnsureRoot<AccountId>,
Gavin Wood's avatar
Gavin Wood committed
523
	>;
Denis_P's avatar
Denis_P committed
524
	/// Two thirds of the technical committee can have an `ExternalMajority/ExternalDefault` vote
525
	/// be tabled immediately and with a shorter voting/enactment period.
526
527
528
	type FastTrackOrigin = frame_system::EnsureOneOf<AccountId,
		pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, TechnicalCollective>,
		frame_system::EnsureRoot<AccountId>,
Gavin Wood's avatar
Gavin Wood committed
529
	>;
530
531
532
	type InstantOrigin = frame_system::EnsureOneOf<AccountId,
		pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, TechnicalCollective>,
		frame_system::EnsureRoot<AccountId>,
Gavin Wood's avatar
Gavin Wood committed
533
	>;
534
535
	type InstantAllowed = InstantAllowed;
	type FastTrackVotingPeriod = FastTrackVotingPeriod;
536
	// To cancel a proposal which has been passed, 2/3 of the council must agree to it.
537
	type CancellationOrigin = EnsureOneOf<AccountId,
538
		pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, CouncilCollective>,
539
540
541
542
543
544
545
		EnsureRoot<AccountId>,
	>;
	// To cancel a proposal before it has been passed, the technical committee must be unanimous or
	// Root must agree.
	type CancelProposalOrigin = EnsureOneOf<AccountId,
		pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, TechnicalCollective>,
		EnsureRoot<AccountId>,
Gavin Wood's avatar
Gavin Wood committed
546
	>;
547
	type BlacklistOrigin = EnsureRoot<AccountId>;
548
549
	// 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.
550
	type VetoOrigin = pallet_collective::EnsureMember<AccountId, TechnicalCollective>;
551
	type CooloffPeriod = CooloffPeriod;
Gavin Wood's avatar
Gavin Wood committed
552
	type PreimageByteDeposit = PreimageByteDeposit;
553
	type OperationalPreimageOrigin = pallet_collective::EnsureMember<AccountId, CouncilCollective>;
Gavin Wood's avatar
Gavin Wood committed
554
	type Slash = Treasury;
Gavin Wood's avatar
Gavin Wood committed
555
	type Scheduler = Scheduler;
556
	type PalletsOrigin = OriginCaller;
557
	type MaxVotes = MaxVotes;
558
559
	type WeightInfo = weights::pallet_democracy::WeightInfo<Runtime>;
	type MaxProposals = MaxProposals;
560
}
561

562
563
parameter_types! {
	pub const CouncilMotionDuration: BlockNumber = 7 * DAYS;
564
	pub const CouncilMaxProposals: u32 = 100;
565
	pub const CouncilMaxMembers: u32 = 100;
566
567
}

568
pub type CouncilCollective = pallet_collective::Instance1;
569
impl pallet_collective::Config<CouncilCollective> for Runtime {
570
571
572
	type Origin = Origin;
	type Proposal = Call;
	type Event = Event;
573
	type MotionDuration = CouncilMotionDuration;
574
	type MaxProposals = CouncilMaxProposals;
575
	type MaxMembers = CouncilMaxMembers;
Wei Tang's avatar
Wei Tang committed
576
	type DefaultVote = pallet_collective::PrimeDefaultVote;
577
	type WeightInfo = weights::pallet_collective::WeightInfo<Runtime>;
578
579
}

Gavin Wood's avatar
Gavin Wood committed
580
parameter_types! {
581
	pub const CandidacyBond: Balance = 100 * DOLLARS;
Kian Paimani's avatar
Kian Paimani committed
582
583
584
585
	// 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
586
587
	/// Weekly council elections; scaling up to monthly eventually.
	pub const TermDuration: BlockNumber = 7 * DAYS;
588
	/// 13 members initially, to be increased to 23 eventually.
589
	pub const DesiredMembers: u32 = 13;
590
	pub const DesiredRunnersUp: u32 = 20;
591
	pub const PhragmenElectionPalletId: LockIdentifier = *b"phrelect";
592
}
593
594
// Make sure that there are no more than `MaxMembers` members elected via phragmen.
const_assert!(DesiredMembers::get() <= CouncilMaxMembers::get());
595

596
impl pallet_elections_phragmen::Config for Runtime {
597
	type Event = Event;
598
	type PalletId = PhragmenElectionPalletId;
599
600
	type Currency = Balances;
	type ChangeMembers = Council;
601
	type InitializeMembers = Council;
602
	type CurrencyToVote = frame_support::traits::U128CurrencyToVote;
Gavin Wood's avatar
Gavin Wood committed
603
	type CandidacyBond = CandidacyBond;
Kian Paimani's avatar
Kian Paimani committed
604
605
	type VotingBondBase = VotingBondBase;
	type VotingBondFactor = VotingBondFactor;
606
607
	type LoserCandidate = Treasury;
	type KickedMember = Treasury;
Gavin Wood's avatar
Gavin Wood committed
608
609
610
	type DesiredMembers = DesiredMembers;
	type DesiredRunnersUp = DesiredRunnersUp;
	type TermDuration = TermDuration;
611
	type WeightInfo = weights::pallet_elections_phragmen::WeightInfo<Runtime>;
612
613
}

614
615
parameter_types! {
	pub const TechnicalMotionDuration: BlockNumber = 7 * DAYS;
616
	pub const TechnicalMaxProposals: u32 = 100;
617
	pub const TechnicalMaxMembers: u32 = 100;
618
619
}

620
pub type TechnicalCollective = pallet_collective::Instance2;
621
impl pallet_collective::Config<TechnicalCollective> for Runtime {
622
623
624
	type Origin = Origin;
	type Proposal = Call;
	type Event = Event;
625
	type MotionDuration = TechnicalMotionDuration;
626
	type MaxProposals = TechnicalMaxProposals;
627
	type MaxMembers = TechnicalMaxMembers;
Wei Tang's avatar
Wei Tang committed
628
	type DefaultVote = pallet_collective::PrimeDefaultVote;
629
	type WeightInfo = weights::pallet_collective::WeightInfo<Runtime>;
630
631
}

632
impl pallet_membership::Config<pallet_membership::Instance1> for Runtime {
633
	type Event = Event;
Gavin Wood's avatar
Gavin Wood committed
634
635
636
637
638
	type AddOrigin = MoreThanHalfCouncil;
	type RemoveOrigin = MoreThanHalfCouncil;
	type SwapOrigin = MoreThanHalfCouncil;
	type ResetOrigin = MoreThanHalfCouncil;
	type PrimeOrigin = MoreThanHalfCouncil;
639
640
	type MembershipInitialized = TechnicalCommittee;
	type MembershipChanged = TechnicalCommittee;
641
	type MaxMembers = TechnicalMaxMembers;
Kian Paimani's avatar
Kian Paimani committed
642
	type WeightInfo = weights::pallet_membership::WeightInfo<Runtime>;
643
644
}

Gavin Wood's avatar
Gavin Wood committed
645
646
parameter_types! {
	pub const ProposalBond: Permill = Permill::from_percent(5);
647
648
649
	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
650
	pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry");
Gavin Wood's avatar
Gavin Wood committed
651
652
653
654

	pub const TipCountdown: BlockNumber = 1 * DAYS;
	pub const TipFindersFee: Percent = Percent::from_percent(20);
	pub const TipReportDepositBase: Balance = 1 * DOLLARS;
655
656
657
658
659
660
661
	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;
662
	pub const MaxApprovals: u32 = 100;
Gavin Wood's avatar
Gavin Wood committed
663
664
}

Gavin Wood's avatar
Gavin Wood committed
665
666
667
type ApproveOrigin = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
668
	pallet_collective::EnsureProportionAtLeast<_3, _5, AccountId, CouncilCollective>
Gavin Wood's avatar
Gavin Wood committed
669
670
>;

671
impl pallet_treasury::Config for Runtime {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
672
	type PalletId = TreasuryPalletId;
Gavin Wood's avatar
Gavin Wood committed
673
	type Currency = Balances;
Gavin Wood's avatar
Gavin Wood committed
674
675
	type ApproveOrigin = ApproveOrigin;
	type RejectOrigin = MoreThanHalfCouncil;
676
	type Event = Event;
677
	type OnSlash = Treasury;
Gavin Wood's avatar
Gavin Wood committed
678
679
680
681
	type ProposalBond = ProposalBond;
	type ProposalBondMinimum = ProposalBondMinimum;
	type SpendPeriod = SpendPeriod;
	type Burn = Burn;
682
683
	type BurnDestination = ();
	type SpendFunds = Bounties;
684
	type MaxApprovals = MaxApprovals;
685
686
687
688
689
	type WeightInfo = weights::pallet_treasury::WeightInfo<Runtime>;
}

impl pallet_bounties::Config for Runtime {
	type Event = Event;
690
691
692
693
694
	type BountyDepositBase = BountyDepositBase;
	type BountyDepositPayoutDelay = BountyDepositPayoutDelay;
	type BountyUpdatePeriod = BountyUpdatePeriod;
	type BountyCuratorDeposit = BountyCuratorDeposit;
	type BountyValueMinimum = BountyValueMinimum;
695
696
697
698
699
700
701
702
703
	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;
704
	type Tippers = PhragmenElection;
705
706
707
708
	type TipCountdown = TipCountdown;
	type TipFindersFee = TipFindersFee;
	type TipReportDepositBase = TipReportDepositBase;
	type WeightInfo = weights::pallet_tips::WeightInfo<Runtime>;
709
}
710

711
impl pallet_offences::Config for Runtime {
712
	type Event = Event;
713
	type IdentificationTuple = pallet_session::historical::IdentificationTuple<Self>;
714
715
716
	type OnOffenceHandler = Staking;
}

717
impl pallet_authority_discovery::Config for Runtime {}
Gavin Wood's avatar
Gavin Wood committed
718

719
parameter_types! {
720
	pub NposSolutionPriority: TransactionPriority =
721
		Perbill::from_percent(90) * TransactionPriority::max_value();
722
723
724
	pub const ImOnlineUnsignedPriority: TransactionPriority = TransactionPriority::max_value();
}

725
impl pallet_im_online::Config for Runtime {
thiolliere's avatar
thiolliere committed
726
	type AuthorityId = ImOnlineId;
727
	type Event = Event;
728
	type ValidatorSet = Historical;
729
	type NextSessionRotation = Babe;
Gavin Wood's avatar
Gavin Wood committed
730
	type ReportUnresponsiveness = Offences;
731
	type UnsignedPriority = ImOnlineUnsignedPriority;
732
	type WeightInfo = weights::pallet_im_online::WeightInfo<Runtime>;
733
734
}

735
impl pallet_grandpa::Config for Runtime {
736
	type Event = Event;
737
738
739
	type Call = Call;

	type KeyOwnerProof =
Gavin Wood's avatar
Gavin Wood committed
740
	<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;
741
742
743
744
745
746

	type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
		KeyTypeId,
		GrandpaId,
	)>>::IdentificationTuple;

Gavin Wood's avatar
Gavin Wood committed
747
748
	type KeyOwnerProofSystem = Historical;

749
750
	type HandleEquivocation =
		pallet_grandpa::EquivocationHandler<Self::KeyOwnerIdentification, Offences, ReportLongevity>;
751
752

	type WeightInfo = ();
753
754
}

755
756
/// Submits a transaction with the node's public and signature type. Adheres to the signed extension
/// format of the chain.
757
impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime where
758
759
	Call: From<LocalCall>,
{
760
	fn create_transaction<C: frame_system::offchain::AppCrypto<Self::Public, Self::Signature>>(
761
762
763
		call: Call,
		public: <Signature as Verify>::Signer,
		account: AccountId,
764
		nonce: <Runtime as frame_system::Config>::Index,
765
	) -> Option<(Call, <UncheckedExtrinsic as ExtrinsicT>::SignaturePayload)> {
766
		use sp_runtime::traits::StaticLookup;
767
		// take the biggest period possible.