lib.rs 69.3 KB
Newer Older
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1
// Copyright 2017-2020 Parity Technologies (UK) Ltd.
Gav's avatar
Gav committed
2
3
4
5
6
7
8
9
10
11
12
13
14
// 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
use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId;
use beefy_primitives::crypto::AuthorityId as BeefyId;
use frame_support::{
	construct_runtime, parameter_types,
52
	traits::{Contains, Everything, InstanceFilter, KeyOwnerProofSystem, LockIdentifier, Nothing},
53
54
	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;
Gavin Wood's avatar
Gavin Wood committed
78
use xcm::latest::prelude::*;
79
80
81
82
83
84
85
86
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;
87

88
89
pub use pallet_balances::Call as BalancesCall;
pub use pallet_election_provider_multi_phase::Call as EPMCall;
Gav Wood's avatar
Gav Wood committed
90
#[cfg(feature = "std")]
91
pub use pallet_staking::StakerStatus;
92
pub use pallet_timestamp::Call as TimestampCall;
93
#[cfg(any(feature = "std", test))]
94
pub use sp_runtime::BuildStorage;
95
96
97

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

100
101
102
// Weights used in the runtime.
mod weights;

103
104
105
#[cfg(test)]
mod tests;

106
107
108
109
// Make the WASM binary available.
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));

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

124
125
126
127
/// The BABE epoch configuration at genesis.
pub const BABE_GENESIS_EPOCH_CONFIG: babe_primitives::BabeEpochConfiguration =
	babe_primitives::BabeEpochConfiguration {
		c: PRIMARY_PROBABILITY,
128
		allowed_slots: babe_primitives::AllowedSlots::PrimaryAndSecondaryVRFSlots,
129
130
	};

131
132
133
/// Native version.
#[cfg(any(feature = "std", test))]
pub fn native_version() -> NativeVersion {
134
	NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
135
136
}

137
/// Don't allow swaps until parathread story is more mature.
138
pub struct BaseFilter;
139
140
impl Contains<Call> for BaseFilter {
	fn contains(c: &Call) -> bool {
141
		!matches!(c, Call::Registrar(paras_registrar::Call::swap(..)))
142
143
144
	}
}

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

151
parameter_types! {
152
	pub const Version: RuntimeVersion = VERSION;
153
	pub const SS58Prefix: u8 = 2;
154
155
}

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

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

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

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

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

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

	// session module is the trigger
217
	type EpochChangeTrigger = pallet_babe::ExternalTrigger;
218

219
220
	type DisabledValidators = Session;

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

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

231
232
	type KeyOwnerProofSystem = Historical;

233
	type HandleEquivocation =
234
		pallet_babe::EquivocationHandler<Self::KeyOwnerIdentification, Offences, ReportLongevity>;
235
236

	type WeightInfo = ();
237
238
}

Gavin Wood's avatar
Gavin Wood committed
239
parameter_types! {
240
	pub const IndexDeposit: Balance = 100 * CENTS;
Gavin Wood's avatar
Gavin Wood committed
241
242
}

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

Gavin Wood's avatar
Gavin Wood committed
251
parameter_types! {
Gavin Wood's avatar
Gavin Wood committed
252
	pub const ExistentialDeposit: Balance = 1 * CENTS;
253
	pub const MaxLocks: u32 = 50;
Gavin Wood's avatar
Gavin Wood committed
254
	pub const MaxReserves: u32 = 50;
Gavin Wood's avatar
Gavin Wood committed
255
256
}

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

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

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

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

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

294
impl pallet_authorship::Config for Runtime {
295
	type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Babe>;
Gavin Wood's avatar
Gavin Wood committed
296
297
	type UncleGenerations = UncleGenerations;
	type FilterUncle = ();
Gavin Wood's avatar
Gavin Wood committed
298
	type EventHandler = (Staking, ImOnline);
Gavin Wood's avatar
Gavin Wood committed
299
300
}

301
302
303
304
305
306
parameter_types! {
	pub const Period: BlockNumber = 10 * MINUTES;
	pub const Offset: BlockNumber = 0;
}

impl_opaque_keys! {
307
	pub struct SessionKeys {
Gavin Wood's avatar
Gavin Wood committed
308
309
310
		pub grandpa: Grandpa,
		pub babe: Babe,
		pub im_online: ImOnline,
311
		pub para_validator: Initializer,
312
		pub para_assignment: ParaSessionInfo,
Gavin Wood's avatar
Gavin Wood committed
313
		pub authority_discovery: AuthorityDiscovery,
314
	}
315
316
}

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

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

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

339
parameter_types! {
340
341
	// phase durations. 1/4 of the last session for each.
	pub const SignedPhase: u32 = EPOCH_DURATION_IN_SLOTS / 4;
342
	pub const UnsignedPhase: u32 = EPOCH_DURATION_IN_SLOTS / 4;
343

344
345
	// signed config
	pub const SignedMaxSubmissions: u32 = 16;
346
347
	pub const SignedDepositBase: Balance = deposit(2, 0);
	pub const SignedDepositByte: Balance = deposit(0, 10) / 1024;
348
349
	// Each good submission will get 1/10 KSM as reward
	pub SignedRewardBase: Balance =  UNITS / 10;
350
	// fallback: emergency phase.
351
	pub const Fallback: pallet_election_provider_multi_phase::FallbackStrategy =
352
		pallet_election_provider_multi_phase::FallbackStrategy::Nothing;
353
	pub SolutionImprovementThreshold: Perbill = Perbill::from_rational(5u32, 10_000);
354
355
356

	// miner configs
	pub const MinerMaxIterations: u32 = 10;
357
	pub OffchainRepeat: BlockNumber = 5;
358
359
}

360
361
sp_npos_elections::generate_solution_type!(
	#[compact]
Kian Paimani's avatar
Kian Paimani committed
362
	pub struct NposCompactSolution24::<
363
364
365
		VoterIndex = u32,
		TargetIndex = u16,
		Accuracy = sp_runtime::PerU16,
Kian Paimani's avatar
Kian Paimani committed
366
	>(24)
367
368
);

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

402
403
404
405
406
407
408
409
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;
410
	use sp_arithmetic::traits::Saturating;
411
412
413
414
415
416
417
418
419

	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.
420
	let ideal_stake = Perquintill::from_percent(75).saturating_sub(auction_proportion);
421
422
423
424

	let stake = Perquintill::from_rational(total_staked, non_gilt_issuance);
	let falloff = Perquintill::from_percent(5);
	let adjustment = compute_inflation(stake, ideal_stake, falloff);
425
426
	let staking_inflation =
		min_annual_inflation.saturating_add(delta_annual_inflation * adjustment);
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447

	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) {
448
449
450
		// 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();
451
452
453
454
455
456
457
458
		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),
459
			auctioned_slots,
460
461
		)
	}
thiolliere's avatar
thiolliere committed
462
463
}

464
parameter_types! {
Gavin Wood's avatar
Gavin Wood committed
465
	// Six sessions in an era (6 hours).
466
	pub const SessionsPerEra: SessionIndex = 6;
Gavin Wood's avatar
Gavin Wood committed
467
	// 28 eras for unbonding (7 days).
468
	pub const BondingDuration: pallet_staking::EraIndex = 28;
469
	// 27 eras in which slashes can be cancelled (slightly less than 7 days).
470
	pub const SlashDeferDuration: pallet_staking::EraIndex = 27;
471
	pub const MaxNominatorRewardedPerValidator: u32 = 256;
472
}
473

Gavin Wood's avatar
Gavin Wood committed
474
475
476
type SlashCancelOrigin = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
477
	pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>,
Gavin Wood's avatar
Gavin Wood committed
478
479
>;

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

507
parameter_types! {
508
509
	pub const LaunchPeriod: BlockNumber = 7 * DAYS;
	pub const VotingPeriod: BlockNumber = 7 * DAYS;
510
	pub const FastTrackVotingPeriod: BlockNumber = 3 * HOURS;
511
	pub const MinimumDeposit: Balance = 100 * CENTS;
512
513
	pub const EnactmentPeriod: BlockNumber = 8 * DAYS;
	pub const CooloffPeriod: BlockNumber = 7 * DAYS;
Gavin Wood's avatar
Gavin Wood committed
514
	// One cent: $10,000 / MB
Gavin Wood's avatar
Gavin Wood committed
515
	pub const PreimageByteDeposit: Balance = 10 * MILLICENTS;
516
	pub const InstantAllowed: bool = true;
517
	pub const MaxVotes: u32 = 100;
518
	pub const MaxProposals: u32 = 100;
519
520
}

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

576
577
parameter_types! {
	pub const CouncilMotionDuration: BlockNumber = 3 * DAYS;
578
	pub const CouncilMaxProposals: u32 = 100;
579
	pub const CouncilMaxMembers: u32 = 100;
580
581
}

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

Gavin Wood's avatar
Gavin Wood committed
594
parameter_types! {
595
	pub const CandidacyBond: Balance = 100 * CENTS;
Kian Paimani's avatar
Kian Paimani committed
596
597
598
599
600
	// 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
601
	pub const TermDuration: BlockNumber = 24 * HOURS;
602
603
	pub const DesiredMembers: u32 = 19;
	pub const DesiredRunnersUp: u32 = 19;
604
	pub const PhragmenElectionPalletId: LockIdentifier = *b"phrelect";
605
}
Kian Paimani's avatar
Kian Paimani committed
606

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

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

628
629
parameter_types! {
	pub const TechnicalMotionDuration: BlockNumber = 3 * DAYS;
630
	pub const TechnicalMaxProposals: u32 = 100;
631
	pub const TechnicalMaxMembers: u32 = 100;
632
633
}

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

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

Gavin Wood's avatar
Gavin Wood committed
659
660
parameter_types! {
	pub const ProposalBond: Permill = Permill::from_percent(5);
661
	pub const ProposalBondMinimum: Balance = 2000 * CENTS;
662
	pub const SpendPeriod: BlockNumber = 6 * DAYS;
663
	pub const Burn: Permill = Permill::from_perthousand(2);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
664
	pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry");
Gavin Wood's avatar
Gavin Wood committed
665
666
667

	pub const TipCountdown: BlockNumber = 1 * DAYS;
	pub const TipFindersFee: Percent = Percent::from_percent(20);
668
	pub const TipReportDepositBase: Balance = 100 * CENTS;
669
	pub const DataDepositPerByte: Balance = 1 * CENTS;
670
	pub const BountyDepositBase: Balance = 100 * CENTS;
671
672
673
674
	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);
675
	pub const BountyValueMinimum: Balance = 200 * CENTS;
676
	pub const MaxApprovals: u32 = 100;
677
	pub const MaxAuthorities: u32 = 100_000;
Gavin Wood's avatar
Gavin Wood committed
678
679
}

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

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

impl pallet_bounties::Config for Runtime {
704
705
706
707
708
	type BountyDepositBase = BountyDepositBase;
	type BountyDepositPayoutDelay = BountyDepositPayoutDelay;
	type BountyUpdatePeriod = BountyUpdatePeriod;
	type BountyCuratorDeposit = BountyCuratorDeposit;
	type BountyValueMinimum = BountyValueMinimum;
709
	type DataDepositPerByte = DataDepositPerByte;
710
	type Event = Event;
711
712
713
714
715
716
	type MaximumReasonLength = MaximumReasonLength;
	type WeightInfo = weights::pallet_bounties::WeightInfo<Runtime>;
}

impl pallet_tips::Config for Runtime {
	type MaximumReasonLength = MaximumReasonLength;
717
	type DataDepositPerByte = DataDepositPerByte;
718
	type Tippers = PhragmenElection;
719
720
721
	type TipCountdown = TipCountdown;
	type TipFindersFee = TipFindersFee;
	type TipReportDepositBase = TipReportDepositBase;
722
	type Event = Event;
723
	type WeightInfo = weights::pallet_tips::WeightInfo<Runtime>;
724
}
725

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

732
733
734
impl pallet_authority_discovery::Config for Runtime {
	type MaxAuthorities = MaxAuthorities;
}
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;
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
757
758
759
760
761
762
763
	type Call = Call;

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

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

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 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