lib.rs 75.2 KB
Newer Older
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1
// Copyright 2017-2020 Parity Technologies (UK) Ltd.
Gav's avatar
Gav committed
2
3
4
5
6
7
8
9
10
11
12
13
14
// 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
	CoreState, GroupRotationInfo, Hash, Id as ParaId, InboundDownwardMessage, InboundHrmpMessage,
28
29
	Moment, Nonce, OccupiedCoreAssumption, PersistedValidationData, ScrapedOnChainVotes,
	SessionInfo, Signature, ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex,
30
};
31
use runtime_common::{
32
33
34
35
36
	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};
37
use sp_std::{cmp::Ordering, collections::btree_map::BTreeMap, prelude::*};
38
39

use runtime_parachains::{
40
41
42
	configuration as parachains_configuration, disputes as parachains_disputes,
	dmp as parachains_dmp, hrmp as parachains_hrmp, inclusion as parachains_inclusion,
	initializer as parachains_initializer, origin as parachains_origin, paras as parachains_paras,
43
44
45
	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
use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId;
use beefy_primitives::crypto::AuthorityId as BeefyId;
use frame_support::{
51
	construct_runtime, match_type, parameter_types,
52
53
	traits::{
		Contains, Everything, InstanceFilter, KeyOwnerProofSystem, LockIdentifier, Nothing,
54
		OnRuntimeUpgrade, PrivilegeCmp,
55
	},
56
57
	weights::Weight,
	PalletId, RuntimeDebug,
58
};
59
60
61
62
63
64
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};
65
use sp_arithmetic::Perquintill;
66
use sp_core::OpaqueMetadata;
67
use sp_runtime::{
68
	create_runtime_str, generic, impl_opaque_keys,
69
	traits::{
70
71
		AccountIdLookup, BlakeTwo256, Block as BlockT, ConvertInto, Extrinsic as ExtrinsicT,
		OpaqueKeys, SaturatedConversion, Verify,
72
	},
73
74
	transaction_validity::{TransactionPriority, TransactionSource, TransactionValidity},
	ApplyExtrinsicResult, KeyTypeId, Perbill, Percent, Permill,
Gav Wood's avatar
Gav Wood committed
75
};
76
use sp_staking::SessionIndex;
77
#[cfg(any(feature = "std", test))]
78
use sp_version::NativeVersion;
79
use sp_version::RuntimeVersion;
80
use static_assertions::const_assert;
Gavin Wood's avatar
Gavin Wood committed
81
use xcm::latest::prelude::*;
82
use xcm_builder::{
83
84
85
86
87
88
	AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom,
	AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, BackingToPlurality,
	ChildParachainAsNative, ChildParachainConvertsVia, ChildSystemParachainAsSuperuser,
	CurrencyAdapter as XcmCurrencyAdapter, FixedWeightBounds, IsChildSystemParachain, IsConcrete,
	LocationInverter, SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation,
	TakeWeightCredit, UsingComponents,
89
90
};
use xcm_executor::XcmExecutor;
91

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

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

104
105
106
// Weights used in the runtime.
mod weights;

107
// Voter bag threshold definitions.
108
mod bag_thresholds;
109

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

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

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

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

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

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

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

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

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

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

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

201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
/// Used the compare the privilege of an origin inside the scheduler.
pub struct OriginPrivilegeCmp;

impl PrivilegeCmp<OriginCaller> for OriginPrivilegeCmp {
	fn cmp_privilege(left: &OriginCaller, right: &OriginCaller) -> Option<Ordering> {
		if left == right {
			return Some(Ordering::Equal)
		}

		match (left, right) {
			// Root is greater than anything.
			(OriginCaller::system(frame_system::RawOrigin::Root), _) => Some(Ordering::Greater),
			// Check which one has more yes votes.
			(
				OriginCaller::Council(pallet_collective::RawOrigin::Members(l_yes_votes, l_count)),
				OriginCaller::Council(pallet_collective::RawOrigin::Members(r_yes_votes, r_count)),
			) => Some((l_yes_votes * r_count).cmp(&(r_yes_votes * l_count))),
			// For every other origin we don't care, as they are not used for `ScheduleOrigin`.
			_ => None,
		}
	}
}

224
impl pallet_scheduler::Config for Runtime {
Gavin Wood's avatar
Gavin Wood committed
225
226
	type Event = Event;
	type Origin = Origin;
227
	type PalletsOrigin = OriginCaller;
Gavin Wood's avatar
Gavin Wood committed
228
	type Call = Call;
229
	type MaximumWeight = MaximumSchedulerWeight;
230
	type ScheduleOrigin = ScheduleOrigin;
231
	type MaxScheduledPerBlock = MaxScheduledPerBlock;
232
	type WeightInfo = weights::pallet_scheduler::WeightInfo<Runtime>;
233
	type OriginPrivilegeCmp = OriginPrivilegeCmp;
Gavin Wood's avatar
Gavin Wood committed
234
235
}

236
parameter_types! {
237
	pub const EpochDuration: u64 = EPOCH_DURATION_IN_SLOTS as u64;
238
	pub const ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK;
239
240
	pub const ReportLongevity: u64 =
		BondingDuration::get() as u64 * SessionsPerEra::get() as u64 * EpochDuration::get();
241
242
}

243
impl pallet_babe::Config for Runtime {
244
245
	type EpochDuration = EpochDuration;
	type ExpectedBlockTime = ExpectedBlockTime;
246
247

	// session module is the trigger
248
	type EpochChangeTrigger = pallet_babe::ExternalTrigger;
249

250
251
	type DisabledValidators = Session;

252
253
	type KeyOwnerProof = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
		KeyTypeId,
254
		pallet_babe::AuthorityId,
255
256
257
258
	)>>::Proof;

	type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
		KeyTypeId,
259
		pallet_babe::AuthorityId,
260
261
	)>>::IdentificationTuple;

262
263
	type KeyOwnerProofSystem = Historical;

264
	type HandleEquivocation =
265
		pallet_babe::EquivocationHandler<Self::KeyOwnerIdentification, Offences, ReportLongevity>;
266
267

	type WeightInfo = ();
268
269

	type MaxAuthorities = MaxAuthorities;
270
271
}

Gavin Wood's avatar
Gavin Wood committed
272
parameter_types! {
273
	pub const IndexDeposit: Balance = 100 * CENTS;
Gavin Wood's avatar
Gavin Wood committed
274
275
}

276
impl pallet_indices::Config for Runtime {
Gav Wood's avatar
Gav Wood committed
277
	type AccountIndex = AccountIndex;
278
279
	type Currency = Balances;
	type Deposit = IndexDeposit;
Gav Wood's avatar
Gav Wood committed
280
	type Event = Event;
281
	type WeightInfo = weights::pallet_indices::WeightInfo<Runtime>;
Gav Wood's avatar
Gav Wood committed
282
283
}

Gavin Wood's avatar
Gavin Wood committed
284
parameter_types! {
Gavin Wood's avatar
Gavin Wood committed
285
	pub const ExistentialDeposit: Balance = 1 * CENTS;
286
	pub const MaxLocks: u32 = 50;
Gavin Wood's avatar
Gavin Wood committed
287
	pub const MaxReserves: u32 = 50;
Gavin Wood's avatar
Gavin Wood committed
288
289
}

290
impl pallet_balances::Config for Runtime {
Gav's avatar
Gav committed
291
	type Balance = Balance;
292
	type DustRemoval = ();
Gavin Wood's avatar
Gavin Wood committed
293
	type Event = Event;
Gavin Wood's avatar
Gavin Wood committed
294
	type ExistentialDeposit = ExistentialDeposit;
295
	type AccountStore = System;
296
	type MaxLocks = MaxLocks;
Gavin Wood's avatar
Gavin Wood committed
297
298
299
	type MaxReserves = MaxReserves;
	type ReserveIdentifier = [u8; 8];
	type WeightInfo = weights::pallet_balances::WeightInfo<Runtime>;
300
301
302
303
}

parameter_types! {
	pub const TransactionByteFee: Balance = 10 * MILLICENTS;
304
305
306
	/// This value increases the priority of `Operational` transactions by adding
	/// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.
	pub const OperationalFeeMultiplier: u8 = 5;
307
308
}

309
impl pallet_transaction_payment::Config for Runtime {
Albrecht's avatar
Albrecht committed
310
	type OnChargeTransaction = CurrencyAdapter<Balances, DealWithFees<Self>>;
Gavin Wood's avatar
Gavin Wood committed
311
	type TransactionByteFee = TransactionByteFee;
312
	type OperationalFeeMultiplier = OperationalFeeMultiplier;
313
	type WeightToFee = WeightToFee;
314
	type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
Gav's avatar
Gav committed
315
316
}

317
parameter_types! {
318
	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;
319
}
320
impl pallet_timestamp::Config for Runtime {
321
	type Moment = u64;
322
	type OnTimestampSet = Babe;
323
	type MinimumPeriod = MinimumPeriod;
324
	type WeightInfo = weights::pallet_timestamp::WeightInfo<Runtime>;
325
326
}

Gavin Wood's avatar
Gavin Wood committed
327
parameter_types! {
328
	pub const UncleGenerations: u32 = 0;
Gavin Wood's avatar
Gavin Wood committed
329
330
}

331
impl pallet_authorship::Config for Runtime {
332
	type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Babe>;
Gavin Wood's avatar
Gavin Wood committed
333
334
	type UncleGenerations = UncleGenerations;
	type FilterUncle = ();
Gavin Wood's avatar
Gavin Wood committed
335
	type EventHandler = (Staking, ImOnline);
Gavin Wood's avatar
Gavin Wood committed
336
337
}

338
339
340
341
342
343
parameter_types! {
	pub const Period: BlockNumber = 10 * MINUTES;
	pub const Offset: BlockNumber = 0;
}

impl_opaque_keys! {
344
	pub struct SessionKeys {
Gavin Wood's avatar
Gavin Wood committed
345
346
347
		pub grandpa: Grandpa,
		pub babe: Babe,
		pub im_online: ImOnline,
348
		pub para_validator: Initializer,
349
		pub para_assignment: ParaSessionInfo,
Gavin Wood's avatar
Gavin Wood committed
350
		pub authority_discovery: AuthorityDiscovery,
351
	}
352
353
}

354
impl pallet_session::Config for Runtime {
Gav's avatar
Gav committed
355
	type Event = Event;
356
	type ValidatorId = AccountId;
357
	type ValidatorIdOf = pallet_staking::StashOf<Self>;
Gavin Wood's avatar
Gavin Wood committed
358
	type ShouldEndSession = Babe;
359
	type NextSessionRotation = Babe;
360
	type SessionManager = pallet_session::historical::NoteHistoricalRoot<Self, Staking>;
Gavin Wood's avatar
Gavin Wood committed
361
362
	type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
	type Keys = SessionKeys;
363
	type WeightInfo = weights::pallet_session::WeightInfo<Runtime>;
364
365
}

366
impl pallet_session::historical::Config for Runtime {
367
368
	type FullIdentification = pallet_staking::Exposure<AccountId, Balance>;
	type FullIdentificationOf = pallet_staking::ExposureOf<Runtime>;
369
370
}

371
parameter_types! {
372
373
	// phase durations. 1/4 of the last session for each.
	pub const SignedPhase: u32 = EPOCH_DURATION_IN_SLOTS / 4;
374
	pub const UnsignedPhase: u32 = EPOCH_DURATION_IN_SLOTS / 4;
375

376
377
	// signed config
	pub const SignedMaxSubmissions: u32 = 16;
378
379
	pub const SignedDepositBase: Balance = deposit(2, 0);
	pub const SignedDepositByte: Balance = deposit(0, 10) / 1024;
380
381
	// Each good submission will get 1/10 KSM as reward
	pub SignedRewardBase: Balance =  UNITS / 10;
382
	pub SolutionImprovementThreshold: Perbill = Perbill::from_rational(5u32, 10_000);
383

384
385
	// 1 hour session, 15 minutes unsigned phase, 8 offchain executions.
	pub OffchainRepeat: BlockNumber = UnsignedPhase::get() / 8;
386
387
388
389
390

	/// Whilst `UseNominatorsAndUpdateBagsList` or `UseNominatorsMap` is in use, this can still be a
	/// very large value. Once the `BagsList` is in full motion, staking might open its door to many
	/// more nominators, and this value should instead be what is a "safe" number (e.g. 22500).
	pub const VoterSnapshotPerBlock: u32 = 22_500;
391
392
}

393
394
sp_npos_elections::generate_solution_type!(
	#[compact]
Kian Paimani's avatar
Kian Paimani committed
395
	pub struct NposCompactSolution24::<
396
397
398
		VoterIndex = u32,
		TargetIndex = u16,
		Accuracy = sp_runtime::PerU16,
Kian Paimani's avatar
Kian Paimani committed
399
	>(24)
400
401
);

402
403
404
impl pallet_election_provider_multi_phase::Config for Runtime {
	type Event = Event;
	type Currency = Balances;
405
	type EstimateCallFee = TransactionPayment;
406
	type UnsignedPhase = UnsignedPhase;
407
408
409
410
411
412
413
414
	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
415
	type SignedPhase = SignedPhase;
416
	type SolutionImprovementThreshold = SolutionImprovementThreshold;
417
	type MinerMaxWeight = OffchainSolutionWeightLimit; // For now use the one from staking.
418
	type MinerMaxLength = OffchainSolutionLengthLimit;
419
	type OffchainRepeat = OffchainRepeat;
420
	type MinerTxPriority = NposSolutionPriority;
421
	type DataProvider = Staking;
422
	type Solution = NposCompactSolution24;
Kian Paimani's avatar
Kian Paimani committed
423
	type Fallback = pallet_election_provider_multi_phase::NoFallback<Self>;
424
425
	type Solver = frame_election_provider_support::SequentialPhragmen<
		AccountId,
Kian Paimani's avatar
Kian Paimani committed
426
		pallet_election_provider_multi_phase::SolutionAccuracyOf<Self>,
427
428
		runtime_common::elections::OffchainRandomBalancing,
	>;
429
	type BenchmarkingConfig = runtime_common::elections::BenchmarkConfig;
430
431
432
433
434
	type ForceOrigin = EnsureOneOf<
		AccountId,
		EnsureRoot<AccountId>,
		pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, CouncilCollective>,
	>;
Kian Paimani's avatar
Kian Paimani committed
435
	type WeightInfo = weights::pallet_election_provider_multi_phase::WeightInfo<Self>;
436
437
438
439
	type VoterSnapshotPerBlock = VoterSnapshotPerBlock;
}

parameter_types! {
440
	pub const BagThresholds: &'static [u64] = &bag_thresholds::THRESHOLDS;
441
442
443
444
445
446
447
}

impl pallet_bags_list::Config for Runtime {
	type Event = Event;
	type VoteWeightProvider = Staking;
	type WeightInfo = weights::pallet_bags_list::WeightInfo<Runtime>;
	type BagThresholds = BagThresholds;
448
449
}

450
451
452
453
454
455
456
457
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;
458
	use sp_arithmetic::traits::Saturating;
459
460
461
462
463
464
465
466
467

	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.
468
	let ideal_stake = Perquintill::from_percent(75).saturating_sub(auction_proportion);
469
470
471
472

	let stake = Perquintill::from_rational(total_staked, non_gilt_issuance);
	let falloff = Perquintill::from_percent(5);
	let adjustment = compute_inflation(stake, ideal_stake, falloff);
473
474
	let staking_inflation =
		min_annual_inflation.saturating_add(delta_annual_inflation * adjustment);
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495

	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) {
496
497
498
		// 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();
499
500
501
502
503
504
505
506
		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),
507
			auctioned_slots,
508
509
		)
	}
thiolliere's avatar
thiolliere committed
510
511
}

512
parameter_types! {
Gavin Wood's avatar
Gavin Wood committed
513
	// Six sessions in an era (6 hours).
514
	pub const SessionsPerEra: SessionIndex = 6;
Gavin Wood's avatar
Gavin Wood committed
515
	// 28 eras for unbonding (7 days).
516
	pub const BondingDuration: pallet_staking::EraIndex = 28;
517
	// 27 eras in which slashes can be cancelled (slightly less than 7 days).
518
	pub const SlashDeferDuration: pallet_staking::EraIndex = 27;
519
	pub const MaxNominatorRewardedPerValidator: u32 = 256;
520
	pub const OffendingValidatorsThreshold: Perbill = Perbill::from_percent(17);
521
}
522

Gavin Wood's avatar
Gavin Wood committed
523
524
525
type SlashCancelOrigin = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
526
	pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>,
Gavin Wood's avatar
Gavin Wood committed
527
528
>;

Kian Paimani's avatar
Kian Paimani committed
529
530
531
532
533
impl frame_election_provider_support::onchain::Config for Runtime {
	type Accuracy = runtime_common::elections::OnOnChainAccuracy;
	type DataProvider = Staking;
}

534
impl pallet_staking::Config for Runtime {
535
	const MAX_NOMINATIONS: u32 =
536
		<NposCompactSolution24 as sp_npos_elections::NposSolution>::LIMIT as u32;
Gavin Wood's avatar
Gavin Wood committed
537
	type Currency = Balances;
538
	type UnixTime = Timestamp;
539
	type CurrencyToVote = CurrencyToVote;
540
	type ElectionProvider = ElectionProviderMultiPhase;
Kian Paimani's avatar
Kian Paimani committed
541
	type GenesisElectionProvider = runtime_common::elections::GenesisElectionOf<Self>;
Gavin Wood's avatar
Gavin Wood committed
542
	type RewardRemainder = Treasury;
Gav's avatar
Gav committed
543
	type Event = Event;
544
	type Slash = Treasury;
545
	type Reward = ();
546
547
	type SessionsPerEra = SessionsPerEra;
	type BondingDuration = BondingDuration;
Gavin Wood's avatar
Gavin Wood committed
548
	type SlashDeferDuration = SlashDeferDuration;
Gavin Wood's avatar
Gavin Wood committed
549
550
	// A majority of the council or root can cancel the slash.
	type SlashCancelOrigin = SlashCancelOrigin;
551
	type SessionInterface = Self;
552
	type EraPayout = EraPayout;
553
	type NextNewSession = Session;
554
	type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator;
555
	type OffendingValidatorsThreshold = OffendingValidatorsThreshold;
556
	// Use the nominators map to iter voters, but also keep bags-list up-to-date.
557
	type SortedListProvider = BagsList;
558
	type WeightInfo = weights::pallet_staking::WeightInfo<Runtime>;
559
560
}

561
parameter_types! {
562
563
	pub const LaunchPeriod: BlockNumber = 7 * DAYS;
	pub const VotingPeriod: BlockNumber = 7 * DAYS;
564
	pub const FastTrackVotingPeriod: BlockNumber = 3 * HOURS;
565
	pub const MinimumDeposit: Balance = 100 * CENTS;
566
567
	pub const EnactmentPeriod: BlockNumber = 8 * DAYS;
	pub const CooloffPeriod: BlockNumber = 7 * DAYS;
Gavin Wood's avatar
Gavin Wood committed
568
	// One cent: $10,000 / MB
Gavin Wood's avatar
Gavin Wood committed
569
	pub const PreimageByteDeposit: Balance = 10 * MILLICENTS;
570
	pub const InstantAllowed: bool = true;
571
	pub const MaxVotes: u32 = 100;
572
	pub const MaxProposals: u32 = 100;
573
574
}

575
impl pallet_democracy::Config for Runtime {
576
577
	type Proposal = Call;
	type Event = Event;
578
	type Currency = Balances;
579
	type EnactmentPeriod = EnactmentPeriod;
Xiliang Chen's avatar
Xiliang Chen committed
580
	type VoteLockingPeriod = EnactmentPeriod;
581
582
583
	type LaunchPeriod = LaunchPeriod;
	type VotingPeriod = VotingPeriod;
	type MinimumDeposit = MinimumDeposit;
584
	/// A straight majority of the council can decide what their next motion is.
585
586
	type ExternalOrigin =
		pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>;
587
	/// A majority can have the next scheduled referendum be a straight majority-carries vote.
588
589
	type ExternalMajorityOrigin =
		pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>;
590
591
	/// A unanimous council can have the next scheduled referendum be a straight default-carries
	/// (NTB) vote.
592
593
	type ExternalDefaultOrigin =
		pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, CouncilCollective>;
Denis_P's avatar
Denis_P committed
594
	/// Two thirds of the technical committee can have an `ExternalMajority/ExternalDefault` vote
595
	/// be tabled immediately and with a shorter voting/enactment period.
596
597
598
599
	type FastTrackOrigin =
		pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, TechnicalCollective>;
	type InstantOrigin =
		pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, TechnicalCollective>;
600
601
	type InstantAllowed = InstantAllowed;
	type FastTrackVotingPeriod = FastTrackVotingPeriod;
602
	// To cancel a proposal which has been passed, 2/3 of the council must agree to it.
603
604
605
606
607
	type CancellationOrigin = EnsureOneOf<
		AccountId,
		EnsureRoot<AccountId>,
		pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, CouncilCollective>,
	>;
608
	type BlacklistOrigin = EnsureRoot<AccountId>;
609
610
611
612
613
614
615
	// 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>,
	>;
616
617
	// 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.
618
	type VetoOrigin = pallet_collective::EnsureMember<AccountId, TechnicalCollective>;
619
	type CooloffPeriod = CooloffPeriod;
Gavin Wood's avatar
Gavin Wood committed
620
	type PreimageByteDeposit = PreimageByteDeposit;
621
	type OperationalPreimageOrigin = pallet_collective::EnsureMember<AccountId, CouncilCollective>;
Gavin Wood's avatar
Gavin Wood committed
622
	type Slash = Treasury;
Gavin Wood's avatar
Gavin Wood committed
623
	type Scheduler = Scheduler;
624
	type PalletsOrigin = OriginCaller;
625
	type MaxVotes = MaxVotes;
626
627
	type WeightInfo = weights::pallet_democracy::WeightInfo<Runtime>;
	type MaxProposals = MaxProposals;
628
}
629

630
631
parameter_types! {
	pub const CouncilMotionDuration: BlockNumber = 3 * DAYS;
632
	pub const CouncilMaxProposals: u32 = 100;
633
	pub const CouncilMaxMembers: u32 = 100;
634
635
}

636
type CouncilCollective = pallet_collective::Instance1;
637
impl pallet_collective::Config<CouncilCollective> for Runtime {
638
639
640
	type Origin = Origin;
	type Proposal = Call;
	type Event = Event;
641
	type MotionDuration = CouncilMotionDuration;
642
	type MaxProposals = CouncilMaxProposals;
643
	type MaxMembers = CouncilMaxMembers;
Wei Tang's avatar
Wei Tang committed
644
	type DefaultVote = pallet_collective::PrimeDefaultVote;
645
	type WeightInfo = weights::pallet_collective_council::WeightInfo<Runtime>;
646
647
}

Gavin Wood's avatar
Gavin Wood committed
648
parameter_types! {
649
	pub const CandidacyBond: Balance = 100 * CENTS;
Kian Paimani's avatar
Kian Paimani committed
650
651
652
653
654
	// 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
655
	pub const TermDuration: BlockNumber = 24 * HOURS;
656
657
	pub const DesiredMembers: u32 = 19;
	pub const DesiredRunnersUp: u32 = 19;
658
	pub const PhragmenElectionPalletId: LockIdentifier = *b"phrelect";
659
}
Kian Paimani's avatar
Kian Paimani committed
660

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

664
impl pallet_elections_phragmen::Config for Runtime {
665
	type Event = Event;
666
667
	type Currency = Balances;
	type ChangeMembers = Council;
668
	type InitializeMembers = Council;
669
	type CurrencyToVote = frame_support::traits::U128CurrencyToVote;
Gavin Wood's avatar
Gavin Wood committed
670
	type CandidacyBond = CandidacyBond;
Kian Paimani's avatar
Kian Paimani committed
671
672
	type VotingBondBase = VotingBondBase;
	type VotingBondFactor = VotingBondFactor;
673
674
	type LoserCandidate = Treasury;
	type KickedMember = Treasury;
Gavin Wood's avatar
Gavin Wood committed
675
676
677
	type DesiredMembers = DesiredMembers;
	type DesiredRunnersUp = DesiredRunnersUp;
	type TermDuration = TermDuration;
678
	type PalletId = PhragmenElectionPalletId;
679
	type WeightInfo = weights::pallet_elections_phragmen::WeightInfo<Runtime>;
680
681
}

682
683
parameter_types! {
	pub const TechnicalMotionDuration: BlockNumber = 3 * DAYS;
684
	pub const TechnicalMaxProposals: u32 = 100;
685
	pub const TechnicalMaxMembers: u32 = 100;
686
687
}

688
type TechnicalCollective = pallet_collective::Instance2;
689
impl pallet_collective::Config<TechnicalCollective> for Runtime {
690
691
692
	type Origin = Origin;
	type Proposal = Call;
	type Event = Event;
693
	type MotionDuration = TechnicalMotionDuration;
694
	type MaxProposals = TechnicalMaxProposals;
695
	type MaxMembers = TechnicalMaxMembers;
Wei Tang's avatar
Wei Tang committed
696
	type DefaultVote = pallet_collective::PrimeDefaultVote;
697
	type WeightInfo = weights::pallet_collective_technical_committee::WeightInfo<Runtime>;
698
699
}

700
impl pallet_membership::Config<pallet_membership::Instance1> for Runtime {
701
	type Event = Event;
Gavin Wood's avatar
Gavin Wood committed
702
703
704
705
706
	type AddOrigin = MoreThanHalfCouncil;
	type RemoveOrigin = MoreThanHalfCouncil;
	type SwapOrigin = MoreThanHalfCouncil;
	type ResetOrigin = MoreThanHalfCouncil;
	type PrimeOrigin = MoreThanHalfCouncil;
707
708
	type MembershipInitialized = TechnicalCommittee;
	type MembershipChanged = TechnicalCommittee;
709
	type MaxMembers = TechnicalMaxMembers;
Kian Paimani's avatar
Kian Paimani committed
710
	type WeightInfo = weights::pallet_membership::WeightInfo<Runtime>;
711
712
}

Gavin Wood's avatar
Gavin Wood committed
713
714
parameter_types! {
	pub const ProposalBond: Permill = Permill::from_percent(5);
715
	pub const ProposalBondMinimum: Balance = 2000 * CENTS;
716
	pub const SpendPeriod: BlockNumber = 6 * DAYS;
717
	pub const Burn: Permill = Permill::from_perthousand(2);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
718
	pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry");
Gavin Wood's avatar
Gavin Wood committed
719
720
721

	pub const TipCountdown: BlockNumber = 1 * DAYS;
	pub const TipFindersFee: Percent = Percent::from_percent(20);
722
	pub const TipReportDepositBase: Balance = 100 * CENTS;
723
	pub const DataDepositPerByte: Balance = 1 * CENTS;
724
	pub const BountyDepositBase: Balance = 100 * CENTS;
725
726
727
728
	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);
729
	pub const BountyValueMinimum: Balance = 200 * CENTS;
730
	pub const MaxApprovals: u32 = 100;
731
	pub const MaxAuthorities: u32 = 100_000;
732
733
734
	pub const MaxKeys: u32 = 10_000;
	pub const MaxPeerInHeartbeats: u32 = 10_000;
	pub const MaxPeerDataEncodingSize: u32 = 1_000;
Gavin Wood's avatar
Gavin Wood committed
735
736
}

Gavin Wood's avatar
Gavin Wood committed
737
738
739
type ApproveOrigin = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
740
	pallet_collective::EnsureProportionAtLeast<_3, _5, AccountId, CouncilCollective>,
Gavin Wood's avatar
Gavin Wood committed
741
742
>;

743
impl pallet_treasury::Config for Runtime {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
744
	type PalletId = TreasuryPalletId;
Gavin Wood's avatar
Gavin Wood committed
745
	type Currency = Balances;
Gavin Wood's avatar
Gavin Wood committed
746
747
	type ApproveOrigin = ApproveOrigin;
	type RejectOrigin = MoreThanHalfCouncil;
748
	type Event = Event;
749
	type OnSlash = Treasury;
Gavin Wood's avatar
Gavin Wood committed
750
751
752
753
	type ProposalBond = ProposalBond;
	type ProposalBondMinimum = ProposalBondMinimum;
	type SpendPeriod = SpendPeriod;
	type Burn = Burn;
754
	type BurnDestination = Society;
755
	type MaxApprovals = MaxApprovals;
756
	type WeightInfo = weights::pallet_treasury::WeightInfo<Runtime>;
757
	type SpendFunds = Bounties;
758
759
760
}

impl pallet_bounties::Config for Runtime {
761
762
763
764
765
	type BountyDepositBase = BountyDepositBase;
	type BountyDepositPayoutDelay = BountyDepositPayoutDelay;
	type BountyUpdatePeriod = BountyUpdatePeriod;
	type BountyCuratorDeposit = BountyCuratorDeposit;
	type BountyValueMinimum = BountyValueMinimum;
766
	type DataDepositPerByte = DataDepositPerByte;
767
	type Event = Event;
768
769
770
771
772
773
	type MaximumReasonLength = MaximumReasonLength;
	type WeightInfo = weights::pallet_bounties::WeightInfo<Runtime>;
}

impl pallet_tips::Config for Runtime {
	type MaximumReasonLength = MaximumReasonLength;
774
	type DataDepositPerByte = DataDepositPerByte;
775
	type Tippers = PhragmenElection;
776
777
778
	type TipCountdown = TipCountdown;
	type TipFindersFee = TipFindersFee;
	type TipReportDepositBase = TipReportDepositBase;
779
	type Event = Event;
780
	type WeightInfo = weights::pallet_tips::WeightInfo<Runtime>;
781
}
782

783
impl pallet_offences::Config for Runtime {
784
	type Event = Event;
785
	type IdentificationTuple = pallet_session::historical::IdentificationTuple<Self>