lib.rs 47.3 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
	BlockHashCount, RocksDbWeight, BlockWeights, BlockLength, OffchainSolutionWeightLimit,
28
	ParachainSessionKeyPlaceholder, AssignmentSessionKeyPlaceholder,
29
};
Gav Wood's avatar
Gav Wood committed
30

31
use sp_std::prelude::*;
Sergey Pepyakin's avatar
Sergey Pepyakin committed
32
use sp_std::collections::btree_map::BTreeMap;
33
use sp_core::u32_trait::{_1, _2, _3, _4, _5};
34
use parity_scale_codec::{Encode, Decode};
35
use primitives::v1::{
36
37
	AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt,
	CoreState, GroupRotationInfo, Hash, Id, Moment, Nonce, OccupiedCoreAssumption,
38
	PersistedValidationData, Signature, ValidationCode, ValidatorId, ValidatorIndex,
39
	InboundDownwardMessage, InboundHrmpMessage, SessionInfo, AssignmentId,
40
41
42
43
44
45
};
use sp_runtime::{
	create_runtime_str, generic, impl_opaque_keys, ModuleId, ApplyExtrinsicResult,
	KeyTypeId, Percent, Permill, Perbill, curve::PiecewiseLinear,
	transaction_validity::{TransactionValidity, TransactionSource, TransactionPriority},
	traits::{
46
		BlakeTwo256, Block as BlockT, OpaqueKeys, ConvertInto, AccountIdLookup,
47
48
		Extrinsic as ExtrinsicT, SaturatedConversion, Verify,
	},
49
};
50
51
#[cfg(feature = "runtime-benchmarks")]
use sp_runtime::RuntimeString;
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::{
59
	parameter_types, construct_runtime, debug, RuntimeDebug,
60
	traits::{KeyOwnerProofSystem, Randomness, 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;
69

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

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

82
83
84
// Weights used in the runtime.
mod weights;

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

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

104
105
106
107
108
109
110
111
112
/// Native version.
#[cfg(any(feature = "std", test))]
pub fn native_version() -> NativeVersion {
	NativeVersion {
		runtime_version: VERSION,
		can_author_with: Default::default(),
	}
}

113
114
pub struct BaseFilter;
impl Filter<Call> for BaseFilter {
Gavin Wood's avatar
Gavin Wood committed
115
	fn filter(call: &Call) -> bool {
116
		match call {
Gavin Wood's avatar
Gavin Wood committed
117
			// These modules are all allowed to be called by transactions:
118
119
			Call::Democracy(_) | Call::Council(_) | Call::TechnicalCommittee(_) |
			Call::TechnicalMembership(_) | Call::Treasury(_) | Call::ElectionsPhragmen(_) |
Gavin Wood's avatar
Gavin Wood committed
120
			Call::System(_) | Call::Scheduler(_) | Call::Indices(_) |
Gavin Wood's avatar
Gavin Wood committed
121
			Call::Babe(_) | Call::Timestamp(_) | Call::Balances(_) |
Gavin Wood's avatar
Gavin Wood committed
122
			Call::Authorship(_) | Call::Staking(_) | Call::Offences(_) |
123
			Call::Session(_) | Call::Grandpa(_) | Call::ImOnline(_) |
Gavin Wood's avatar
Gavin Wood committed
124
			Call::AuthorityDiscovery(_) |
Gavin Wood's avatar
Gavin Wood committed
125
			Call::Utility(_) | Call::Claims(_) | Call::Vesting(_) |
126
127
			Call::Identity(_) | Call::Proxy(_) | Call::Multisig(_) |
			Call::Bounties(_) | Call::Tips(_)
128
			=> true,
129
130
131
132
		}
	}
}

Gavin Wood's avatar
Gavin Wood committed
133
134
135
type MoreThanHalfCouncil = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
136
	pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>
Gavin Wood's avatar
Gavin Wood committed
137
138
>;

139
parameter_types! {
140
	pub const Version: RuntimeVersion = VERSION;
141
	pub const SS58Prefix: u8 = 0;
142
143
}

144
impl frame_system::Config for Runtime {
145
	type BaseCallFilter = BaseFilter;
146
147
	type BlockWeights = BlockWeights;
	type BlockLength = BlockLength;
148
	type Origin = Origin;
149
	type Call = Call;
Gav Wood's avatar
Gav Wood committed
150
	type Index = Nonce;
151
152
153
154
	type BlockNumber = BlockNumber;
	type Hash = Hash;
	type Hashing = BlakeTwo256;
	type AccountId = AccountId;
155
	type Lookup = AccountIdLookup<AccountId, ()>;
156
	type Header = generic::Header<BlockNumber, BlakeTwo256>;
Gav's avatar
Gav committed
157
	type Event = Event;
158
	type BlockHashCount = BlockHashCount;
159
	type DbWeight = RocksDbWeight;
160
	type Version = Version;
161
	type PalletInfo = PalletInfo;
162
	type AccountData = pallet_balances::AccountData<Balance>;
Gavin Wood's avatar
Gavin Wood committed
163
	type OnNewAccount = ();
164
	type OnKilledAccount = ();
165
	type SystemWeightInfo = weights::frame_system::WeightInfo<Runtime>;
166
	type SS58Prefix = SS58Prefix;
167
168
}

169
parameter_types! {
170
171
	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) *
		BlockWeights::get().max_block;
172
173
174
	pub const MaxScheduledPerBlock: u32 = 50;
}

175
impl pallet_scheduler::Config for Runtime {
Gavin Wood's avatar
Gavin Wood committed
176
177
	type Event = Event;
	type Origin = Origin;
178
	type PalletsOrigin = OriginCaller;
Gavin Wood's avatar
Gavin Wood committed
179
	type Call = Call;
180
	type MaximumWeight = MaximumSchedulerWeight;
181
	type ScheduleOrigin = EnsureRoot<AccountId>;
182
	type MaxScheduledPerBlock = MaxScheduledPerBlock;
183
	type WeightInfo = weights::pallet_scheduler::WeightInfo<Runtime>;
Gavin Wood's avatar
Gavin Wood committed
184
185
}

186
parameter_types! {
187
	pub const EpochDuration: u64 = EPOCH_DURATION_IN_BLOCKS as u64;
188
	pub const ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK;
189
190
	pub const ReportLongevity: u64 =
		BondingDuration::get() as u64 * SessionsPerEra::get() as u64 * EpochDuration::get();
191
192
}

193
impl pallet_babe::Config for Runtime {
194
195
	type EpochDuration = EpochDuration;
	type ExpectedBlockTime = ExpectedBlockTime;
196
197

	// session module is the trigger
198
	type EpochChangeTrigger = pallet_babe::ExternalTrigger;
199
200
201
202
203

	type KeyOwnerProofSystem = Historical;

	type KeyOwnerProof = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
		KeyTypeId,
204
		pallet_babe::AuthorityId,
205
206
207
208
	)>>::Proof;

	type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
		KeyTypeId,
209
		pallet_babe::AuthorityId,
210
211
212
	)>>::IdentificationTuple;

	type HandleEquivocation =
213
		pallet_babe::EquivocationHandler<Self::KeyOwnerIdentification, Offences, ReportLongevity>;
214
215

	type WeightInfo = ();
216
217
}

Gavin Wood's avatar
Gavin Wood committed
218
parameter_types! {
Gavin Wood's avatar
Gavin Wood committed
219
	pub const IndexDeposit: Balance = 10 * DOLLARS;
Gavin Wood's avatar
Gavin Wood committed
220
221
}

222
impl pallet_indices::Config for Runtime {
Gav Wood's avatar
Gav Wood committed
223
	type AccountIndex = AccountIndex;
224
225
	type Currency = Balances;
	type Deposit = IndexDeposit;
Gav Wood's avatar
Gav Wood committed
226
	type Event = Event;
227
	type WeightInfo = weights::pallet_indices::WeightInfo<Runtime>;
Gav Wood's avatar
Gav Wood committed
228
229
}

Gavin Wood's avatar
Gavin Wood committed
230
parameter_types! {
231
	pub const ExistentialDeposit: Balance = 100 * CENTS;
232
	pub const MaxLocks: u32 = 50;
Gavin Wood's avatar
Gavin Wood committed
233
234
}

235
impl pallet_balances::Config for Runtime {
Gav's avatar
Gav committed
236
	type Balance = Balance;
237
	type DustRemoval = ();
Gavin Wood's avatar
Gavin Wood committed
238
	type Event = Event;
Gavin Wood's avatar
Gavin Wood committed
239
	type ExistentialDeposit = ExistentialDeposit;
240
	type AccountStore = System;
241
	type MaxLocks = MaxLocks;
242
	type WeightInfo = weights::pallet_balances::WeightInfo<Runtime>;
243
244
245
246
247
248
}

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

249
impl pallet_transaction_payment::Config for Runtime {
Albrecht's avatar
Albrecht committed
250
	type OnChargeTransaction = CurrencyAdapter<Balances, DealWithFees<Runtime>>;
Gavin Wood's avatar
Gavin Wood committed
251
	type TransactionByteFee = TransactionByteFee;
252
	type WeightToFee = WeightToFee;
253
	type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
Gav's avatar
Gav committed
254
255
}

256
parameter_types! {
257
	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;
258
}
259
impl pallet_timestamp::Config for Runtime {
260
	type Moment = u64;
261
	type OnTimestampSet = Babe;
262
	type MinimumPeriod = MinimumPeriod;
263
	type WeightInfo = weights::pallet_timestamp::WeightInfo<Runtime>;
264
265
}

Gavin Wood's avatar
Gavin Wood committed
266
parameter_types! {
267
	pub const UncleGenerations: u32 = 0;
Gavin Wood's avatar
Gavin Wood committed
268
269
270
}

// TODO: substrate#2986 implement this properly
271
impl pallet_authorship::Config for Runtime {
272
	type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Babe>;
Gavin Wood's avatar
Gavin Wood committed
273
274
	type UncleGenerations = UncleGenerations;
	type FilterUncle = ();
Gavin Wood's avatar
Gavin Wood committed
275
	type EventHandler = (Staking, ImOnline);
Gavin Wood's avatar
Gavin Wood committed
276
277
}

278
279
280
281
282
283
284
285
286
287
impl_opaque_keys! {
	pub struct OldSessionKeys {
		pub grandpa: Grandpa,
		pub babe: Babe,
		pub im_online: ImOnline,
		pub para_validator: ParachainSessionKeyPlaceholder<Runtime>,
		pub authority_discovery: AuthorityDiscovery,
	}
}

288
impl_opaque_keys! {
289
	pub struct SessionKeys {
Gavin Wood's avatar
Gavin Wood committed
290
291
292
		pub grandpa: Grandpa,
		pub babe: Babe,
		pub im_online: ImOnline,
293
294
		pub para_validator: ParachainSessionKeyPlaceholder<Runtime>,
		pub para_assignment: AssignmentSessionKeyPlaceholder<Runtime>,
Gavin Wood's avatar
Gavin Wood committed
295
		pub authority_discovery: AuthorityDiscovery,
296
	}
297
298
}

299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
fn transform_session_keys(v: AccountId, old: OldSessionKeys) -> SessionKeys {
	SessionKeys {
		grandpa: old.grandpa,
		babe: old.babe,
		im_online: old.im_online,
		para_validator: old.para_validator,
		para_assignment: {
			// We need to produce a dummy value that's unique for the validator.
			let mut id = AssignmentId::default();
			let id_raw: &mut [u8] = id.as_mut();
			id_raw.copy_from_slice(v.as_ref());
			id_raw[0..4].copy_from_slice(b"asgn");

			id
		},
		authority_discovery: old.authority_discovery,
	}
}

thiolliere's avatar
thiolliere committed
318
319
320
321
parameter_types! {
	pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(17);
}

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

335
impl pallet_session::historical::Config for Runtime {
336
337
	type FullIdentification = pallet_staking::Exposure<AccountId, Balance>;
	type FullIdentificationOf = pallet_staking::ExposureOf<Runtime>;
338
339
}

340
341
342
// 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))%`.
343
pallet_staking_reward_curve::build! {
thiolliere's avatar
thiolliere committed
344
345
346
	const REWARD_CURVE: PiecewiseLinear<'static> = curve!(
		min_inflation: 0_025_000,
		max_inflation: 0_100_000,
347
348
349
		// 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
350
351
352
353
354
355
		falloff: 0_050_000,
		max_piece_count: 40,
		test_precision: 0_005_000,
	);
}

356
parameter_types! {
Gavin Wood's avatar
Gavin Wood committed
357
	// Six sessions in an era (24 hours).
358
	pub const SessionsPerEra: SessionIndex = 6;
Gavin Wood's avatar
Gavin Wood committed
359
	// 28 eras for unbonding (28 days).
360
361
	pub const BondingDuration: pallet_staking::EraIndex = 28;
	pub const SlashDeferDuration: pallet_staking::EraIndex = 27;
thiolliere's avatar
thiolliere committed
362
	pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE;
363
	pub const MaxNominatorRewardedPerValidator: u32 = 128;
joe petrowski's avatar
joe petrowski committed
364
	// last 15 minutes of the last session will be for election.
Gavin Wood's avatar
Gavin Wood committed
365
	pub const ElectionLookahead: BlockNumber = EPOCH_DURATION_IN_BLOCKS / 16;
366
367
	pub const MaxIterations: u32 = 10;
	pub MinSolutionScoreBump: Perbill = Perbill::from_rational_approximation(5u32, 10_000);
368
}
369

Gavin Wood's avatar
Gavin Wood committed
370
371
372
type SlashCancelOrigin = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
373
	pallet_collective::EnsureProportionAtLeast<_3, _4, AccountId, CouncilCollective>
Gavin Wood's avatar
Gavin Wood committed
374
375
>;

376
impl pallet_staking::Config for Runtime {
Gavin Wood's avatar
Gavin Wood committed
377
	type Currency = Balances;
378
	type UnixTime = Timestamp;
379
	type CurrencyToVote = CurrencyToVote;
Gavin Wood's avatar
Gavin Wood committed
380
	type RewardRemainder = Treasury;
Gav's avatar
Gav committed
381
	type Event = Event;
382
	type Slash = Treasury;
383
	type Reward = ();
384
385
	type SessionsPerEra = SessionsPerEra;
	type BondingDuration = BondingDuration;
Gavin Wood's avatar
Gavin Wood committed
386
387
	type SlashDeferDuration = SlashDeferDuration;
	// A super-majority of the council can cancel the slash.
Gavin Wood's avatar
Gavin Wood committed
388
	type SlashCancelOrigin = SlashCancelOrigin;
389
	type SessionInterface = Self;
thiolliere's avatar
thiolliere committed
390
	type RewardCurve = RewardCurve;
Gavin Wood's avatar
Gavin Wood committed
391
	type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator;
392
393
394
	type NextNewSession = Session;
	type ElectionLookahead = ElectionLookahead;
	type Call = Call;
395
	type UnsignedPriority = StakingUnsignedPriority;
396
	type MaxIterations = MaxIterations;
397
	type MinSolutionScoreBump = MinSolutionScoreBump;
398
399
400
	// The unsigned solution weight targeted by the OCW. We set it to the maximum possible value of
	// a single extrinsic.
	type OffchainSolutionWeightLimit = OffchainSolutionWeightLimit;
401
	type WeightInfo = weights::pallet_staking::WeightInfo<Runtime>;
402
403
}

Gavin Wood's avatar
Gavin Wood committed
404
405
406
407
408
409
410
411
412
413
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;
}

414
impl pallet_identity::Config for Runtime {
Gavin Wood's avatar
Gavin Wood committed
415
416
417
418
419
420
421
422
423
	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
424
425
	type ForceOrigin = MoreThanHalfCouncil;
	type RegistrarOrigin = MoreThanHalfCouncil;
426
	type WeightInfo = weights::pallet_identity::WeightInfo<Runtime>;
Gavin Wood's avatar
Gavin Wood committed
427
428
}

429
parameter_types! {
430
431
	pub const LaunchPeriod: BlockNumber = 28 * DAYS;
	pub const VotingPeriod: BlockNumber = 28 * DAYS;
432
	pub const FastTrackVotingPeriod: BlockNumber = 3 * HOURS;
433
	pub const MinimumDeposit: Balance = 100 * DOLLARS;
Gav Wood's avatar
Gav Wood committed
434
	pub const EnactmentPeriod: BlockNumber = 28 * DAYS;
435
	pub const CooloffPeriod: BlockNumber = 7 * DAYS;
Gavin Wood's avatar
Gavin Wood committed
436
437
	// One cent: $10,000 / MB
	pub const PreimageByteDeposit: Balance = 1 * CENTS;
Gavin Wood's avatar
Gavin Wood committed
438
	pub const InstantAllowed: bool = true;
439
	pub const MaxVotes: u32 = 100;
440
	pub const MaxProposals: u32 = 100;
441
442
}

443
impl pallet_democracy::Config for Runtime {
444
445
	type Proposal = Call;
	type Event = Event;
446
	type Currency = Balances;
447
448
449
450
	type EnactmentPeriod = EnactmentPeriod;
	type LaunchPeriod = LaunchPeriod;
	type VotingPeriod = VotingPeriod;
	type MinimumDeposit = MinimumDeposit;
451
	/// A straight majority of the council can decide what their next motion is.
452
453
454
	type ExternalOrigin = frame_system::EnsureOneOf<AccountId,
		pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>,
		frame_system::EnsureRoot<AccountId>,
Gavin Wood's avatar
Gavin Wood committed
455
	>;
456
	/// A 60% super-majority can have the next scheduled referendum be a straight majority-carries vote.
457
458
459
	type ExternalMajorityOrigin = frame_system::EnsureOneOf<AccountId,
		pallet_collective::EnsureProportionAtLeast<_3, _5, AccountId, CouncilCollective>,
		frame_system::EnsureRoot<AccountId>,
Gavin Wood's avatar
Gavin Wood committed
460
	>;
461
462
	/// A unanimous council can have the next scheduled referendum be a straight default-carries
	/// (NTB) vote.
463
464
465
	type ExternalDefaultOrigin = frame_system::EnsureOneOf<AccountId,
		pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, CouncilCollective>,
		frame_system::EnsureRoot<AccountId>,
Gavin Wood's avatar
Gavin Wood committed
466
	>;
467
468
	/// Two thirds of the technical committee can have an ExternalMajority/ExternalDefault vote
	/// be tabled immediately and with a shorter voting/enactment period.
469
470
471
	type FastTrackOrigin = frame_system::EnsureOneOf<AccountId,
		pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, TechnicalCollective>,
		frame_system::EnsureRoot<AccountId>,
Gavin Wood's avatar
Gavin Wood committed
472
	>;
473
474
475
	type InstantOrigin = frame_system::EnsureOneOf<AccountId,
		pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, TechnicalCollective>,
		frame_system::EnsureRoot<AccountId>,
Gavin Wood's avatar
Gavin Wood committed
476
	>;
477
478
	type InstantAllowed = InstantAllowed;
	type FastTrackVotingPeriod = FastTrackVotingPeriod;
479
	// To cancel a proposal which has been passed, 2/3 of the council must agree to it.
480
	type CancellationOrigin = EnsureOneOf<AccountId,
481
		pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, CouncilCollective>,
482
483
484
485
486
487
488
		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
489
	>;
490
	type BlacklistOrigin = EnsureRoot<AccountId>;
491
492
	// 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.
493
	type VetoOrigin = pallet_collective::EnsureMember<AccountId, TechnicalCollective>;
494
	type CooloffPeriod = CooloffPeriod;
Gavin Wood's avatar
Gavin Wood committed
495
	type PreimageByteDeposit = PreimageByteDeposit;
496
	type OperationalPreimageOrigin = pallet_collective::EnsureMember<AccountId, CouncilCollective>;
Gavin Wood's avatar
Gavin Wood committed
497
	type Slash = Treasury;
Gavin Wood's avatar
Gavin Wood committed
498
	type Scheduler = Scheduler;
499
	type PalletsOrigin = OriginCaller;
500
	type MaxVotes = MaxVotes;
501
502
	type WeightInfo = weights::pallet_democracy::WeightInfo<Runtime>;
	type MaxProposals = MaxProposals;
503
}
504

505
506
parameter_types! {
	pub const CouncilMotionDuration: BlockNumber = 7 * DAYS;
507
	pub const CouncilMaxProposals: u32 = 100;
508
	pub const CouncilMaxMembers: u32 = 100;
509
510
}

511
type CouncilCollective = pallet_collective::Instance1;
512
impl pallet_collective::Config<CouncilCollective> for Runtime {
513
514
515
	type Origin = Origin;
	type Proposal = Call;
	type Event = Event;
516
	type MotionDuration = CouncilMotionDuration;
517
	type MaxProposals = CouncilMaxProposals;
518
	type MaxMembers = CouncilMaxMembers;
Wei Tang's avatar
Wei Tang committed
519
	type DefaultVote = pallet_collective::PrimeDefaultVote;
520
	type WeightInfo = weights::pallet_collective::WeightInfo<Runtime>;
521
522
}

Gavin Wood's avatar
Gavin Wood committed
523
parameter_types! {
524
	pub const CandidacyBond: Balance = 100 * DOLLARS;
Kian Paimani's avatar
Kian Paimani committed
525
526
527
528
	// 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
529
530
	/// Weekly council elections; scaling up to monthly eventually.
	pub const TermDuration: BlockNumber = 7 * DAYS;
531
	/// 13 members initially, to be increased to 23 eventually.
532
	pub const DesiredMembers: u32 = 13;
533
	pub const DesiredRunnersUp: u32 = 20;
534
	pub const ElectionsPhragmenModuleId: LockIdentifier = *b"phrelect";
535
}
536
537
// Make sure that there are no more than `MaxMembers` members elected via phragmen.
const_assert!(DesiredMembers::get() <= CouncilMaxMembers::get());
538

539
impl pallet_elections_phragmen::Config for Runtime {
540
	type Event = Event;
Gavin Wood's avatar
Gavin Wood committed
541
	type ModuleId = ElectionsPhragmenModuleId;
542
543
	type Currency = Balances;
	type ChangeMembers = Council;
544
	type InitializeMembers = Council;
545
	type CurrencyToVote = frame_support::traits::U128CurrencyToVote;
Gavin Wood's avatar
Gavin Wood committed
546
	type CandidacyBond = CandidacyBond;
Kian Paimani's avatar
Kian Paimani committed
547
548
	type VotingBondBase = VotingBondBase;
	type VotingBondFactor = VotingBondFactor;
549
550
	type LoserCandidate = Treasury;
	type KickedMember = Treasury;
Gavin Wood's avatar
Gavin Wood committed
551
552
553
	type DesiredMembers = DesiredMembers;
	type DesiredRunnersUp = DesiredRunnersUp;
	type TermDuration = TermDuration;
554
	type WeightInfo = weights::pallet_elections_phragmen::WeightInfo<Runtime>;
555
556
}

557
558
parameter_types! {
	pub const TechnicalMotionDuration: BlockNumber = 7 * DAYS;
559
	pub const TechnicalMaxProposals: u32 = 100;
560
	pub const TechnicalMaxMembers: u32 = 100;
561
562
}

563
type TechnicalCollective = pallet_collective::Instance2;
564
impl pallet_collective::Config<TechnicalCollective> for Runtime {
565
566
567
	type Origin = Origin;
	type Proposal = Call;
	type Event = Event;
568
	type MotionDuration = TechnicalMotionDuration;
569
	type MaxProposals = TechnicalMaxProposals;
570
	type MaxMembers = TechnicalMaxMembers;
Wei Tang's avatar
Wei Tang committed
571
	type DefaultVote = pallet_collective::PrimeDefaultVote;
572
	type WeightInfo = weights::pallet_collective::WeightInfo<Runtime>;
573
574
}

575
impl pallet_membership::Config<pallet_membership::Instance1> for Runtime {
576
	type Event = Event;
Gavin Wood's avatar
Gavin Wood committed
577
578
579
580
581
	type AddOrigin = MoreThanHalfCouncil;
	type RemoveOrigin = MoreThanHalfCouncil;
	type SwapOrigin = MoreThanHalfCouncil;
	type ResetOrigin = MoreThanHalfCouncil;
	type PrimeOrigin = MoreThanHalfCouncil;
582
583
584
585
	type MembershipInitialized = TechnicalCommittee;
	type MembershipChanged = TechnicalCommittee;
}

Gavin Wood's avatar
Gavin Wood committed
586
587
parameter_types! {
	pub const ProposalBond: Permill = Permill::from_percent(5);
588
589
590
	pub const ProposalBondMinimum: Balance = 100 * DOLLARS;
	pub const SpendPeriod: BlockNumber = 24 * DAYS;
	pub const Burn: Permill = Permill::from_percent(1);
591
	pub const TreasuryModuleId: ModuleId = ModuleId(*b"py/trsry");
Gavin Wood's avatar
Gavin Wood committed
592
593
594
595

	pub const TipCountdown: BlockNumber = 1 * DAYS;
	pub const TipFindersFee: Percent = Percent::from_percent(20);
	pub const TipReportDepositBase: Balance = 1 * DOLLARS;
596
597
598
599
600
601
602
	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;
Gavin Wood's avatar
Gavin Wood committed
603
604
}

Gavin Wood's avatar
Gavin Wood committed
605
606
607
type ApproveOrigin = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
608
	pallet_collective::EnsureProportionAtLeast<_3, _5, AccountId, CouncilCollective>
Gavin Wood's avatar
Gavin Wood committed
609
610
>;

611
impl pallet_treasury::Config for Runtime {
Gavin Wood's avatar
Gavin Wood committed
612
	type ModuleId = TreasuryModuleId;
Gavin Wood's avatar
Gavin Wood committed
613
	type Currency = Balances;
Gavin Wood's avatar
Gavin Wood committed
614
615
	type ApproveOrigin = ApproveOrigin;
	type RejectOrigin = MoreThanHalfCouncil;
616
	type Event = Event;
617
	type OnSlash = Treasury;
Gavin Wood's avatar
Gavin Wood committed
618
619
620
621
	type ProposalBond = ProposalBond;
	type ProposalBondMinimum = ProposalBondMinimum;
	type SpendPeriod = SpendPeriod;
	type Burn = Burn;
622
623
624
625
626
627
628
	type BurnDestination = ();
	type SpendFunds = Bounties;
	type WeightInfo = weights::pallet_treasury::WeightInfo<Runtime>;
}

impl pallet_bounties::Config for Runtime {
	type Event = Event;
629
630
631
632
633
	type BountyDepositBase = BountyDepositBase;
	type BountyDepositPayoutDelay = BountyDepositPayoutDelay;
	type BountyUpdatePeriod = BountyUpdatePeriod;
	type BountyCuratorDeposit = BountyCuratorDeposit;
	type BountyValueMinimum = BountyValueMinimum;
634
635
636
637
638
639
640
641
642
643
644
645
646
647
	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;
	type Tippers = ElectionsPhragmen;
	type TipCountdown = TipCountdown;
	type TipFindersFee = TipFindersFee;
	type TipReportDepositBase = TipReportDepositBase;
	type WeightInfo = weights::pallet_tips::WeightInfo<Runtime>;
648
}
649

650
parameter_types! {
651
	pub OffencesWeightSoftLimit: Weight = Perbill::from_percent(60) * BlockWeights::get().max_block;
652
653
}

654
impl pallet_offences::Config for Runtime {
655
	type Event = Event;
656
	type IdentificationTuple = pallet_session::historical::IdentificationTuple<Self>;
657
	type OnOffenceHandler = Staking;
658
	type WeightSoftLimit = OffencesWeightSoftLimit;
659
660
}

661
impl pallet_authority_discovery::Config for Runtime {}
Gavin Wood's avatar
Gavin Wood committed
662

663
664
665
666
parameter_types! {
	pub const SessionDuration: BlockNumber = EPOCH_DURATION_IN_BLOCKS as _;
}

667
parameter_types! {
668
669
	pub StakingUnsignedPriority: TransactionPriority =
		Perbill::from_percent(90) * TransactionPriority::max_value();
670
671
672
	pub const ImOnlineUnsignedPriority: TransactionPriority = TransactionPriority::max_value();
}

673
impl pallet_im_online::Config for Runtime {
thiolliere's avatar
thiolliere committed
674
	type AuthorityId = ImOnlineId;
675
	type Event = Event;
676
	type ValidatorSet = Historical;
677
	type SessionDuration = SessionDuration;
Gavin Wood's avatar
Gavin Wood committed
678
	type ReportUnresponsiveness = Offences;
679
	type UnsignedPriority = ImOnlineUnsignedPriority;
680
	type WeightInfo = weights::pallet_im_online::WeightInfo<Runtime>;
681
682
}

683
impl pallet_grandpa::Config for Runtime {
684
	type Event = Event;
685
686
687
	type Call = Call;

	type KeyOwnerProof =
Gavin Wood's avatar
Gavin Wood committed
688
	<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;
689
690
691
692
693
694

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

Gavin Wood's avatar
Gavin Wood committed
695
696
	type KeyOwnerProofSystem = Historical;

697
698
	type HandleEquivocation =
		pallet_grandpa::EquivocationHandler<Self::KeyOwnerIdentification, Offences, ReportLongevity>;
699
700

	type WeightInfo = ();
701
702
}

703
704
/// Submits a transaction with the node's public and signature type. Adheres to the signed extension
/// format of the chain.
705
impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime where
706
707
	Call: From<LocalCall>,
{
708
	fn create_transaction<C: frame_system::offchain::AppCrypto<Self::Public, Self::Signature>>(
709
710
711
		call: Call,
		public: <Signature as Verify>::Signer,
		account: AccountId,
712
		nonce: <Runtime as frame_system::Config>::Index,
713
	) -> Option<(Call, <UncheckedExtrinsic as ExtrinsicT>::SignaturePayload)> {
714
		use sp_runtime::traits::StaticLookup;
715
		// take the biggest period possible.
716
717
718
719
720
721
722
		let period = BlockHashCount::get()
			.checked_next_power_of_two()
			.map(|c| c / 2)
			.unwrap_or(2) as u64;

		let current_block = System::block_number()
			.saturated_into::<u64>()
723
724
			// The `System::block_number` is initialized with `n+1`,
			// so the actual block number is `n`.
725
726
727
			.saturating_sub(1);
		let tip = 0;
		let extra: SignedExtra = (
728
729
730
731
732
733
734
			frame_system::CheckSpecVersion::<Runtime>::new(),
			frame_system::CheckTxVersion::<Runtime>::new(),
			frame_system::CheckGenesis::<Runtime>::new(),
			frame_system::CheckMortality::<Runtime>::from(generic::Era::mortal(period, current_block)),
			frame_system::CheckNonce::<Runtime>::from(nonce),
			frame_system::CheckWeight::<Runtime>::new(),
			pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(tip),
735
			claims::PrevalidateAttests::<Runtime>::new(),
736
737
		);
		let raw_payload = SignedPayload::new(call, extra).map_err(|e| {
738
			debug::warn!("Unable to create signed payload: {:?}", e);
739
		}).ok()?;
740
741
742
		let signature = raw_payload.using_encoded(|payload| {
			C::sign(payload, public)
		})?;
743
		let (call, extra, _) = raw_payload.deconstruct();
744
745
		let address = <Runtime as frame_system::Config>::Lookup::unlookup(account);
		Some((call, (address, signature, extra)))
746
	}
747
748
}

749
impl frame_system::offchain::SigningTypes for Runtime {
750
751
752
753
	type Public = <Signature as Verify>::Signer;
	type Signature = Signature;
}

754
impl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime where Call: From<C> {
755
	type Extrinsic = UncheckedExtrinsic;
Gavin Wood's avatar
Gavin Wood committed
756
	type OverarchingCall = Call;
757
758
}

759
760
761
762
763
764
parameter_types! {
	pub const ParathreadDeposit: Balance = 500 * DOLLARS;
	pub const QueueSize: usize = 2;
	pub const MaxRetries: u32 = 3;
}

Gavin Wood's avatar
Gavin Wood committed
765
parameter_types! {
766
	pub Prefix: &'static [u8] = b"Pay DOTs to the Polkadot account:";
767
768
}

769
impl claims::Config for Runtime {
770
	type Event = Event;
Gavin Wood's avatar
Gavin Wood committed
771
	type VestingSchedule = Vesting;
772
	type Prefix = Prefix;
773
	/// At least 3/4 of the council must agree to a claim move before it can happen.
774
	type MoveClaimOrigin = pallet_collective::EnsureProportionAtLeast<_3, _4, AccountId, CouncilCollective>;
775
	type WeightInfo = weights::runtime_common_claims::WeightInfo<Runtime>;
776
777
}

778
779
780
781
parameter_types! {
	pub const MinVestedTransfer: Balance = 100 * DOLLARS;
}

782
impl pallet_vesting::Config for Runtime {
Gavin Wood's avatar
Gavin Wood committed
783
784
785
	type Event = Event;
	type Currency = Balances;
	type BlockNumberToBalance = ConvertInto;
786
	type MinVestedTransfer = MinVestedTransfer;
787
	type WeightInfo = weights::pallet_vesting::WeightInfo<Runtime>;
Gavin Wood's avatar
Gavin Wood committed
788
789
}

790
impl pallet_utility::Config for Runtime {
791
792
	type Event