lib.rs 57 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
353
354
355
356
357
	// signed config
	pub const SignedMaxSubmissions: u32 = 16;
	pub const SignedDepositBase: Balance = deposit(1, 0);
	// A typical solution occupies within an order of magnitude of 50kb.
	// This formula is currently adjusted such that a typical solution will spend an amount equal
	// to the base deposit for every 50 kb.
	pub const SignedDepositByte: Balance = deposit(1, 0) / (50 * 1024);
358
359
	// Each good submission will get 1 DOT as reward
	pub SignedRewardBase: Balance = 1 * UNITS;
360
	// fallback: emergency phase.
361
	pub const Fallback: pallet_election_provider_multi_phase::FallbackStrategy =
362
		pallet_election_provider_multi_phase::FallbackStrategy::Nothing;
363
	pub SolutionImprovementThreshold: Perbill = Perbill::from_rational(5u32, 10_000);
364
365
366

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	type WeightInfo = ();
773
774
}

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

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