lib.rs 73.7 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
}

thiolliere's avatar
thiolliere committed
351
352
353
354
parameter_types! {
	pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(17);
}

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

368
impl pallet_session::historical::Config for Runtime {
369
370
	type FullIdentification = pallet_staking::Exposure<AccountId, Balance>;
	type FullIdentificationOf = pallet_staking::ExposureOf<Runtime>;
371
372
}

373
parameter_types! {
374
375
	// phase durations. 1/4 of the last session for each.
	pub const SignedPhase: u32 = EPOCH_DURATION_IN_SLOTS / 4;
376
	pub const UnsignedPhase: u32 = EPOCH_DURATION_IN_SLOTS / 4;
377

378
379
	// signed config
	pub const SignedMaxSubmissions: u32 = 16;
380
381
382
383
	// 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;
384
385
	// Each good submission will get 1 DOT as reward
	pub SignedRewardBase: Balance = 1 * UNITS;
386
	pub SolutionImprovementThreshold: Perbill = Perbill::from_rational(5u32, 10_000);
387
388

	// miner configs
389
	pub OffchainRepeat: BlockNumber = 5;
390
391
392
393
394

	/// 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;
395
396
}

397
398
sp_npos_elections::generate_solution_type!(
	#[compact]
399
400
401
402
403
	pub struct NposCompactSolution16::<
		VoterIndex = u32,
		TargetIndex = u16,
		Accuracy = sp_runtime::PerU16,
	>(16)
404
405
);

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

443
444
445
// 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))%`.
446
pallet_staking_reward_curve::build! {
thiolliere's avatar
thiolliere committed
447
448
449
	const REWARD_CURVE: PiecewiseLinear<'static> = curve!(
		min_inflation: 0_025_000,
		max_inflation: 0_100_000,
450
451
452
		// 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
453
454
455
456
457
458
		falloff: 0_050_000,
		max_piece_count: 40,
		test_precision: 0_005_000,
	);
}

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

Gavin Wood's avatar
Gavin Wood committed
469
470
471
type SlashCancelOrigin = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
472
	pallet_collective::EnsureProportionAtLeast<_3, _4, AccountId, CouncilCollective>,
Gavin Wood's avatar
Gavin Wood committed
473
474
>;

Kian Paimani's avatar
Kian Paimani committed
475
476
477
478
479
impl frame_election_provider_support::onchain::Config for Runtime {
	type Accuracy = runtime_common::elections::OnOnChainAccuracy;
	type DataProvider = Staking;
}

480
impl pallet_staking::Config for Runtime {
481
	const MAX_NOMINATIONS: u32 =
482
		<NposCompactSolution16 as sp_npos_elections::NposSolution>::LIMIT as u32;
Gavin Wood's avatar
Gavin Wood committed
483
	type Currency = Balances;
484
	type UnixTime = Timestamp;
485
	type CurrencyToVote = CurrencyToVote;
Gavin Wood's avatar
Gavin Wood committed
486
	type RewardRemainder = Treasury;
Gav's avatar
Gav committed
487
	type Event = Event;
488
	type Slash = Treasury;
489
	type Reward = ();
490
491
	type SessionsPerEra = SessionsPerEra;
	type BondingDuration = BondingDuration;
Gavin Wood's avatar
Gavin Wood committed
492
493
	type SlashDeferDuration = SlashDeferDuration;
	// A super-majority of the council can cancel the slash.
Gavin Wood's avatar
Gavin Wood committed
494
	type SlashCancelOrigin = SlashCancelOrigin;
495
	type SessionInterface = Self;
Kian Paimani's avatar
Kian Paimani committed
496
	type EraPayout = pallet_staking::ConvertCurve<RewardCurve>;
Gavin Wood's avatar
Gavin Wood committed
497
	type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator;
498
	type NextNewSession = Session;
499
	type ElectionProvider = ElectionProviderMultiPhase;
Kian Paimani's avatar
Kian Paimani committed
500
	type GenesisElectionProvider = runtime_common::elections::GenesisElectionOf<Self>;
501
502
503
	// 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>;
504
	type WeightInfo = weights::pallet_staking::WeightInfo<Runtime>;
505
506
}

Gavin Wood's avatar
Gavin Wood committed
507
508
509
510
511
512
513
514
515
516
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;
}

517
impl pallet_identity::Config for Runtime {
Gavin Wood's avatar
Gavin Wood committed
518
519
520
521
522
523
524
525
526
	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
527
528
	type ForceOrigin = MoreThanHalfCouncil;
	type RegistrarOrigin = MoreThanHalfCouncil;
529
	type WeightInfo = weights::pallet_identity::WeightInfo<Runtime>;
Gavin Wood's avatar
Gavin Wood committed
530
531
}

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

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

616
617
parameter_types! {
	pub const CouncilMotionDuration: BlockNumber = 7 * DAYS;
618
	pub const CouncilMaxProposals: u32 = 100;
619
	pub const CouncilMaxMembers: u32 = 100;
620
621
}

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

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

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

668
669
parameter_types! {
	pub const TechnicalMotionDuration: BlockNumber = 7 * DAYS;
670
	pub const TechnicalMaxProposals: u32 = 100;
671
	pub const TechnicalMaxMembers: u32 = 100;
672
673
}

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

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

Gavin Wood's avatar
Gavin Wood committed
699
700
parameter_types! {
	pub const ProposalBond: Permill = Permill::from_percent(5);
701
702
703
	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
704
	pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry");
Gavin Wood's avatar
Gavin Wood committed
705
706
707
708

	pub const TipCountdown: BlockNumber = 1 * DAYS;
	pub const TipFindersFee: Percent = Percent::from_percent(20);
	pub const TipReportDepositBase: Balance = 1 * DOLLARS;
709
710
711
712
713
714
715
	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;
716
	pub const MaxApprovals: u32 = 100;
717
	pub const MaxAuthorities: u32 = 100_000;
718
719
720
	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
721
722
}

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

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

impl pallet_bounties::Config for Runtime {
	type Event = Event;
748
749
750
751
752
	type BountyDepositBase = BountyDepositBase;
	type BountyDepositPayoutDelay = BountyDepositPayoutDelay;
	type BountyUpdatePeriod = BountyUpdatePeriod;
	type BountyCuratorDeposit = BountyCuratorDeposit;
	type BountyValueMinimum = BountyValueMinimum;
753
754
755
756
757
758
759
760
761
	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;
762
	type Tippers = PhragmenElection;
763
764
765
766
	type TipCountdown = TipCountdown;
	type TipFindersFee = TipFindersFee;
	type TipReportDepositBase = TipReportDepositBase;
	type WeightInfo = weights::pallet_tips::WeightInfo<Runtime>;
767
}
768

769
impl pallet_offences::Config for Runtime {
770
	type Event = Event;
771
	type IdentificationTuple = pallet_session::historical::IdentificationTuple<Self>;
772
773
774
	type OnOffenceHandler = Staking;
}

775
776
777
impl pallet_authority_discovery::Config for Runtime {
	type MaxAuthorities = MaxAuthorities;
}
Gavin Wood's avatar
Gavin Wood committed
778

779
parameter_types! {
780
	pub NposSolutionPriority: TransactionPriority =
781
		Perbill::from_percent(90) * TransactionPriority::max_value();
782
783
784
	pub const ImOnlineUnsignedPriority: TransactionPriority = TransactionPriority::max_value();
}

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

798
impl pallet_grandpa::Config for Runtime {
799
	type Event = Event;
800