lib.rs 69 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
53
54
	traits::{
		Contains, Everything, InstanceFilter, KeyOwnerProofSystem, LockIdentifier, OnRuntimeUpgrade,
	},
55
56
	weights::Weight,
	PalletId, RuntimeDebug,
57
};
58
59
60
61
62
63
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};
64
use sp_arithmetic::Perquintill;
65
use sp_core::OpaqueMetadata;
66
use sp_runtime::{
67
	create_runtime_str, generic, impl_opaque_keys,
68
	traits::{
69
70
		AccountIdLookup, BlakeTwo256, Block as BlockT, ConvertInto, Extrinsic as ExtrinsicT,
		OpaqueKeys, SaturatedConversion, Verify,
71
	},
72
73
	transaction_validity::{TransactionPriority, TransactionSource, TransactionValidity},
	ApplyExtrinsicResult, KeyTypeId, Perbill, Percent, Permill,
Gav Wood's avatar
Gav Wood committed
74
};
75
use sp_staking::SessionIndex;
76
#[cfg(any(feature = "std", test))]
77
use sp_version::NativeVersion;
78
use sp_version::RuntimeVersion;
79
use static_assertions::const_assert;
Gavin Wood's avatar
Gavin Wood committed
80
use xcm::latest::prelude::*;
81
82
83
84
85
86
87
88
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;
89

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

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

102
103
104
// Weights used in the runtime.
mod weights;

105
106
107
#[cfg(test)]
mod tests;

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

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

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

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

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

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

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

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

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

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

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

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

214
impl pallet_babe::Config for Runtime {
215
216
	type EpochDuration = EpochDuration;
	type ExpectedBlockTime = ExpectedBlockTime;
217
218

	// session module is the trigger
219
	type EpochChangeTrigger = pallet_babe::ExternalTrigger;
220

221
222
	type DisabledValidators = Session;

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

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

233
234
	type KeyOwnerProofSystem = Historical;

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

	type WeightInfo = ();
239
240
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	// miner configs
	pub const MinerMaxIterations: u32 = 10;
362
	pub OffchainRepeat: BlockNumber = 5;
363
364
}

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

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

407
408
409
410
411
412
413
414
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;
415
	use sp_arithmetic::traits::Saturating;
416
417
418
419
420
421
422
423
424

	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.
425
	let ideal_stake = Perquintill::from_percent(75).saturating_sub(auction_proportion);
426
427
428
429

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

	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) {
453
454
455
		// 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();
456
457
458
459
460
461
462
463
		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),
464
			auctioned_slots,
465
466
		)
	}
thiolliere's avatar
thiolliere committed
467
468
}

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

Gavin Wood's avatar
Gavin Wood committed
479
480
481
type SlashCancelOrigin = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
482
	pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>,
Gavin Wood's avatar
Gavin Wood committed
483
484
>;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

753
impl pallet_grandpa::Config for Runtime {
754
	type Event = Event;
755
756
757
758
759
760
761
762
763
764
	type Call = Call;

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

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

765
766
	type KeyOwnerProofSystem = Historical;

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

	type WeightInfo = ();
774
775
}

776
777
/// Submits transaction with the node's public and signature type. Adheres to the signed extension
/// format of the chain.
778
779
impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime
where
780
781
	Call: From<LocalCall>,
{
782
	fn create_transaction<C: frame_system::offchain::AppCrypto<Self::Public, Self::Signature>>(
783
784
785
		call: Call,
		public: <Signature as Verify>::Signer,
		account: AccountId,
786
		nonce: <Runtime as frame_system::Config>::Index,
Fedor Sakharov's avatar