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

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

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

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

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

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

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

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

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

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

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

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

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

Qinxuan Chen's avatar
Qinxuan Chen committed
179
180
impl pallet_randomness_collective_flip::Config for Runtime {}

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

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

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

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

211
impl pallet_babe::Config for Runtime {
212
213
	type EpochDuration = EpochDuration;
	type ExpectedBlockTime = ExpectedBlockTime;
214
215

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

	type KeyOwnerProofSystem = Historical;

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

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

	type HandleEquivocation =
231
		pallet_babe::EquivocationHandler<Self::KeyOwnerIdentification, Offences, ReportLongevity>;
232
233

	type WeightInfo = ();
234
235
}

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

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

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

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

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

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

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

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

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

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

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

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

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

332
333
334
parameter_types! {
	// no signed phase for now, just unsigned.
	pub const SignedPhase: u32 = 0;
335
	pub const UnsignedPhase: u32 = EPOCH_DURATION_IN_SLOTS / 4;
336

337
	// fallback: run election on-chain.
338
	pub const Fallback: pallet_election_provider_multi_phase::FallbackStrategy =
339
		pallet_election_provider_multi_phase::FallbackStrategy::Nothing;
340
	pub SolutionImprovementThreshold: Perbill = Perbill::from_rational(5u32, 10_000);
341
342
343

	// miner configs
	pub const MinerMaxIterations: u32 = 10;
344
	pub OffchainRepeat: BlockNumber = 5;
345
346
}

347
348
sp_npos_elections::generate_solution_type!(
	#[compact]
349
350
351
352
353
	pub struct NposCompactSolution16::<
		VoterIndex = u32,
		TargetIndex = u16,
		Accuracy = sp_runtime::PerU16,
	>(16)
354
355
);

356
357
358
359
360
impl pallet_election_provider_multi_phase::Config for Runtime {
	type Event = Event;
	type Currency = Balances;
	type SignedPhase = SignedPhase;
	type UnsignedPhase = UnsignedPhase;
361
	type SolutionImprovementThreshold = SolutionImprovementThreshold;
362
	type MinerMaxIterations = MinerMaxIterations;
363
	type MinerMaxWeight = OffchainSolutionWeightLimit; // For now use the one from staking.
364
	type MinerMaxLength = OffchainSolutionLengthLimit;
365
	type OffchainRepeat = OffchainRepeat;
366
	type MinerTxPriority = NposSolutionPriority;
367
368
	type DataProvider = Staking;
	type OnChainAccuracy = Perbill;
369
	type CompactSolution = NposCompactSolution16;
370
371
	type Fallback = Fallback;
	type BenchmarkingConfig = ();
372
373
374
375
376
	type ForceOrigin = EnsureOneOf<
		AccountId,
		EnsureRoot<AccountId>,
		pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, CouncilCollective>,
	>;
377
	type WeightInfo = weights::pallet_election_provider_multi_phase::WeightInfo<Runtime>;
378
379
}

380
381
382
// 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))%`.
383
pallet_staking_reward_curve::build! {
thiolliere's avatar
thiolliere committed
384
385
386
	const REWARD_CURVE: PiecewiseLinear<'static> = curve!(
		min_inflation: 0_025_000,
		max_inflation: 0_100_000,
387
388
389
		// 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
390
391
392
393
394
395
		falloff: 0_050_000,
		max_piece_count: 40,
		test_precision: 0_005_000,
	);
}

396
parameter_types! {
Gavin Wood's avatar
Gavin Wood committed
397
	// Six sessions in an era (24 hours).
398
	pub const SessionsPerEra: SessionIndex = 6;
Gavin Wood's avatar
Gavin Wood committed
399
	// 28 eras for unbonding (28 days).
400
401
	pub const BondingDuration: pallet_staking::EraIndex = 28;
	pub const SlashDeferDuration: pallet_staking::EraIndex = 27;
thiolliere's avatar
thiolliere committed
402
	pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE;
403
	pub const MaxNominatorRewardedPerValidator: u32 = 256;
404
}
405

Gavin Wood's avatar
Gavin Wood committed
406
407
408
type SlashCancelOrigin = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
409
	pallet_collective::EnsureProportionAtLeast<_3, _4, AccountId, CouncilCollective>
Gavin Wood's avatar
Gavin Wood committed
410
411
>;

412
impl pallet_staking::Config for Runtime {
413
	const MAX_NOMINATIONS: u32 = <NposCompactSolution16 as sp_npos_elections::CompactSolution>::LIMIT as u32;
Gavin Wood's avatar
Gavin Wood committed
414
	type Currency = Balances;
415
	type UnixTime = Timestamp;
416
	type CurrencyToVote = CurrencyToVote;
Gavin Wood's avatar
Gavin Wood committed
417
	type RewardRemainder = Treasury;
Gav's avatar
Gav committed
418
	type Event = Event;
419
	type Slash = Treasury;
420
	type Reward = ();
421
422
	type SessionsPerEra = SessionsPerEra;
	type BondingDuration = BondingDuration;
Gavin Wood's avatar
Gavin Wood committed
423
424
	type SlashDeferDuration = SlashDeferDuration;
	// A super-majority of the council can cancel the slash.
Gavin Wood's avatar
Gavin Wood committed
425
	type SlashCancelOrigin = SlashCancelOrigin;
426
	type SessionInterface = Self;
Kian Paimani's avatar
Kian Paimani committed
427
	type EraPayout = pallet_staking::ConvertCurve<RewardCurve>;
Gavin Wood's avatar
Gavin Wood committed
428
	type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator;
429
	type NextNewSession = Session;
430
	type ElectionProvider = ElectionProviderMultiPhase;
431
432
433
434
	type GenesisElectionProvider =
		frame_election_provider_support::onchain::OnChainSequentialPhragmen<
			pallet_election_provider_multi_phase::OnChainConfig<Self>
		>;
435
	type WeightInfo = weights::pallet_staking::WeightInfo<Runtime>;
436
437
}

Gavin Wood's avatar
Gavin Wood committed
438
439
440
441
442
443
444
445
446
447
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;
}

448
impl pallet_identity::Config for Runtime {
Gavin Wood's avatar
Gavin Wood committed
449
450
451
452
453
454
455
456
457
	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
458
459
	type ForceOrigin = MoreThanHalfCouncil;
	type RegistrarOrigin = MoreThanHalfCouncil;
460
	type WeightInfo = weights::pallet_identity::WeightInfo<Runtime>;
Gavin Wood's avatar
Gavin Wood committed
461
462
}

463
parameter_types! {
464
465
	pub const LaunchPeriod: BlockNumber = 28 * DAYS;
	pub const VotingPeriod: BlockNumber = 28 * DAYS;
466
	pub const FastTrackVotingPeriod: BlockNumber = 3 * HOURS;
467
	pub const MinimumDeposit: Balance = 100 * DOLLARS;
Gav Wood's avatar
Gav Wood committed
468
	pub const EnactmentPeriod: BlockNumber = 28 * DAYS;
469
	pub const CooloffPeriod: BlockNumber = 7 * DAYS;
Gavin Wood's avatar
Gavin Wood committed
470
471
	// One cent: $10,000 / MB
	pub const PreimageByteDeposit: Balance = 1 * CENTS;
Gavin Wood's avatar
Gavin Wood committed
472
	pub const InstantAllowed: bool = true;
473
	pub const MaxVotes: u32 = 100;
474
	pub const MaxProposals: u32 = 100;
475
476
}

477
impl pallet_democracy::Config for Runtime {
478
479
	type Proposal = Call;
	type Event = Event;
480
	type Currency = Balances;
481
482
483
484
	type EnactmentPeriod = EnactmentPeriod;
	type LaunchPeriod = LaunchPeriod;
	type VotingPeriod = VotingPeriod;
	type MinimumDeposit = MinimumDeposit;
485
	/// A straight majority of the council can decide what their next motion is.
486
487
488
	type ExternalOrigin = frame_system::EnsureOneOf<AccountId,
		pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>,
		frame_system::EnsureRoot<AccountId>,
Gavin Wood's avatar
Gavin Wood committed
489
	>;
490
	/// A 60% super-majority can have the next scheduled referendum be a straight majority-carries vote.
491
492
493
	type ExternalMajorityOrigin = frame_system::EnsureOneOf<AccountId,
		pallet_collective::EnsureProportionAtLeast<_3, _5, AccountId, CouncilCollective>,
		frame_system::EnsureRoot<AccountId>,
Gavin Wood's avatar
Gavin Wood committed
494
	>;
495
496
	/// A unanimous council can have the next scheduled referendum be a straight default-carries
	/// (NTB) vote.
497
498
499
	type ExternalDefaultOrigin = frame_system::EnsureOneOf<AccountId,
		pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, CouncilCollective>,
		frame_system::EnsureRoot<AccountId>,
Gavin Wood's avatar
Gavin Wood committed
500
	>;
501
502
	/// Two thirds of the technical committee can have an ExternalMajority/ExternalDefault vote
	/// be tabled immediately and with a shorter voting/enactment period.
503
504
505
	type FastTrackOrigin = frame_system::EnsureOneOf<AccountId,
		pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, TechnicalCollective>,
		frame_system::EnsureRoot<AccountId>,
Gavin Wood's avatar
Gavin Wood committed
506
	>;
507
508
509
	type InstantOrigin = frame_system::EnsureOneOf<AccountId,
		pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, TechnicalCollective>,
		frame_system::EnsureRoot<AccountId>,
Gavin Wood's avatar
Gavin Wood committed
510
	>;
511
512
	type InstantAllowed = InstantAllowed;
	type FastTrackVotingPeriod = FastTrackVotingPeriod;
513
	// To cancel a proposal which has been passed, 2/3 of the council must agree to it.
514
	type CancellationOrigin = EnsureOneOf<AccountId,
515
		pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, CouncilCollective>,
516
517
518
519
520
521
522
		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
523
	>;
524
	type BlacklistOrigin = EnsureRoot<AccountId>;
525
526
	// 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.
527
	type VetoOrigin = pallet_collective::EnsureMember<AccountId, TechnicalCollective>;
528
	type CooloffPeriod = CooloffPeriod;
Gavin Wood's avatar
Gavin Wood committed
529
	type PreimageByteDeposit = PreimageByteDeposit;
530
	type OperationalPreimageOrigin = pallet_collective::EnsureMember<AccountId, CouncilCollective>;
Gavin Wood's avatar
Gavin Wood committed
531
	type Slash = Treasury;
Gavin Wood's avatar
Gavin Wood committed
532
	type Scheduler = Scheduler;
533
	type PalletsOrigin = OriginCaller;
534
	type MaxVotes = MaxVotes;
535
536
	type WeightInfo = weights::pallet_democracy::WeightInfo<Runtime>;
	type MaxProposals = MaxProposals;
537
}
538

539
540
parameter_types! {
	pub const CouncilMotionDuration: BlockNumber = 7 * DAYS;
541
	pub const CouncilMaxProposals: u32 = 100;
542
	pub const CouncilMaxMembers: u32 = 100;
543
544
}

545
type CouncilCollective = pallet_collective::Instance1;
546
impl pallet_collective::Config<CouncilCollective> for Runtime {
547
548
549
	type Origin = Origin;
	type Proposal = Call;
	type Event = Event;
550
	type MotionDuration = CouncilMotionDuration;
551
	type MaxProposals = CouncilMaxProposals;
552
	type MaxMembers = CouncilMaxMembers;
Wei Tang's avatar
Wei Tang committed
553
	type DefaultVote = pallet_collective::PrimeDefaultVote;
554
	type WeightInfo = weights::pallet_collective::WeightInfo<Runtime>;
555
556
}

Gavin Wood's avatar
Gavin Wood committed
557
parameter_types! {
558
	pub const CandidacyBond: Balance = 100 * DOLLARS;
Kian Paimani's avatar
Kian Paimani committed
559
560
561
562
	// 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
563
564
	/// Weekly council elections; scaling up to monthly eventually.
	pub const TermDuration: BlockNumber = 7 * DAYS;
565
	/// 13 members initially, to be increased to 23 eventually.
566
	pub const DesiredMembers: u32 = 13;
567
	pub const DesiredRunnersUp: u32 = 20;
568
	pub const PhragmenElectionPalletId: LockIdentifier = *b"phrelect";
569
}
570
571
// Make sure that there are no more than `MaxMembers` members elected via phragmen.
const_assert!(DesiredMembers::get() <= CouncilMaxMembers::get());
572

573
impl pallet_elections_phragmen::Config for Runtime {
574
	type Event = Event;
575
	type PalletId = PhragmenElectionPalletId;
576
577
	type Currency = Balances;
	type ChangeMembers = Council;
578
	type InitializeMembers = Council;
579
	type CurrencyToVote = frame_support::traits::U128CurrencyToVote;
Gavin Wood's avatar
Gavin Wood committed
580
	type CandidacyBond = CandidacyBond;
Kian Paimani's avatar
Kian Paimani committed
581
582
	type VotingBondBase = VotingBondBase;
	type VotingBondFactor = VotingBondFactor;
583
584
	type LoserCandidate = Treasury;
	type KickedMember = Treasury;
Gavin Wood's avatar
Gavin Wood committed
585
586
587
	type DesiredMembers = DesiredMembers;
	type DesiredRunnersUp = DesiredRunnersUp;
	type TermDuration = TermDuration;
588
	type WeightInfo = weights::pallet_elections_phragmen::WeightInfo<Runtime>;
589
590
}

591
592
parameter_types! {
	pub const TechnicalMotionDuration: BlockNumber = 7 * DAYS;
593
	pub const TechnicalMaxProposals: u32 = 100;
594
	pub const TechnicalMaxMembers: u32 = 100;
595
596
}

597
type TechnicalCollective = pallet_collective::Instance2;
598
impl pallet_collective::Config<TechnicalCollective> for Runtime {
599
600
601
	type Origin = Origin;
	type Proposal = Call;
	type Event = Event;
602
	type MotionDuration = TechnicalMotionDuration;
603
	type MaxProposals = TechnicalMaxProposals;
604
	type MaxMembers = TechnicalMaxMembers;
Wei Tang's avatar
Wei Tang committed
605
	type DefaultVote = pallet_collective::PrimeDefaultVote;
606
	type WeightInfo = weights::pallet_collective::WeightInfo<Runtime>;
607
608
}

609
impl pallet_membership::Config<pallet_membership::Instance1> for Runtime {
610
	type Event = Event;
Gavin Wood's avatar
Gavin Wood committed
611
612
613
614
615
	type AddOrigin = MoreThanHalfCouncil;
	type RemoveOrigin = MoreThanHalfCouncil;
	type SwapOrigin = MoreThanHalfCouncil;
	type ResetOrigin = MoreThanHalfCouncil;
	type PrimeOrigin = MoreThanHalfCouncil;
616
617
	type MembershipInitialized = TechnicalCommittee;
	type MembershipChanged = TechnicalCommittee;
618
	type MaxMembers = TechnicalMaxMembers;
Kian Paimani's avatar
Kian Paimani committed
619
	type WeightInfo = weights::pallet_membership::WeightInfo<Runtime>;
620
621
}

Gavin Wood's avatar
Gavin Wood committed
622
623
parameter_types! {
	pub const ProposalBond: Permill = Permill::from_percent(5);
624
625
626
	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
627
	pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry");
Gavin Wood's avatar
Gavin Wood committed
628
629
630
631

	pub const TipCountdown: BlockNumber = 1 * DAYS;
	pub const TipFindersFee: Percent = Percent::from_percent(20);
	pub const TipReportDepositBase: Balance = 1 * DOLLARS;
632
633
634
635
636
637
638
	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;
639
	pub const MaxApprovals: u32 = 100;
Gavin Wood's avatar
Gavin Wood committed
640
641
}

Gavin Wood's avatar
Gavin Wood committed
642
643
644
type ApproveOrigin = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
645
	pallet_collective::EnsureProportionAtLeast<_3, _5, AccountId, CouncilCollective>
Gavin Wood's avatar
Gavin Wood committed
646
647
>;

648
impl pallet_treasury::Config for Runtime {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
649
	type PalletId = TreasuryPalletId;
Gavin Wood's avatar
Gavin Wood committed
650
	type Currency = Balances;
Gavin Wood's avatar
Gavin Wood committed
651
652
	type ApproveOrigin = ApproveOrigin;
	type RejectOrigin = MoreThanHalfCouncil;
653
	type Event = Event;
654
	type OnSlash = Treasury;
Gavin Wood's avatar
Gavin Wood committed
655
656
657
658
	type ProposalBond = ProposalBond;
	type ProposalBondMinimum = ProposalBondMinimum;
	type SpendPeriod = SpendPeriod;
	type Burn = Burn;
659
660
	type BurnDestination = ();
	type SpendFunds = Bounties;
661
	type MaxApprovals = MaxApprovals;
662
663
664
665
666
	type WeightInfo = weights::pallet_treasury::WeightInfo<Runtime>;
}

impl pallet_bounties::Config for Runtime {
	type Event = Event;
667
668
669
670
671
	type BountyDepositBase = BountyDepositBase;
	type BountyDepositPayoutDelay = BountyDepositPayoutDelay;
	type BountyUpdatePeriod = BountyUpdatePeriod;
	type BountyCuratorDeposit = BountyCuratorDeposit;
	type BountyValueMinimum = BountyValueMinimum;
672
673
674
675
676
677
678
679
680
	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;
681
	type Tippers = PhragmenElection;
682
683
684
685
	type TipCountdown = TipCountdown;
	type TipFindersFee = TipFindersFee;
	type TipReportDepositBase = TipReportDepositBase;
	type WeightInfo = weights::pallet_tips::WeightInfo<Runtime>;
686
}
687

688
impl pallet_offences::Config for Runtime {
689
	type Event = Event;
690
	type IdentificationTuple = pallet_session::historical::IdentificationTuple<Self>;
691
692
693
	type OnOffenceHandler = Staking;
}

694
impl pallet_authority_discovery::Config for Runtime {}
Gavin Wood's avatar
Gavin Wood committed
695

696
parameter_types! {
697
	pub NposSolutionPriority: TransactionPriority =
698
		Perbill::from_percent(90) * TransactionPriority::max_value();
699
700
701
	pub const ImOnlineUnsignedPriority: TransactionPriority = TransactionPriority::max_value();
}

702
impl pallet_im_online::Config for Runtime {
thiolliere's avatar
thiolliere committed
703
	type AuthorityId = ImOnlineId;
704
	type Event = Event;
705
	type ValidatorSet = Historical;
706
	type NextSessionRotation = Babe;
Gavin Wood's avatar
Gavin Wood committed
707
	type ReportUnresponsiveness = Offences;
708
	type UnsignedPriority = ImOnlineUnsignedPriority;
709
	type WeightInfo = weights::pallet_im_online::WeightInfo<Runtime>;
710
711
}

712
impl pallet_grandpa::Config for Runtime {
713
	type Event = Event;
714
715
716
	type Call = Call;

	type KeyOwnerProof =
Gavin Wood's avatar
Gavin Wood committed
717
	<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;
718
719
720
721
722
723

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

Gavin Wood's avatar
Gavin Wood committed
724
725
	type KeyOwnerProofSystem = Historical;

726
727
	type HandleEquivocation =
		pallet_grandpa::EquivocationHandler<Self::KeyOwnerIdentification, Offences, ReportLongevity>;
728
729

	type WeightInfo = ();
730
731
}

732
733
/// Submits a transaction with the node's public and signature type. Adheres to the signed extension
/// format of the chain.
734
impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime where
735
736
	Call: From<LocalCall>,
{
737
	fn create_transaction<C: frame_system::offchain::AppCrypto<Self::Public, Self::Signature>>(
738
739
740
		call: Call,
		public: <Signature as Verify>::Signer,
		account: AccountId,
741
		nonce: <Runtime as frame_system::Config>::Index,
742
	) -> Option<(Call, <UncheckedExtrinsic as ExtrinsicT>::SignaturePayload)> {
743
		use sp_runtime::traits::StaticLookup;
744
		// take the biggest period possible.
745
746
747
748
749
750
751
		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>()
752
753
			// The `System::block_number` is initialized with `n+1`,
			// so the actual block number is `n`.
754
755
756
			.saturating_sub(1);
		let tip = 0;
		let extra: SignedExtra = (
757
758
759
760
761
762
763
			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),
764
			claims::PrevalidateAttests::<Runtime>::new(),
765
766
		);
		let raw_payload = SignedPayload::new(call, extra).map_err(|e| {
767
			log::warn!("Unable to create signed payload: {:?}", e);