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

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

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

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

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

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

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

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

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

121
pub struct BaseFilter;
122
123
impl Contains<Call> for BaseFilter {
	fn contains(call: &Call) -> bool {
124
		match call {
Gavin Wood's avatar
Gavin Wood committed
125
			// These modules are all allowed to be called by transactions:
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
			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(_) |
			Call::ElectionProviderMultiPhase(_) => true,
152
153
154
155
		}
	}
}

Gavin Wood's avatar
Gavin Wood committed
156
157
158
type MoreThanHalfCouncil = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
159
	pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>,
Gavin Wood's avatar
Gavin Wood committed
160
161
>;

162
parameter_types! {
163
	pub const Version: RuntimeVersion = VERSION;
164
	pub const SS58Prefix: u8 = 0;
165
166
}

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

193
parameter_types! {
194
195
	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) *
		BlockWeights::get().max_block;
196
197
198
	pub const MaxScheduledPerBlock: u32 = 50;
}

199
200
201
type ScheduleOrigin = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
202
	pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>,
203
204
>;

205
impl pallet_scheduler::Config for Runtime {
Gavin Wood's avatar
Gavin Wood committed
206
207
	type Event = Event;
	type Origin = Origin;
208
	type PalletsOrigin = OriginCaller;
Gavin Wood's avatar
Gavin Wood committed
209
	type Call = Call;
210
	type MaximumWeight = MaximumSchedulerWeight;
211
	type ScheduleOrigin = ScheduleOrigin;
212
	type MaxScheduledPerBlock = MaxScheduledPerBlock;
213
	type WeightInfo = weights::pallet_scheduler::WeightInfo<Runtime>;
Gavin Wood's avatar
Gavin Wood committed
214
215
}

216
parameter_types! {
217
	pub const EpochDuration: u64 = EPOCH_DURATION_IN_SLOTS as u64;
218
	pub const ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK;
219
220
	pub const ReportLongevity: u64 =
		BondingDuration::get() as u64 * SessionsPerEra::get() as u64 * EpochDuration::get();
221
222
}

223
impl pallet_babe::Config for Runtime {
224
225
	type EpochDuration = EpochDuration;
	type ExpectedBlockTime = ExpectedBlockTime;
226
227

	// session module is the trigger
228
	type EpochChangeTrigger = pallet_babe::ExternalTrigger;
229

230
231
	type DisabledValidators = Session;

232
233
234
235
	type KeyOwnerProofSystem = Historical;

	type KeyOwnerProof = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
		KeyTypeId,
236
		pallet_babe::AuthorityId,
237
238
239
240
	)>>::Proof;

	type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
		KeyTypeId,
241
		pallet_babe::AuthorityId,
242
243
244
	)>>::IdentificationTuple;

	type HandleEquivocation =
245
		pallet_babe::EquivocationHandler<Self::KeyOwnerIdentification, Offences, ReportLongevity>;
246
247

	type WeightInfo = ();
248
249
}

Gavin Wood's avatar
Gavin Wood committed
250
parameter_types! {
Gavin Wood's avatar
Gavin Wood committed
251
	pub const IndexDeposit: Balance = 10 * DOLLARS;
Gavin Wood's avatar
Gavin Wood committed
252
253
}

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

Gavin Wood's avatar
Gavin Wood committed
262
parameter_types! {
263
	pub const ExistentialDeposit: Balance = 100 * CENTS;
264
	pub const MaxLocks: u32 = 50;
Gavin Wood's avatar
Gavin Wood committed
265
	pub const MaxReserves: u32 = 50;
Gavin Wood's avatar
Gavin Wood committed
266
267
}

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

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

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

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

Gavin Wood's avatar
Gavin Wood committed
301
parameter_types! {
302
	pub const UncleGenerations: u32 = 0;
Gavin Wood's avatar
Gavin Wood committed
303
304
305
}

// TODO: substrate#2986 implement this properly
306
impl pallet_authorship::Config for Runtime {
307
	type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Babe>;
Gavin Wood's avatar
Gavin Wood committed
308
309
	type UncleGenerations = UncleGenerations;
	type FilterUncle = ();
Gavin Wood's avatar
Gavin Wood committed
310
	type EventHandler = (Staking, ImOnline);
Gavin Wood's avatar
Gavin Wood committed
311
312
}

313
impl_opaque_keys! {
314
	pub struct SessionKeys {
Gavin Wood's avatar
Gavin Wood committed
315
316
317
		pub grandpa: Grandpa,
		pub babe: Babe,
		pub im_online: ImOnline,
318
319
		pub para_validator: ParachainSessionKeyPlaceholder<Runtime>,
		pub para_assignment: AssignmentSessionKeyPlaceholder<Runtime>,
Gavin Wood's avatar
Gavin Wood committed
320
		pub authority_discovery: AuthorityDiscovery,
321
	}
322
323
}

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

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

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

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

351
352
	// signed config
	pub const SignedMaxSubmissions: u32 = 16;
353
354
355
356
	// 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;
357
358
	// Each good submission will get 1 DOT as reward
	pub SignedRewardBase: Balance = 1 * UNITS;
359
	// fallback: emergency phase.
360
	pub const Fallback: pallet_election_provider_multi_phase::FallbackStrategy =
361
		pallet_election_provider_multi_phase::FallbackStrategy::Nothing;
362
	pub SolutionImprovementThreshold: Perbill = Perbill::from_rational(5u32, 10_000);
363
364
365

	// miner configs
	pub const MinerMaxIterations: u32 = 10;
366
	pub OffchainRepeat: BlockNumber = 5;
367
368
}

369
370
sp_npos_elections::generate_solution_type!(
	#[compact]
371
372
373
374
375
	pub struct NposCompactSolution16::<
		VoterIndex = u32,
		TargetIndex = u16,
		Accuracy = sp_runtime::PerU16,
	>(16)
376
377
);

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

411
412
413
// 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))%`.
414
pallet_staking_reward_curve::build! {
thiolliere's avatar
thiolliere committed
415
416
417
	const REWARD_CURVE: PiecewiseLinear<'static> = curve!(
		min_inflation: 0_025_000,
		max_inflation: 0_100_000,
418
419
420
		// 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
421
422
423
424
425
426
		falloff: 0_050_000,
		max_piece_count: 40,
		test_precision: 0_005_000,
	);
}

427
parameter_types! {
Gavin Wood's avatar
Gavin Wood committed
428
	// Six sessions in an era (24 hours).
429
	pub const SessionsPerEra: SessionIndex = 6;
Gavin Wood's avatar
Gavin Wood committed
430
	// 28 eras for unbonding (28 days).
431
432
	pub const BondingDuration: pallet_staking::EraIndex = 28;
	pub const SlashDeferDuration: pallet_staking::EraIndex = 27;
thiolliere's avatar
thiolliere committed
433
	pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE;
434
	pub const MaxNominatorRewardedPerValidator: u32 = 256;
435
}
436

Gavin Wood's avatar
Gavin Wood committed
437
438
439
type SlashCancelOrigin = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
440
	pallet_collective::EnsureProportionAtLeast<_3, _4, AccountId, CouncilCollective>,
Gavin Wood's avatar
Gavin Wood committed
441
442
>;

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

Gavin Wood's avatar
Gavin Wood committed
470
471
472
473
474
475
476
477
478
479
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;
}

480
impl pallet_identity::Config for Runtime {
Gavin Wood's avatar
Gavin Wood committed
481
482
483
484
485
486
487
488
489
	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
490
491
	type ForceOrigin = MoreThanHalfCouncil;
	type RegistrarOrigin = MoreThanHalfCouncil;
492
	type WeightInfo = weights::pallet_identity::WeightInfo<Runtime>;
Gavin Wood's avatar
Gavin Wood committed
493
494
}

495
parameter_types! {
496
497
	pub const LaunchPeriod: BlockNumber = 28 * DAYS;
	pub const VotingPeriod: BlockNumber = 28 * DAYS;
498
	pub const FastTrackVotingPeriod: BlockNumber = 3 * HOURS;
499
	pub const MinimumDeposit: Balance = 100 * DOLLARS;
Gav Wood's avatar
Gav Wood committed
500
	pub const EnactmentPeriod: BlockNumber = 28 * DAYS;
501
	pub const CooloffPeriod: BlockNumber = 7 * DAYS;
Gavin Wood's avatar
Gavin Wood committed
502
503
	// One cent: $10,000 / MB
	pub const PreimageByteDeposit: Balance = 1 * CENTS;
Gavin Wood's avatar
Gavin Wood committed
504
	pub const InstantAllowed: bool = true;
505
	pub const MaxVotes: u32 = 100;
506
	pub const MaxProposals: u32 = 100;
507
508
}

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

578
579
parameter_types! {
	pub const CouncilMotionDuration: BlockNumber = 7 * DAYS;
580
	pub const CouncilMaxProposals: u32 = 100;
581
	pub const CouncilMaxMembers: u32 = 100;
582
583
}

584
pub type CouncilCollective = pallet_collective::Instance1;
585
impl pallet_collective::Config<CouncilCollective> for Runtime {
586
587
588
	type Origin = Origin;
	type Proposal = Call;
	type Event = Event;
589
	type MotionDuration = CouncilMotionDuration;
590
	type MaxProposals = CouncilMaxProposals;
591
	type MaxMembers = CouncilMaxMembers;
Wei Tang's avatar
Wei Tang committed
592
	type DefaultVote = pallet_collective::PrimeDefaultVote;
593
	type WeightInfo = weights::pallet_collective::WeightInfo<Runtime>;
594
595
}

Gavin Wood's avatar
Gavin Wood committed
596
parameter_types! {
597
	pub const CandidacyBond: Balance = 100 * DOLLARS;
Kian Paimani's avatar
Kian Paimani committed
598
599
600
601
	// 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
602
603
	/// Weekly council elections; scaling up to monthly eventually.
	pub const TermDuration: BlockNumber = 7 * DAYS;
604
	/// 13 members initially, to be increased to 23 eventually.
605
	pub const DesiredMembers: u32 = 13;
606
	pub const DesiredRunnersUp: u32 = 20;
607
	pub const PhragmenElectionPalletId: LockIdentifier = *b"phrelect";
608
}
609
610
// Make sure that there are no more than `MaxMembers` members elected via phragmen.
const_assert!(DesiredMembers::get() <= CouncilMaxMembers::get());
611

612
impl pallet_elections_phragmen::Config for Runtime {
613
	type Event = Event;
614
	type PalletId = PhragmenElectionPalletId;
615
616
	type Currency = Balances;
	type ChangeMembers = Council;
617
	type InitializeMembers = Council;
618
	type CurrencyToVote = frame_support::traits::U128CurrencyToVote;
Gavin Wood's avatar
Gavin Wood committed
619
	type CandidacyBond = CandidacyBond;
Kian Paimani's avatar
Kian Paimani committed
620
621
	type VotingBondBase = VotingBondBase;
	type VotingBondFactor = VotingBondFactor;
622
623
	type LoserCandidate = Treasury;
	type KickedMember = Treasury;
Gavin Wood's avatar
Gavin Wood committed
624
625
626
	type DesiredMembers = DesiredMembers;
	type DesiredRunnersUp = DesiredRunnersUp;
	type TermDuration = TermDuration;
627
	type WeightInfo = weights::pallet_elections_phragmen::WeightInfo<Runtime>;
628
629
}

630
631
parameter_types! {
	pub const TechnicalMotionDuration: BlockNumber = 7 * DAYS;
632
	pub const TechnicalMaxProposals: u32 = 100;
633
	pub const TechnicalMaxMembers: u32 = 100;
634
635
}

636
pub type TechnicalCollective = pallet_collective::Instance2;
637
impl pallet_collective::Config<TechnicalCollective> for Runtime {
638
639
640
	type Origin = Origin;
	type Proposal = Call;
	type Event = Event;
641
	type MotionDuration = TechnicalMotionDuration;
642
	type MaxProposals = TechnicalMaxProposals;
643
	type MaxMembers = TechnicalMaxMembers;
Wei Tang's avatar
Wei Tang committed
644
	type DefaultVote = pallet_collective::PrimeDefaultVote;
645
	type WeightInfo = weights::pallet_collective::WeightInfo<Runtime>;
646
647
}

648
impl pallet_membership::Config<pallet_membership::Instance1> for Runtime {
649
	type Event = Event;
Gavin Wood's avatar
Gavin Wood committed
650
651
652
653
654
	type AddOrigin = MoreThanHalfCouncil;
	type RemoveOrigin = MoreThanHalfCouncil;
	type SwapOrigin = MoreThanHalfCouncil;
	type ResetOrigin = MoreThanHalfCouncil;
	type PrimeOrigin = MoreThanHalfCouncil;
655
656
	type MembershipInitialized = TechnicalCommittee;
	type MembershipChanged = TechnicalCommittee;
657
	type MaxMembers = TechnicalMaxMembers;
Kian Paimani's avatar
Kian Paimani committed
658
	type WeightInfo = weights::pallet_membership::WeightInfo<Runtime>;
659
660
}

Gavin Wood's avatar
Gavin Wood committed
661
662
parameter_types! {
	pub const ProposalBond: Permill = Permill::from_percent(5);
663
664
665
	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
666
	pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry");
Gavin Wood's avatar
Gavin Wood committed
667
668
669
670

	pub const TipCountdown: BlockNumber = 1 * DAYS;
	pub const TipFindersFee: Percent = Percent::from_percent(20);
	pub const TipReportDepositBase: Balance = 1 * DOLLARS;
671
672
673
674
675
676
677
	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;
678
	pub const MaxApprovals: u32 = 100;
Gavin Wood's avatar
Gavin Wood committed
679
680
}

Gavin Wood's avatar
Gavin Wood committed
681
682
683
type ApproveOrigin = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
684
	pallet_collective::EnsureProportionAtLeast<_3, _5, AccountId, CouncilCollective>,
Gavin Wood's avatar
Gavin Wood committed
685
686
>;

687
impl pallet_treasury::Config for Runtime {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
688
	type PalletId = TreasuryPalletId;
Gavin Wood's avatar
Gavin Wood committed
689
	type Currency = Balances;
Gavin Wood's avatar
Gavin Wood committed
690
691
	type ApproveOrigin = ApproveOrigin;
	type RejectOrigin = MoreThanHalfCouncil;
692
	type Event = Event;
693
	type OnSlash = Treasury;
Gavin Wood's avatar
Gavin Wood committed
694
695
696
697
	type ProposalBond = ProposalBond;
	type ProposalBondMinimum = ProposalBondMinimum;
	type SpendPeriod = SpendPeriod;
	type Burn = Burn;
698
699
	type BurnDestination = ();
	type SpendFunds = Bounties;
700
	type MaxApprovals = MaxApprovals;
701
702
703
704
705
	type WeightInfo = weights::pallet_treasury::WeightInfo<Runtime>;
}

impl pallet_bounties::Config for Runtime {
	type Event = Event;
706
707
708
709
710
	type BountyDepositBase = BountyDepositBase;
	type BountyDepositPayoutDelay = BountyDepositPayoutDelay;
	type BountyUpdatePeriod = BountyUpdatePeriod;
	type BountyCuratorDeposit = BountyCuratorDeposit;
	type BountyValueMinimum = BountyValueMinimum;
711
712
713
714
715
716
717
718
719
	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;
720
	type Tippers = PhragmenElection;
721
722
723
724
	type TipCountdown = TipCountdown;
	type TipFindersFee = TipFindersFee;
	type TipReportDepositBase = TipReportDepositBase;
	type WeightInfo = weights::pallet_tips::WeightInfo<Runtime>;
725
}
726

727
impl pallet_offences::Config for Runtime {
728
	type Event = Event;
729
	type IdentificationTuple = pallet_session::historical::IdentificationTuple<Self>;
730
731
732
	type OnOffenceHandler = Staking;
}

733
impl pallet_authority_discovery::Config for Runtime {}
Gavin Wood's avatar
Gavin Wood committed
734

735
parameter_types! {
736
	pub NposSolutionPriority: TransactionPriority =
737
		Perbill::from_percent(90) * TransactionPriority::max_value();
738
739
740
	pub const ImOnlineUnsignedPriority: TransactionPriority = TransactionPriority::max_value();
}

741
impl pallet_im_online::Config for Runtime {
thiolliere's avatar
thiolliere committed
742
	type AuthorityId = ImOnlineId;
743
	type Event = Event;
744
	type ValidatorSet = Historical;
745
	type NextSessionRotation = Babe;
Gavin Wood's avatar
Gavin Wood committed
746
	type ReportUnresponsiveness = Offences;
747
	type UnsignedPriority = ImOnlineUnsignedPriority;
748
	type WeightInfo = weights::pallet_im_online::WeightInfo<Runtime>;
749
750
}

751
impl pallet_grandpa::Config for Runtime {
752
	type Event = Event;
753
754
755
	type Call = Call;

	type KeyOwnerProof =
756
		<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;
757
758
759
760
761
762

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

Gavin Wood's avatar
Gavin Wood committed
763
764
	type KeyOwnerProofSystem = Historical;

765
766
767
768
769
	type HandleEquivocation = pallet_grandpa::EquivocationHandler<
		Self::KeyOwnerIdentification,
		Offences,
		ReportLongevity,
	>;
770
771

	type WeightInfo = ();
772
773
}

774
775
/// Submits a transaction with the node's public and signature type. Adheres to the signed extension
/// format of the chain.
776
777
impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime
where
778
779
	Call: From<LocalCall>,
{
780
	fn create_transaction<C: frame_system::offchain::AppCrypto<Self::Public, Self::Signature>>(
781
782
783
		call: Call,
		public: <Signature as Verify>::Signer,
		account: AccountId,
784
		nonce: <Runtime as frame_system::Config>::Index,
785
	) -> Option<(Call, <UncheckedExtrinsic as ExtrinsicT>::SignaturePayload)> {
786
		use sp_runtime::traits::StaticLookup;
787
		// take the biggest period possible.
788
789
		let period =
			BlockHashCount::get().checked_next_power_of_two().map(|c| c / 2).unwrap_or(2) as u64;
790
791
792

		let current_block = System::block_number()
			.saturated_into::<u64>()