lib.rs 70.8 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
// 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
15
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
Gav's avatar
Gav committed
16

17
//! The Kusama 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 parity_scale_codec::{Decode, Encode, MaxEncodedLen};
25
use primitives::v1::{
26
	AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt,
27
28
29
	CoreState, GroupRotationInfo, Hash, Id as ParaId, InboundDownwardMessage, InboundHrmpMessage,
	Moment, Nonce, OccupiedCoreAssumption, PersistedValidationData, SessionInfo, Signature,
	ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex,
30
};
31
use runtime_common::{
32
33
34
35
36
37
38
39
40
41
42
43
44
45
	auctions, claims, crowdloan, impls::DealWithFees, paras_registrar, slots, xcm_sender,
	BlockHashCount, BlockLength, BlockWeights, CurrencyToVote, OffchainSolutionLengthLimit,
	OffchainSolutionWeightLimit, RocksDbWeight, SlowAdjustingFeeUpdate, ToAuthor,
};
use sp_core::u32_trait::{_1, _2, _3, _5};
use sp_std::{collections::btree_map::BTreeMap, prelude::*};

use runtime_parachains::{
	configuration as parachains_configuration, dmp as parachains_dmp, hrmp as parachains_hrmp,
	inclusion as parachains_inclusion, initializer as parachains_initializer,
	origin as parachains_origin, paras as parachains_paras,
	paras_inherent as parachains_paras_inherent, reward_points as parachains_reward_points,
	runtime_api_impl::v1 as parachains_runtime_api_impl, scheduler as parachains_scheduler,
	session_info as parachains_session_info, shared as parachains_shared, ump as parachains_ump,
46
};
47

48
49
50
51
52
53
54
use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId;
use beefy_primitives::crypto::AuthorityId as BeefyId;
use frame_support::{
	construct_runtime, parameter_types,
	traits::{All, Filter, InstanceFilter, KeyOwnerProofSystem, LockIdentifier, OnRuntimeUpgrade},
	weights::Weight,
	PalletId, RuntimeDebug,
55
};
56
57
58
59
60
61
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};
62
use sp_arithmetic::Perquintill;
63
use sp_core::OpaqueMetadata;
64
use sp_runtime::{
65
	create_runtime_str, generic, impl_opaque_keys,
66
	traits::{
67
68
		AccountIdLookup, BlakeTwo256, Block as BlockT, ConvertInto, Extrinsic as ExtrinsicT,
		OpaqueKeys, SaturatedConversion, Verify,
69
	},
70
71
	transaction_validity::{TransactionPriority, TransactionSource, TransactionValidity},
	ApplyExtrinsicResult, KeyTypeId, Perbill, Percent, Permill,
Gav Wood's avatar
Gav Wood committed
72
};
73
use sp_staking::SessionIndex;
74
#[cfg(any(feature = "std", test))]
75
use sp_version::NativeVersion;
76
use sp_version::RuntimeVersion;
77
use static_assertions::const_assert;
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
use xcm::v0::{
	BodyId,
	Junction::Parachain,
	MultiAsset::{self, AllConcreteFungible},
	MultiLocation::{self, Null, X1},
	NetworkId, Xcm,
};
use xcm_builder::{
	AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom,
	BackingToPlurality, ChildParachainAsNative, ChildParachainConvertsVia,
	ChildSystemParachainAsSuperuser, CurrencyAdapter as XcmCurrencyAdapter, FixedWeightBounds,
	IsChildSystemParachain, IsConcrete, LocationInverter, SignedAccountId32AsNative,
	SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, UsingComponents,
};
use xcm_executor::XcmExecutor;
93

94
95
pub use pallet_balances::Call as BalancesCall;
pub use pallet_election_provider_multi_phase::Call as EPMCall;
Gav Wood's avatar
Gav Wood committed
96
#[cfg(feature = "std")]
97
pub use pallet_staking::StakerStatus;
98
pub use pallet_timestamp::Call as TimestampCall;
99
#[cfg(any(feature = "std", test))]
100
pub use sp_runtime::BuildStorage;
101
102
103

/// Constant values used within the runtime.
pub mod constants;
104
use constants::{currency::*, fee::*, time::*};
105

106
107
108
// Weights used in the runtime.
mod weights;

109
110
111
#[cfg(test)]
mod tests;

112
113
114
115
// Make the WASM binary available.
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));

116
117
118
119
/// Runtime version (Kusama).
pub const VERSION: RuntimeVersion = RuntimeVersion {
	spec_name: create_runtime_str!("kusama"),
	impl_name: create_runtime_str!("parity-kusama"),
120
	authoring_version: 2,
121
	spec_version: 9090,
122
	impl_version: 0,
123
	#[cfg(not(feature = "disable-runtime-api"))]
124
	apis: RUNTIME_API_VERSIONS,
125
	#[cfg(feature = "disable-runtime-api")]
126
	apis: version::create_apis_vec![[]],
127
	transaction_version: 5,
128
};
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
129

130
131
132
133
/// The BABE epoch configuration at genesis.
pub const BABE_GENESIS_EPOCH_CONFIG: babe_primitives::BabeEpochConfiguration =
	babe_primitives::BabeEpochConfiguration {
		c: PRIMARY_PROBABILITY,
134
		allowed_slots: babe_primitives::AllowedSlots::PrimaryAndSecondaryVRFSlots,
135
136
	};

137
138
139
/// Native version.
#[cfg(any(feature = "std", test))]
pub fn native_version() -> NativeVersion {
140
	NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
141
142
}

143
/// Don't allow swaps until parathread story is more mature.
144
145
pub struct BaseFilter;
impl Filter<Call> for BaseFilter {
146
	fn filter(c: &Call) -> bool {
147
		!matches!(c, Call::Registrar(paras_registrar::Call::swap(..)))
148
149
150
	}
}

Gavin Wood's avatar
Gavin Wood committed
151
152
153
type MoreThanHalfCouncil = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
154
	pallet_collective::EnsureProportionMoreThan<_1, _2, AccountId, CouncilCollective>,
Gavin Wood's avatar
Gavin Wood committed
155
156
>;

157
parameter_types! {
158
	pub const Version: RuntimeVersion = VERSION;
159
	pub const SS58Prefix: u8 = 2;
160
161
}

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

188
parameter_types! {
189
190
	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) *
		BlockWeights::get().max_block;
191
192
193
	pub const MaxScheduledPerBlock: u32 = 50;
}

194
195
196
type ScheduleOrigin = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
197
	pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>,
198
199
>;

200
impl pallet_scheduler::Config for Runtime {
Gavin Wood's avatar
Gavin Wood committed
201
202
	type Event = Event;
	type Origin = Origin;
203
	type PalletsOrigin = OriginCaller;
Gavin Wood's avatar
Gavin Wood committed
204
	type Call = Call;
205
	type MaximumWeight = MaximumSchedulerWeight;
206
	type ScheduleOrigin = ScheduleOrigin;
207
	type MaxScheduledPerBlock = MaxScheduledPerBlock;
208
	type WeightInfo = weights::pallet_scheduler::WeightInfo<Runtime>;
Gavin Wood's avatar
Gavin Wood committed
209
210
}

211
parameter_types! {
212
	pub const EpochDuration: u64 = EPOCH_DURATION_IN_SLOTS as u64;
213
	pub const ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK;
214
215
	pub const ReportLongevity: u64 =
		BondingDuration::get() as u64 * SessionsPerEra::get() as u64 * EpochDuration::get();
216
217
}

218
impl pallet_babe::Config for Runtime {
219
220
	type EpochDuration = EpochDuration;
	type ExpectedBlockTime = ExpectedBlockTime;
221
222

	// session module is the trigger
223
	type EpochChangeTrigger = pallet_babe::ExternalTrigger;
224

225
226
	type DisabledValidators = Session;

227
228
	type KeyOwnerProof = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
		KeyTypeId,
229
		pallet_babe::AuthorityId,
230
231
232
233
	)>>::Proof;

	type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
		KeyTypeId,
234
		pallet_babe::AuthorityId,
235
236
	)>>::IdentificationTuple;

237
238
	type KeyOwnerProofSystem = Historical;

239
	type HandleEquivocation =
240
		pallet_babe::EquivocationHandler<Self::KeyOwnerIdentification, Offences, ReportLongevity>;
241
242

	type WeightInfo = ();
243
244
}

Gavin Wood's avatar
Gavin Wood committed
245
parameter_types! {
246
	pub const IndexDeposit: Balance = 100 * CENTS;
Gavin Wood's avatar
Gavin Wood committed
247
248
}

249
impl pallet_indices::Config for Runtime {
Gav Wood's avatar
Gav Wood committed
250
	type AccountIndex = AccountIndex;
251
252
	type Currency = Balances;
	type Deposit = IndexDeposit;
Gav Wood's avatar
Gav Wood committed
253
	type Event = Event;
254
	type WeightInfo = weights::pallet_indices::WeightInfo<Runtime>;
Gav Wood's avatar
Gav Wood committed
255
256
}

Gavin Wood's avatar
Gavin Wood committed
257
parameter_types! {
Gavin Wood's avatar
Gavin Wood committed
258
	pub const ExistentialDeposit: Balance = 1 * CENTS;
259
	pub const MaxLocks: u32 = 50;
Gavin Wood's avatar
Gavin Wood committed
260
	pub const MaxReserves: u32 = 50;
Gavin Wood's avatar
Gavin Wood committed
261
262
}

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

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

279
impl pallet_transaction_payment::Config for Runtime {
Albrecht's avatar
Albrecht committed
280
	type OnChargeTransaction = CurrencyAdapter<Balances, DealWithFees<Self>>;
Gavin Wood's avatar
Gavin Wood committed
281
	type TransactionByteFee = TransactionByteFee;
282
	type WeightToFee = WeightToFee;
283
	type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
Gav's avatar
Gav committed
284
285
}

286
parameter_types! {
287
	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;
288
}
289
impl pallet_timestamp::Config for Runtime {
290
	type Moment = u64;
291
	type OnTimestampSet = Babe;
292
	type MinimumPeriod = MinimumPeriod;
293
	type WeightInfo = weights::pallet_timestamp::WeightInfo<Runtime>;
294
295
}

Gavin Wood's avatar
Gavin Wood committed
296
parameter_types! {
297
	pub const UncleGenerations: u32 = 0;
Gavin Wood's avatar
Gavin Wood committed
298
299
}

300
impl pallet_authorship::Config for Runtime {
301
	type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Babe>;
Gavin Wood's avatar
Gavin Wood committed
302
303
	type UncleGenerations = UncleGenerations;
	type FilterUncle = ();
Gavin Wood's avatar
Gavin Wood committed
304
	type EventHandler = (Staking, ImOnline);
Gavin Wood's avatar
Gavin Wood committed
305
306
}

307
308
309
310
311
312
parameter_types! {
	pub const Period: BlockNumber = 10 * MINUTES;
	pub const Offset: BlockNumber = 0;
}

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

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

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

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

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

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

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

369
370
sp_npos_elections::generate_solution_type!(
	#[compact]
Kian Paimani's avatar
Kian Paimani committed
371
	pub struct NposCompactSolution24::<
372
373
374
		VoterIndex = u32,
		TargetIndex = u16,
		Accuracy = sp_runtime::PerU16,
Kian Paimani's avatar
Kian Paimani committed
375
	>(24)
376
377
);

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

411
412
413
414
415
416
417
418
fn era_payout(
	total_staked: Balance,
	non_gilt_issuance: Balance,
	max_annual_inflation: Perquintill,
	period_fraction: Perquintill,
	auctioned_slots: u64,
) -> (Balance, Balance) {
	use pallet_staking_reward_fn::compute_inflation;
419
	use sp_arithmetic::traits::Saturating;
420
421
422
423
424
425
426
427
428

	let min_annual_inflation = Perquintill::from_rational(25u64, 1000u64);
	let delta_annual_inflation = max_annual_inflation.saturating_sub(min_annual_inflation);

	// 30% reserved for up to 60 slots.
	let auction_proportion = Perquintill::from_rational(auctioned_slots.min(60), 200u64);

	// Therefore the ideal amount at stake (as a percentage of total issuance) is 75% less the amount that we expect
	// to be taken up with auctions.
429
	let ideal_stake = Perquintill::from_percent(75).saturating_sub(auction_proportion);
430
431
432
433

	let stake = Perquintill::from_rational(total_staked, non_gilt_issuance);
	let falloff = Perquintill::from_percent(5);
	let adjustment = compute_inflation(stake, ideal_stake, falloff);
434
435
	let staking_inflation =
		min_annual_inflation.saturating_add(delta_annual_inflation * adjustment);
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456

	let max_payout = period_fraction * max_annual_inflation * non_gilt_issuance;
	let staking_payout = (period_fraction * staking_inflation) * non_gilt_issuance;
	let rest = max_payout.saturating_sub(staking_payout);

	let other_issuance = non_gilt_issuance.saturating_sub(total_staked);
	if total_staked > other_issuance {
		let _cap_rest = Perquintill::from_rational(other_issuance, total_staked) * staking_payout;
		// We don't do anything with this, but if we wanted to, we could introduce a cap on the treasury amount
		// with: `rest = rest.min(cap_rest);`
	}
	(staking_payout, rest)
}

pub struct EraPayout;
impl pallet_staking::EraPayout<Balance> for EraPayout {
	fn era_payout(
		total_staked: Balance,
		_total_issuance: Balance,
		era_duration_millis: u64,
	) -> (Balance, Balance) {
457
458
459
		// TODO: #3011 Update with proper auctioned slots tracking.
		// This should be fine for the first year of parachains.
		let auctioned_slots: u64 = auctions::Pallet::<Runtime>::auction_counter().into();
460
461
462
463
464
465
466
467
		const MAX_ANNUAL_INFLATION: Perquintill = Perquintill::from_percent(10);
		const MILLISECONDS_PER_YEAR: u64 = 1000 * 3600 * 24 * 36525 / 100;

		era_payout(
			total_staked,
			Gilt::issuance().non_gilt,
			MAX_ANNUAL_INFLATION,
			Perquintill::from_rational(era_duration_millis, MILLISECONDS_PER_YEAR),
468
			auctioned_slots,
469
470
		)
	}
thiolliere's avatar
thiolliere committed
471
472
}

473
parameter_types! {
Gavin Wood's avatar
Gavin Wood committed
474
	// Six sessions in an era (6 hours).
475
	pub const SessionsPerEra: SessionIndex = 6;
Gavin Wood's avatar
Gavin Wood committed
476
	// 28 eras for unbonding (7 days).
477
	pub const BondingDuration: pallet_staking::EraIndex = 28;
478
	// 27 eras in which slashes can be cancelled (slightly less than 7 days).
479
	pub const SlashDeferDuration: pallet_staking::EraIndex = 27;
480
	pub const MaxNominatorRewardedPerValidator: u32 = 256;
481
}
482

Gavin Wood's avatar
Gavin Wood committed
483
484
485
type SlashCancelOrigin = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
486
	pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>,
Gavin Wood's avatar
Gavin Wood committed
487
488
>;

489
impl pallet_staking::Config for Runtime {
490
491
	const MAX_NOMINATIONS: u32 =
		<NposCompactSolution24 as sp_npos_elections::CompactSolution>::LIMIT as u32;
Gavin Wood's avatar
Gavin Wood committed
492
	type Currency = Balances;
493
	type UnixTime = Timestamp;
494
	type CurrencyToVote = CurrencyToVote;
495
	type ElectionProvider = ElectionProviderMultiPhase;
496
497
	type GenesisElectionProvider =
		frame_election_provider_support::onchain::OnChainSequentialPhragmen<
498
			pallet_election_provider_multi_phase::OnChainConfig<Self>,
499
		>;
Gavin Wood's avatar
Gavin Wood committed
500
	type RewardRemainder = Treasury;
Gav's avatar
Gav committed
501
	type Event = Event;
502
	type Slash = Treasury;
503
	type Reward = ();
504
505
	type SessionsPerEra = SessionsPerEra;
	type BondingDuration = BondingDuration;
Gavin Wood's avatar
Gavin Wood committed
506
	type SlashDeferDuration = SlashDeferDuration;
Gavin Wood's avatar
Gavin Wood committed
507
508
	// A majority of the council or root can cancel the slash.
	type SlashCancelOrigin = SlashCancelOrigin;
509
	type SessionInterface = Self;
510
	type EraPayout = EraPayout;
511
	type NextNewSession = Session;
512
	type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator;
513
	type WeightInfo = weights::pallet_staking::WeightInfo<Runtime>;
514
515
}

516
parameter_types! {
517
518
	pub const LaunchPeriod: BlockNumber = 7 * DAYS;
	pub const VotingPeriod: BlockNumber = 7 * DAYS;
519
	pub const FastTrackVotingPeriod: BlockNumber = 3 * HOURS;
520
	pub const MinimumDeposit: Balance = 100 * CENTS;
521
522
	pub const EnactmentPeriod: BlockNumber = 8 * DAYS;
	pub const CooloffPeriod: BlockNumber = 7 * DAYS;
Gavin Wood's avatar
Gavin Wood committed
523
	// One cent: $10,000 / MB
Gavin Wood's avatar
Gavin Wood committed
524
	pub const PreimageByteDeposit: Balance = 10 * MILLICENTS;
525
	pub const InstantAllowed: bool = true;
526
	pub const MaxVotes: u32 = 100;
527
	pub const MaxProposals: u32 = 100;
528
529
}

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

584
585
parameter_types! {
	pub const CouncilMotionDuration: BlockNumber = 3 * DAYS;
586
	pub const CouncilMaxProposals: u32 = 100;
587
	pub const CouncilMaxMembers: u32 = 100;
588
589
}

590
type CouncilCollective = pallet_collective::Instance1;
591
impl pallet_collective::Config<CouncilCollective> for Runtime {
592
593
594
	type Origin = Origin;
	type Proposal = Call;
	type Event = Event;
595
	type MotionDuration = CouncilMotionDuration;
596
	type MaxProposals = CouncilMaxProposals;
597
	type MaxMembers = CouncilMaxMembers;
Wei Tang's avatar
Wei Tang committed
598
	type DefaultVote = pallet_collective::PrimeDefaultVote;
599
	type WeightInfo = weights::pallet_collective::WeightInfo<Runtime>;
600
601
}

Gavin Wood's avatar
Gavin Wood committed
602
parameter_types! {
603
	pub const CandidacyBond: Balance = 100 * CENTS;
Kian Paimani's avatar
Kian Paimani committed
604
605
606
607
608
	// 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);
	/// Daily council elections
Gavin Wood's avatar
Gavin Wood committed
609
	pub const TermDuration: BlockNumber = 24 * HOURS;
610
611
	pub const DesiredMembers: u32 = 19;
	pub const DesiredRunnersUp: u32 = 19;
612
	pub const PhragmenElectionPalletId: LockIdentifier = *b"phrelect";
613
}
Kian Paimani's avatar
Kian Paimani committed
614

615
616
// Make sure that there are no more than MaxMembers members elected via phragmen.
const_assert!(DesiredMembers::get() <= CouncilMaxMembers::get());
617

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

636
637
parameter_types! {
	pub const TechnicalMotionDuration: BlockNumber = 3 * DAYS;
638
	pub const TechnicalMaxProposals: u32 = 100;
639
	pub const TechnicalMaxMembers: u32 = 100;
640
641
}

642
type TechnicalCollective = pallet_collective::Instance2;
643
impl pallet_collective::Config<TechnicalCollective> for Runtime {
644
645
646
	type Origin = Origin;
	type Proposal = Call;
	type Event = Event;
647
	type MotionDuration = TechnicalMotionDuration;
648
	type MaxProposals = TechnicalMaxProposals;
649
	type MaxMembers = TechnicalMaxMembers;
Wei Tang's avatar
Wei Tang committed
650
	type DefaultVote = pallet_collective::PrimeDefaultVote;
651
	type WeightInfo = weights::pallet_collective::WeightInfo<Runtime>;
652
653
}

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

Gavin Wood's avatar
Gavin Wood committed
667
668
parameter_types! {
	pub const ProposalBond: Permill = Permill::from_percent(5);
669
	pub const ProposalBondMinimum: Balance = 2000 * CENTS;
670
	pub const SpendPeriod: BlockNumber = 6 * DAYS;
671
	pub const Burn: Permill = Permill::from_perthousand(2);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
672
	pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry");
Gavin Wood's avatar
Gavin Wood committed
673
674
675

	pub const TipCountdown: BlockNumber = 1 * DAYS;
	pub const TipFindersFee: Percent = Percent::from_percent(20);
676
	pub const TipReportDepositBase: Balance = 100 * CENTS;
677
	pub const DataDepositPerByte: Balance = 1 * CENTS;
678
	pub const BountyDepositBase: Balance = 100 * CENTS;
679
680
681
682
	pub const BountyDepositPayoutDelay: BlockNumber = 4 * DAYS;
	pub const BountyUpdatePeriod: BlockNumber = 90 * DAYS;
	pub const MaximumReasonLength: u32 = 16384;
	pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);
683
	pub const BountyValueMinimum: Balance = 200 * CENTS;
684
	pub const MaxApprovals: u32 = 100;
Gavin Wood's avatar
Gavin Wood committed
685
686
}

Gavin Wood's avatar
Gavin Wood committed
687
688
689
type ApproveOrigin = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
690
	pallet_collective::EnsureProportionAtLeast<_3, _5, AccountId, CouncilCollective>,
Gavin Wood's avatar
Gavin Wood committed
691
692
>;

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

impl pallet_bounties::Config for Runtime {
711
712
713
714
715
	type BountyDepositBase = BountyDepositBase;
	type BountyDepositPayoutDelay = BountyDepositPayoutDelay;
	type BountyUpdatePeriod = BountyUpdatePeriod;
	type BountyCuratorDeposit = BountyCuratorDeposit;
	type BountyValueMinimum = BountyValueMinimum;
716
	type DataDepositPerByte = DataDepositPerByte;
717
	type Event = Event;
718
719
720
721
722
723
	type MaximumReasonLength = MaximumReasonLength;
	type WeightInfo = weights::pallet_bounties::WeightInfo<Runtime>;
}

impl pallet_tips::Config for Runtime {
	type MaximumReasonLength = MaximumReasonLength;
724
	type DataDepositPerByte = DataDepositPerByte;
725
	type Tippers = PhragmenElection;
726
727
728
	type TipCountdown = TipCountdown;
	type TipFindersFee = TipFindersFee;
	type TipReportDepositBase = TipReportDepositBase;
729
	type Event = Event;
730
	type WeightInfo = weights::pallet_tips::WeightInfo<Runtime>;
731
}
732

733
impl pallet_offences::Config for Runtime {
734
	type Event = Event;
735
	type IdentificationTuple = pallet_session::historical::IdentificationTuple<Self>;
736
737
738
	type OnOffenceHandler = Staking;
}

739
impl pallet_authority_discovery::Config for Runtime {}
Gavin Wood's avatar
Gavin Wood committed
740

741
parameter_types! {
742
	pub NposSolutionPriority: TransactionPriority =
743
		Perbill::from_percent(90) * TransactionPriority::max_value();
744
745
746
	pub const ImOnlineUnsignedPriority: TransactionPriority = TransactionPriority::max_value();
}

747
impl pallet_im_online::Config for Runtime {
thiolliere's avatar
thiolliere committed
748
	type AuthorityId = ImOnlineId;
749
	type Event = Event;
750
	type ValidatorSet = Historical;
751
	type NextSessionRotation = Babe;
752
	type ReportUnresponsiveness = Offences;
753
	type UnsignedPriority = ImOnlineUnsignedPriority;
754
	type WeightInfo = weights::pallet_im_online::WeightInfo<Runtime>;
755
756
}

757
impl pallet_grandpa::Config for Runtime {
758
	type Event = Event;
759
760
761
762
763
764
765
766
767
768
	type Call = Call;

	type KeyOwnerProof =
		<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;

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

769
770
	type KeyOwnerProofSystem = Historical;

771
772
773
774
775
	type HandleEquivocation = pallet_grandpa::EquivocationHandler<
		Self::KeyOwnerIdentification,
		Offences,
		ReportLongevity,
	>;
776
777

	type WeightInfo = ();
778
779
}

780
781
/// Submits transaction with the node's public and signature type. Adheres to the signed extension
/// format of the chain.
782
783
impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime
where
784
785
	Call: From<LocalCall>,
{
786
	fn create_transaction<C: frame_system::offchain::AppCrypto<Self::Public, Self::Signature>>(
787
788
789
		call: Call,
		public: <Signature as Verify>::Signer,
		account: AccountId,
790
		nonce: <Runtime as frame_system::Config>::Index,
791
	) -> Option<(Call, <UncheckedExtrinsic as ExtrinsicT>::SignaturePayload)> {