lib.rs 53.9 KB
Newer Older
Shawn Tabrizi's avatar
Shawn Tabrizi committed
1
// Copyright 2017-2020 Parity Technologies (UK) Ltd.
Gav's avatar
Gav committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// This file is part of Polkadot.

// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Polkadot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Polkadot.  If not, see <http://www.gnu.org/licenses/>.

17
//! The Polkadot runtime. This can be compiled with `#[no_std]`, ready for Wasm.
Gav's avatar
Gav committed
18
19

#![cfg_attr(not(feature = "std"), no_std)]
20
// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
21
#![recursion_limit = "256"]
Gav Wood's avatar
Gav Wood committed
22

Albrecht's avatar
Albrecht committed
23
use pallet_transaction_payment::CurrencyAdapter;
24
use runtime_common::{
25
	claims, SlowAdjustingFeeUpdate, CurrencyToVote,
26
	impls::DealWithFees,
27
28
	BlockHashCount, RocksDbWeight, BlockWeights, BlockLength,
	OffchainSolutionWeightLimit, OffchainSolutionLengthLimit,
29
	ParachainSessionKeyPlaceholder, AssignmentSessionKeyPlaceholder,
30
};
Gav Wood's avatar
Gav Wood committed
31

32
use sp_std::prelude::*;
Sergey Pepyakin's avatar
Sergey Pepyakin committed
33
use sp_std::collections::btree_map::BTreeMap;
34
use sp_core::u32_trait::{_1, _2, _3, _4, _5};
35
use parity_scale_codec::{Encode, Decode};
36
use primitives::v1::{
37
38
	AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt,
	CoreState, GroupRotationInfo, Hash, Id, Moment, Nonce, OccupiedCoreAssumption,
39
	PersistedValidationData, Signature, ValidationCode, ValidatorId, ValidatorIndex,
40
	InboundDownwardMessage, InboundHrmpMessage, SessionInfo,
41
42
};
use sp_runtime::{
Shawn Tabrizi's avatar
Shawn Tabrizi committed
43
	create_runtime_str, generic, impl_opaque_keys, ApplyExtrinsicResult,
44
45
46
	KeyTypeId, Percent, Permill, Perbill, curve::PiecewiseLinear,
	transaction_validity::{TransactionValidity, TransactionSource, TransactionPriority},
	traits::{
47
		BlakeTwo256, Block as BlockT, OpaqueKeys, ConvertInto, AccountIdLookup,
48
49
		Extrinsic as ExtrinsicT, SaturatedConversion, Verify,
	},
50
};
51
52
#[cfg(feature = "runtime-benchmarks")]
use sp_runtime::RuntimeString;
53
54
use sp_version::RuntimeVersion;
use pallet_grandpa::{AuthorityId as GrandpaId, fg_primitives};
55
#[cfg(any(feature = "std", test))]
56
use sp_version::NativeVersion;
57
58
use sp_core::OpaqueMetadata;
use sp_staking::SessionIndex;
59
use frame_support::{
Shawn Tabrizi's avatar
Shawn Tabrizi committed
60
	parameter_types, construct_runtime, RuntimeDebug, PalletId,
61
	traits::{KeyOwnerProofSystem, LockIdentifier, Filter, MaxEncodedLen},
62
	weights::Weight,
Gavin Wood's avatar
Gavin Wood committed
63
};
64
use frame_system::{EnsureRoot, EnsureOneOf};
65
use pallet_im_online::sr25519::AuthorityId as ImOnlineId;
Gavin Wood's avatar
Gavin Wood committed
66
use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId;
67
use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo};
68
use pallet_session::historical as session_historical;
69
use static_assertions::const_assert;
70
71
use beefy_primitives::ecdsa::AuthorityId as BeefyId;
use pallet_mmr_primitives as mmr;
72

Gav Wood's avatar
Gav Wood committed
73
#[cfg(feature = "std")]
74
pub use pallet_staking::StakerStatus;
75
#[cfg(any(feature = "std", test))]
76
pub use sp_runtime::BuildStorage;
77
78
pub use pallet_timestamp::Call as TimestampCall;
pub use pallet_balances::Call as BalancesCall;
79
80
81

/// Constant values used within the runtime.
pub mod constants;
82
use constants::{time::*, currency::*, fee::*};
83
use frame_support::traits::InstanceFilter;
84

85
86
87
// Weights used in the runtime.
mod weights;

88
89
90
91
// Make the WASM binary available.
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));

92
// Polkadot version identifier;
93
/// Runtime version (Polkadot).
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
94
pub const VERSION: RuntimeVersion = RuntimeVersion {
95
96
	spec_name: create_runtime_str!("polkadot"),
	impl_name: create_runtime_str!("parity-polkadot"),
Gavin Wood's avatar
Gavin Wood committed
97
	authoring_version: 0,
Martin Pugh's avatar
Martin Pugh committed
98
	spec_version: 9040,
99
	impl_version: 0,
100
	#[cfg(not(feature = "disable-runtime-api"))]
101
	apis: RUNTIME_API_VERSIONS,
102
	#[cfg(feature = "disable-runtime-api")]
103
	apis: version::create_apis_vec![[]],
104
	transaction_version: 7,
105
};
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
106

107
108
109
110
111
112
113
/// The BABE epoch configuration at genesis.
pub const BABE_GENESIS_EPOCH_CONFIG: babe_primitives::BabeEpochConfiguration =
	babe_primitives::BabeEpochConfiguration {
		c: PRIMARY_PROBABILITY,
		allowed_slots: babe_primitives::AllowedSlots::PrimaryAndSecondaryVRFSlots
	};

114
115
116
117
118
119
120
121
122
/// Native version.
#[cfg(any(feature = "std", test))]
pub fn native_version() -> NativeVersion {
	NativeVersion {
		runtime_version: VERSION,
		can_author_with: Default::default(),
	}
}

123
124
pub struct BaseFilter;
impl Filter<Call> for BaseFilter {
Gavin Wood's avatar
Gavin Wood committed
125
	fn filter(call: &Call) -> bool {
126
		match call {
Gavin Wood's avatar
Gavin Wood committed
127
			// These modules are all allowed to be called by transactions:
128
			Call::Democracy(_) | Call::Council(_) | Call::TechnicalCommittee(_) |
129
			Call::TechnicalMembership(_) | Call::Treasury(_) | Call::PhragmenElection(_) |
Gavin Wood's avatar
Gavin Wood committed
130
			Call::System(_) | Call::Scheduler(_) | Call::Indices(_) |
Gavin Wood's avatar
Gavin Wood committed
131
			Call::Babe(_) | Call::Timestamp(_) | Call::Balances(_) |
Gavin Wood's avatar
Gavin Wood committed
132
			Call::Authorship(_) | Call::Staking(_) | Call::Offences(_) |
133
			Call::Session(_) | Call::Grandpa(_) | Call::ImOnline(_) |
Gavin Wood's avatar
Gavin Wood committed
134
			Call::AuthorityDiscovery(_) |
Gavin Wood's avatar
Gavin Wood committed
135
			Call::Utility(_) | Call::Claims(_) | Call::Vesting(_) |
136
			Call::Identity(_) | Call::Proxy(_) | Call::Multisig(_) |
137
			Call::Bounties(_) | Call::Tips(_) | Call::ElectionProviderMultiPhase(_)
138
			=> true,
139
140
141
142
		}
	}
}

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

149
parameter_types! {
150
	pub const Version: RuntimeVersion = VERSION;
151
	pub const SS58Prefix: u8 = 0;
152
153
}

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

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

186
impl pallet_scheduler::Config for Runtime {
Gavin Wood's avatar
Gavin Wood committed
187
188
	type Event = Event;
	type Origin = Origin;
189
	type PalletsOrigin = OriginCaller;
Gavin Wood's avatar
Gavin Wood committed
190
	type Call = Call;
191
	type MaximumWeight = MaximumSchedulerWeight;
192
	type ScheduleOrigin = EnsureRoot<AccountId>;
193
	type MaxScheduledPerBlock = MaxScheduledPerBlock;
194
	type WeightInfo = weights::pallet_scheduler::WeightInfo<Runtime>;
Gavin Wood's avatar
Gavin Wood committed
195
196
}

197
parameter_types! {
198
	pub const EpochDuration: u64 = EPOCH_DURATION_IN_SLOTS as u64;
199
	pub const ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK;
200
201
	pub const ReportLongevity: u64 =
		BondingDuration::get() as u64 * SessionsPerEra::get() as u64 * EpochDuration::get();
202
203
}

204
impl pallet_babe::Config for Runtime {
205
206
	type EpochDuration = EpochDuration;
	type ExpectedBlockTime = ExpectedBlockTime;
207
208

	// session module is the trigger
209
	type EpochChangeTrigger = pallet_babe::ExternalTrigger;
210
211
212
213
214

	type KeyOwnerProofSystem = Historical;

	type KeyOwnerProof = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
		KeyTypeId,
215
		pallet_babe::AuthorityId,
216
217
218
219
	)>>::Proof;

	type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
		KeyTypeId,
220
		pallet_babe::AuthorityId,
221
222
223
	)>>::IdentificationTuple;

	type HandleEquivocation =
224
		pallet_babe::EquivocationHandler<Self::KeyOwnerIdentification, Offences, ReportLongevity>;
225
226

	type WeightInfo = ();
227
228
}

Gavin Wood's avatar
Gavin Wood committed
229
parameter_types! {
Gavin Wood's avatar
Gavin Wood committed
230
	pub const IndexDeposit: Balance = 10 * DOLLARS;
Gavin Wood's avatar
Gavin Wood committed
231
232
}

233
impl pallet_indices::Config for Runtime {
Gav Wood's avatar
Gav Wood committed
234
	type AccountIndex = AccountIndex;
235
236
	type Currency = Balances;
	type Deposit = IndexDeposit;
Gav Wood's avatar
Gav Wood committed
237
	type Event = Event;
238
	type WeightInfo = weights::pallet_indices::WeightInfo<Runtime>;
Gav Wood's avatar
Gav Wood committed
239
240
}

Gavin Wood's avatar
Gavin Wood committed
241
parameter_types! {
242
	pub const ExistentialDeposit: Balance = 100 * CENTS;
243
	pub const MaxLocks: u32 = 50;
Gavin Wood's avatar
Gavin Wood committed
244
245
}

246
impl pallet_balances::Config for Runtime {
Gav's avatar
Gav committed
247
	type Balance = Balance;
248
	type DustRemoval = ();
Gavin Wood's avatar
Gavin Wood committed
249
	type Event = Event;
Gavin Wood's avatar
Gavin Wood committed
250
	type ExistentialDeposit = ExistentialDeposit;
251
	type AccountStore = System;
252
	type MaxLocks = MaxLocks;
253
	type WeightInfo = weights::pallet_balances::WeightInfo<Runtime>;
254
255
256
257
258
259
}

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

260
impl pallet_transaction_payment::Config for Runtime {
Albrecht's avatar
Albrecht committed
261
	type OnChargeTransaction = CurrencyAdapter<Balances, DealWithFees<Runtime>>;
Gavin Wood's avatar
Gavin Wood committed
262
	type TransactionByteFee = TransactionByteFee;
263
	type WeightToFee = WeightToFee;
264
	type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
Gav's avatar
Gav committed
265
266
}

267
parameter_types! {
268
	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;
269
}
270
impl pallet_timestamp::Config for Runtime {
271
	type Moment = u64;
272
	type OnTimestampSet = Babe;
273
	type MinimumPeriod = MinimumPeriod;
274
	type WeightInfo = weights::pallet_timestamp::WeightInfo<Runtime>;
275
276
}

Gavin Wood's avatar
Gavin Wood committed
277
parameter_types! {
278
	pub const UncleGenerations: u32 = 0;
Gavin Wood's avatar
Gavin Wood committed
279
280
281
}

// TODO: substrate#2986 implement this properly
282
impl pallet_authorship::Config for Runtime {
283
	type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Babe>;
Gavin Wood's avatar
Gavin Wood committed
284
285
	type UncleGenerations = UncleGenerations;
	type FilterUncle = ();
Gavin Wood's avatar
Gavin Wood committed
286
	type EventHandler = (Staking, ImOnline);
Gavin Wood's avatar
Gavin Wood committed
287
288
}

289
impl_opaque_keys! {
290
	pub struct SessionKeys {
Gavin Wood's avatar
Gavin Wood committed
291
292
293
		pub grandpa: Grandpa,
		pub babe: Babe,
		pub im_online: ImOnline,
294
295
		pub para_validator: ParachainSessionKeyPlaceholder<Runtime>,
		pub para_assignment: AssignmentSessionKeyPlaceholder<Runtime>,
Gavin Wood's avatar
Gavin Wood committed
296
		pub authority_discovery: AuthorityDiscovery,
297
	}
298
299
}

thiolliere's avatar
thiolliere committed
300
301
302
303
parameter_types! {
	pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(17);
}

304
impl pallet_session::Config for Runtime {
Gav's avatar
Gav committed
305
	type Event = Event;
306
	type ValidatorId = AccountId;
307
	type ValidatorIdOf = pallet_staking::StashOf<Self>;
Gavin Wood's avatar
Gavin Wood committed
308
	type ShouldEndSession = Babe;
309
	type NextSessionRotation = Babe;
310
	type SessionManager = pallet_session::historical::NoteHistoricalRoot<Self, Staking>;
Gavin Wood's avatar
Gavin Wood committed
311
312
	type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
	type Keys = SessionKeys;
thiolliere's avatar
thiolliere committed
313
	type DisabledValidatorsThreshold = DisabledValidatorsThreshold;
314
	type WeightInfo = weights::pallet_session::WeightInfo<Runtime>;
315
316
}

317
impl pallet_session::historical::Config for Runtime {
318
319
	type FullIdentification = pallet_staking::Exposure<AccountId, Balance>;
	type FullIdentificationOf = pallet_staking::ExposureOf<Runtime>;
320
321
}

322
323
324
parameter_types! {
	// no signed phase for now, just unsigned.
	pub const SignedPhase: u32 = 0;
325
	pub const UnsignedPhase: u32 = EPOCH_DURATION_IN_SLOTS / 4;
326

327
	// fallback: run election on-chain.
328
	pub const Fallback: pallet_election_provider_multi_phase::FallbackStrategy =
329
330
		pallet_election_provider_multi_phase::FallbackStrategy::OnChain;
	pub SolutionImprovementThreshold: Perbill = Perbill::from_rational(5u32, 10_000);
331
332
333

	// miner configs
	pub const MinerMaxIterations: u32 = 10;
334
	pub OffchainRepeat: BlockNumber = 5;
335
336
}

337
338
sp_npos_elections::generate_solution_type!(
	#[compact]
339
340
341
342
343
	pub struct NposCompactSolution16::<
		VoterIndex = u32,
		TargetIndex = u16,
		Accuracy = sp_runtime::PerU16,
	>(16)
344
345
);

346
347
348
349
350
impl pallet_election_provider_multi_phase::Config for Runtime {
	type Event = Event;
	type Currency = Balances;
	type SignedPhase = SignedPhase;
	type UnsignedPhase = UnsignedPhase;
351
	type SolutionImprovementThreshold = SolutionImprovementThreshold;
352
	type MinerMaxIterations = MinerMaxIterations;
353
	type MinerMaxWeight = OffchainSolutionWeightLimit; // For now use the one from staking.
354
	type MinerMaxLength = OffchainSolutionLengthLimit;
355
	type OffchainRepeat = OffchainRepeat;
356
	type MinerTxPriority = NposSolutionPriority;
357
358
	type DataProvider = Staking;
	type OnChainAccuracy = Perbill;
359
	type CompactSolution = NposCompactSolution16;
360
361
	type Fallback = Fallback;
	type BenchmarkingConfig = ();
362
363
364
365
366
	type ForceOrigin = EnsureOneOf<
		AccountId,
		EnsureRoot<AccountId>,
		pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, CouncilCollective>,
	>;
367
	type WeightInfo = weights::pallet_election_provider_multi_phase::WeightInfo<Runtime>;
368
369
}

370
371
372
// TODO #6469: This shouldn't be static, but a lazily cached value, not built unless needed, and
// re-built in case input parameters have changed. The `ideal_stake` should be determined by the
// amount of parachain slots being bid on: this should be around `(75 - 25.min(slots / 4))%`.
373
pallet_staking_reward_curve::build! {
thiolliere's avatar
thiolliere committed
374
375
376
	const REWARD_CURVE: PiecewiseLinear<'static> = curve!(
		min_inflation: 0_025_000,
		max_inflation: 0_100_000,
377
378
379
		// 3:2:1 staked : parachains : float.
		// while there's no parachains, then this is 75% staked : 25% float.
		ideal_stake: 0_750_000,
thiolliere's avatar
thiolliere committed
380
381
382
383
384
385
		falloff: 0_050_000,
		max_piece_count: 40,
		test_precision: 0_005_000,
	);
}

386
parameter_types! {
Gavin Wood's avatar
Gavin Wood committed
387
	// Six sessions in an era (24 hours).
388
	pub const SessionsPerEra: SessionIndex = 6;
Gavin Wood's avatar
Gavin Wood committed
389
	// 28 eras for unbonding (28 days).
390
391
	pub const BondingDuration: pallet_staking::EraIndex = 28;
	pub const SlashDeferDuration: pallet_staking::EraIndex = 27;
thiolliere's avatar
thiolliere committed
392
	pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE;
393
	pub const MaxNominatorRewardedPerValidator: u32 = 256;
394
}
395

Gavin Wood's avatar
Gavin Wood committed
396
397
398
type SlashCancelOrigin = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
399
	pallet_collective::EnsureProportionAtLeast<_3, _4, AccountId, CouncilCollective>
Gavin Wood's avatar
Gavin Wood committed
400
401
>;

402
impl pallet_staking::Config for Runtime {
403
	const MAX_NOMINATIONS: u32 = <NposCompactSolution16 as sp_npos_elections::CompactSolution>::LIMIT as u32;
Gavin Wood's avatar
Gavin Wood committed
404
	type Currency = Balances;
405
	type UnixTime = Timestamp;
406
	type CurrencyToVote = CurrencyToVote;
Gavin Wood's avatar
Gavin Wood committed
407
	type RewardRemainder = Treasury;
Gav's avatar
Gav committed
408
	type Event = Event;
409
	type Slash = Treasury;
410
	type Reward = ();
411
412
	type SessionsPerEra = SessionsPerEra;
	type BondingDuration = BondingDuration;
Gavin Wood's avatar
Gavin Wood committed
413
414
	type SlashDeferDuration = SlashDeferDuration;
	// A super-majority of the council can cancel the slash.
Gavin Wood's avatar
Gavin Wood committed
415
	type SlashCancelOrigin = SlashCancelOrigin;
416
	type SessionInterface = Self;
Kian Paimani's avatar
Kian Paimani committed
417
	type EraPayout = pallet_staking::ConvertCurve<RewardCurve>;
Gavin Wood's avatar
Gavin Wood committed
418
	type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator;
419
	type NextNewSession = Session;
420
	type ElectionProvider = ElectionProviderMultiPhase;
421
	type WeightInfo = weights::pallet_staking::WeightInfo<Runtime>;
422
423
}

Gavin Wood's avatar
Gavin Wood committed
424
425
426
427
428
429
430
431
432
433
parameter_types! {
	// Minimum 4 CENTS/byte
	pub const BasicDeposit: Balance = deposit(1, 258);
	pub const FieldDeposit: Balance = deposit(0, 66);
	pub const SubAccountDeposit: Balance = deposit(1, 53);
	pub const MaxSubAccounts: u32 = 100;
	pub const MaxAdditionalFields: u32 = 100;
	pub const MaxRegistrars: u32 = 20;
}

434
impl pallet_identity::Config for Runtime {
Gavin Wood's avatar
Gavin Wood committed
435
436
437
438
439
440
441
442
443
	type Event = Event;
	type Currency = Balances;
	type BasicDeposit = BasicDeposit;
	type FieldDeposit = FieldDeposit;
	type SubAccountDeposit = SubAccountDeposit;
	type MaxSubAccounts = MaxSubAccounts;
	type MaxAdditionalFields = MaxAdditionalFields;
	type MaxRegistrars = MaxRegistrars;
	type Slashed = Treasury;
Gavin Wood's avatar
Gavin Wood committed
444
445
	type ForceOrigin = MoreThanHalfCouncil;
	type RegistrarOrigin = MoreThanHalfCouncil;
446
	type WeightInfo = weights::pallet_identity::WeightInfo<Runtime>;
Gavin Wood's avatar
Gavin Wood committed
447
448
}

449
parameter_types! {
450
451
	pub const LaunchPeriod: BlockNumber = 28 * DAYS;
	pub const VotingPeriod: BlockNumber = 28 * DAYS;
452
	pub const FastTrackVotingPeriod: BlockNumber = 3 * HOURS;
453
	pub const MinimumDeposit: Balance = 100 * DOLLARS;
Gav Wood's avatar
Gav Wood committed
454
	pub const EnactmentPeriod: BlockNumber = 28 * DAYS;
455
	pub const CooloffPeriod: BlockNumber = 7 * DAYS;
Gavin Wood's avatar
Gavin Wood committed
456
457
	// One cent: $10,000 / MB
	pub const PreimageByteDeposit: Balance = 1 * CENTS;
Gavin Wood's avatar
Gavin Wood committed
458
	pub const InstantAllowed: bool = true;
459
	pub const MaxVotes: u32 = 100;
460
	pub const MaxProposals: u32 = 100;
461
462
}

463
impl pallet_democracy::Config for Runtime {
464
465
	type Proposal = Call;
	type Event = Event;
466
	type Currency = Balances;
467
468
469
470
	type EnactmentPeriod = EnactmentPeriod;
	type LaunchPeriod = LaunchPeriod;
	type VotingPeriod = VotingPeriod;
	type MinimumDeposit = MinimumDeposit;
471
	/// A straight majority of the council can decide what their next motion is.
472
473
474
	type ExternalOrigin = frame_system::EnsureOneOf<AccountId,
		pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>,
		frame_system::EnsureRoot<AccountId>,
Gavin Wood's avatar
Gavin Wood committed
475
	>;
476
	/// A 60% super-majority can have the next scheduled referendum be a straight majority-carries vote.
477
478
479
	type ExternalMajorityOrigin = frame_system::EnsureOneOf<AccountId,
		pallet_collective::EnsureProportionAtLeast<_3, _5, AccountId, CouncilCollective>,
		frame_system::EnsureRoot<AccountId>,
Gavin Wood's avatar
Gavin Wood committed
480
	>;
481
482
	/// A unanimous council can have the next scheduled referendum be a straight default-carries
	/// (NTB) vote.
483
484
485
	type ExternalDefaultOrigin = frame_system::EnsureOneOf<AccountId,
		pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, CouncilCollective>,
		frame_system::EnsureRoot<AccountId>,
Gavin Wood's avatar
Gavin Wood committed
486
	>;
487
488
	/// Two thirds of the technical committee can have an ExternalMajority/ExternalDefault vote
	/// be tabled immediately and with a shorter voting/enactment period.
489
490
491
	type FastTrackOrigin = frame_system::EnsureOneOf<AccountId,
		pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, TechnicalCollective>,
		frame_system::EnsureRoot<AccountId>,
Gavin Wood's avatar
Gavin Wood committed
492
	>;
493
494
495
	type InstantOrigin = frame_system::EnsureOneOf<AccountId,
		pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, TechnicalCollective>,
		frame_system::EnsureRoot<AccountId>,
Gavin Wood's avatar
Gavin Wood committed
496
	>;
497
498
	type InstantAllowed = InstantAllowed;
	type FastTrackVotingPeriod = FastTrackVotingPeriod;
499
	// To cancel a proposal which has been passed, 2/3 of the council must agree to it.
500
	type CancellationOrigin = EnsureOneOf<AccountId,
501
		pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, CouncilCollective>,
502
503
504
505
506
507
508
		EnsureRoot<AccountId>,
	>;
	// To cancel a proposal before it has been passed, the technical committee must be unanimous or
	// Root must agree.
	type CancelProposalOrigin = EnsureOneOf<AccountId,
		pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, TechnicalCollective>,
		EnsureRoot<AccountId>,
Gavin Wood's avatar
Gavin Wood committed
509
	>;
510
	type BlacklistOrigin = EnsureRoot<AccountId>;
511
512
	// 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.
513
	type VetoOrigin = pallet_collective::EnsureMember<AccountId, TechnicalCollective>;
514
	type CooloffPeriod = CooloffPeriod;
Gavin Wood's avatar
Gavin Wood committed
515
	type PreimageByteDeposit = PreimageByteDeposit;
516
	type OperationalPreimageOrigin = pallet_collective::EnsureMember<AccountId, CouncilCollective>;
Gavin Wood's avatar
Gavin Wood committed
517
	type Slash = Treasury;
Gavin Wood's avatar
Gavin Wood committed
518
	type Scheduler = Scheduler;
519
	type PalletsOrigin = OriginCaller;
520
	type MaxVotes = MaxVotes;
521
522
	type WeightInfo = weights::pallet_democracy::WeightInfo<Runtime>;
	type MaxProposals = MaxProposals;
523
}
524

525
526
parameter_types! {
	pub const CouncilMotionDuration: BlockNumber = 7 * DAYS;
527
	pub const CouncilMaxProposals: u32 = 100;
528
	pub const CouncilMaxMembers: u32 = 100;
529
530
}

531
type CouncilCollective = pallet_collective::Instance1;
532
impl pallet_collective::Config<CouncilCollective> for Runtime {
533
534
535
	type Origin = Origin;
	type Proposal = Call;
	type Event = Event;
536
	type MotionDuration = CouncilMotionDuration;
537
	type MaxProposals = CouncilMaxProposals;
538
	type MaxMembers = CouncilMaxMembers;
Wei Tang's avatar
Wei Tang committed
539
	type DefaultVote = pallet_collective::PrimeDefaultVote;
540
	type WeightInfo = weights::pallet_collective::WeightInfo<Runtime>;
541
542
}

Gavin Wood's avatar
Gavin Wood committed
543
parameter_types! {
544
	pub const CandidacyBond: Balance = 100 * DOLLARS;
Kian Paimani's avatar
Kian Paimani committed
545
546
547
548
	// 1 storage item created, key size is 32 bytes, value size is 16+16.
	pub const VotingBondBase: Balance = deposit(1, 64);
	// additional data per vote is 32 bytes (account id).
	pub const VotingBondFactor: Balance = deposit(0, 32);
Gavin Wood's avatar
Gavin Wood committed
549
550
	/// Weekly council elections; scaling up to monthly eventually.
	pub const TermDuration: BlockNumber = 7 * DAYS;
551
	/// 13 members initially, to be increased to 23 eventually.
552
	pub const DesiredMembers: u32 = 13;
553
	pub const DesiredRunnersUp: u32 = 20;
554
	pub const PhragmenElectionPalletId: LockIdentifier = *b"phrelect";
555
}
556
557
// Make sure that there are no more than `MaxMembers` members elected via phragmen.
const_assert!(DesiredMembers::get() <= CouncilMaxMembers::get());
558

559
impl pallet_elections_phragmen::Config for Runtime {
560
	type Event = Event;
561
	type PalletId = PhragmenElectionPalletId;
562
563
	type Currency = Balances;
	type ChangeMembers = Council;
564
	type InitializeMembers = Council;
565
	type CurrencyToVote = frame_support::traits::U128CurrencyToVote;
Gavin Wood's avatar
Gavin Wood committed
566
	type CandidacyBond = CandidacyBond;
Kian Paimani's avatar
Kian Paimani committed
567
568
	type VotingBondBase = VotingBondBase;
	type VotingBondFactor = VotingBondFactor;
569
570
	type LoserCandidate = Treasury;
	type KickedMember = Treasury;
Gavin Wood's avatar
Gavin Wood committed
571
572
573
	type DesiredMembers = DesiredMembers;
	type DesiredRunnersUp = DesiredRunnersUp;
	type TermDuration = TermDuration;
574
	type WeightInfo = weights::pallet_elections_phragmen::WeightInfo<Runtime>;
575
576
}

577
578
parameter_types! {
	pub const TechnicalMotionDuration: BlockNumber = 7 * DAYS;
579
	pub const TechnicalMaxProposals: u32 = 100;
580
	pub const TechnicalMaxMembers: u32 = 100;
581
582
}

583
type TechnicalCollective = pallet_collective::Instance2;
584
impl pallet_collective::Config<TechnicalCollective> for Runtime {
585
586
587
	type Origin = Origin;
	type Proposal = Call;
	type Event = Event;
588
	type MotionDuration = TechnicalMotionDuration;
589
	type MaxProposals = TechnicalMaxProposals;
590
	type MaxMembers = TechnicalMaxMembers;
Wei Tang's avatar
Wei Tang committed
591
	type DefaultVote = pallet_collective::PrimeDefaultVote;
592
	type WeightInfo = weights::pallet_collective::WeightInfo<Runtime>;
593
594
}

595
impl pallet_membership::Config<pallet_membership::Instance1> for Runtime {
596
	type Event = Event;
Gavin Wood's avatar
Gavin Wood committed
597
598
599
600
601
	type AddOrigin = MoreThanHalfCouncil;
	type RemoveOrigin = MoreThanHalfCouncil;
	type SwapOrigin = MoreThanHalfCouncil;
	type ResetOrigin = MoreThanHalfCouncil;
	type PrimeOrigin = MoreThanHalfCouncil;
602
603
	type MembershipInitialized = TechnicalCommittee;
	type MembershipChanged = TechnicalCommittee;
604
	type MaxMembers = TechnicalMaxMembers;
Kian Paimani's avatar
Kian Paimani committed
605
	type WeightInfo = weights::pallet_membership::WeightInfo<Runtime>;
606
607
}

Gavin Wood's avatar
Gavin Wood committed
608
609
parameter_types! {
	pub const ProposalBond: Permill = Permill::from_percent(5);
610
611
612
	pub const ProposalBondMinimum: Balance = 100 * DOLLARS;
	pub const SpendPeriod: BlockNumber = 24 * DAYS;
	pub const Burn: Permill = Permill::from_percent(1);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
613
	pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry");
Gavin Wood's avatar
Gavin Wood committed
614
615
616
617

	pub const TipCountdown: BlockNumber = 1 * DAYS;
	pub const TipFindersFee: Percent = Percent::from_percent(20);
	pub const TipReportDepositBase: Balance = 1 * DOLLARS;
618
619
620
621
622
623
624
	pub const DataDepositPerByte: Balance = 1 * CENTS;
	pub const BountyDepositBase: Balance = 1 * DOLLARS;
	pub const BountyDepositPayoutDelay: BlockNumber = 8 * DAYS;
	pub const BountyUpdatePeriod: BlockNumber = 90 * DAYS;
	pub const MaximumReasonLength: u32 = 16384;
	pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);
	pub const BountyValueMinimum: Balance = 10 * DOLLARS;
625
	pub const MaxApprovals: u32 = 100;
Gavin Wood's avatar
Gavin Wood committed
626
627
}

Gavin Wood's avatar
Gavin Wood committed
628
629
630
type ApproveOrigin = EnsureOneOf<
	AccountId,
	EnsureRoot<AccountId>,
631
	pallet_collective::EnsureProportionAtLeast<_3, _5, AccountId, CouncilCollective>
Gavin Wood's avatar
Gavin Wood committed
632
633
>;

634
impl pallet_treasury::Config for Runtime {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
635
	type PalletId = TreasuryPalletId;
Gavin Wood's avatar
Gavin Wood committed
636
	type Currency = Balances;
Gavin Wood's avatar
Gavin Wood committed
637
638
	type ApproveOrigin = ApproveOrigin;
	type RejectOrigin = MoreThanHalfCouncil;
639
	type Event = Event;
640
	type OnSlash = Treasury;
Gavin Wood's avatar
Gavin Wood committed
641
642
643
644
	type ProposalBond = ProposalBond;
	type ProposalBondMinimum = ProposalBondMinimum;
	type SpendPeriod = SpendPeriod;
	type Burn = Burn;
645
646
	type BurnDestination = ();
	type SpendFunds = Bounties;
647
	type MaxApprovals = MaxApprovals;
648
649
650
651
652
	type WeightInfo = weights::pallet_treasury::WeightInfo<Runtime>;
}

impl pallet_bounties::Config for Runtime {
	type Event = Event;
653
654
655
656
657
	type BountyDepositBase = BountyDepositBase;
	type BountyDepositPayoutDelay = BountyDepositPayoutDelay;
	type BountyUpdatePeriod = BountyUpdatePeriod;
	type BountyCuratorDeposit = BountyCuratorDeposit;
	type BountyValueMinimum = BountyValueMinimum;
658
659
660
661
662
663
664
665
666
	type DataDepositPerByte = DataDepositPerByte;
	type MaximumReasonLength = MaximumReasonLength;
	type WeightInfo = weights::pallet_bounties::WeightInfo<Runtime>;
}

impl pallet_tips::Config for Runtime {
	type Event = Event;
	type DataDepositPerByte = DataDepositPerByte;
	type MaximumReasonLength = MaximumReasonLength;
667
	type Tippers = PhragmenElection;
668
669
670
671
	type TipCountdown = TipCountdown;
	type TipFindersFee = TipFindersFee;
	type TipReportDepositBase = TipReportDepositBase;
	type WeightInfo = weights::pallet_tips::WeightInfo<Runtime>;
672
}
673

674
impl pallet_offences::Config for Runtime {
675
	type Event = Event;
676
	type IdentificationTuple = pallet_session::historical::IdentificationTuple<Self>;
677
678
679
	type OnOffenceHandler = Staking;
}

680
impl pallet_authority_discovery::Config for Runtime {}
Gavin Wood's avatar
Gavin Wood committed
681

682
parameter_types! {
683
	pub NposSolutionPriority: TransactionPriority =
684
		Perbill::from_percent(90) * TransactionPriority::max_value();
685
686
687
	pub const ImOnlineUnsignedPriority: TransactionPriority = TransactionPriority::max_value();
}

688
impl pallet_im_online::Config for Runtime {
thiolliere's avatar
thiolliere committed
689
	type AuthorityId = ImOnlineId;
690
	type Event = Event;
691
	type ValidatorSet = Historical;
692
	type NextSessionRotation = Babe;
Gavin Wood's avatar
Gavin Wood committed
693
	type ReportUnresponsiveness = Offences;
694
	type UnsignedPriority = ImOnlineUnsignedPriority;
695
	type WeightInfo = weights::pallet_im_online::WeightInfo<Runtime>;
696
697
}

698
impl pallet_grandpa::Config for Runtime {
699
	type Event = Event;
700
701
702
	type Call = Call;

	type KeyOwnerProof =
Gavin Wood's avatar
Gavin Wood committed
703
	<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;
704
705
706
707
708
709

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

Gavin Wood's avatar
Gavin Wood committed
710
711
	type KeyOwnerProofSystem = Historical;

712
713
	type HandleEquivocation =
		pallet_grandpa::EquivocationHandler<Self::KeyOwnerIdentification, Offences, ReportLongevity>;
714
715

	type WeightInfo = ();
716
717
}

718
719
/// Submits a transaction with the node's public and signature type. Adheres to the signed extension
/// format of the chain.
720
impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime where
721
722
	Call: From<LocalCall>,
{
723
	fn create_transaction<C: frame_system::offchain::AppCrypto<Self::Public, Self::Signature>>(
724
725
726
		call: Call,
		public: <Signature as Verify>::Signer,
		account: AccountId,
727
		nonce: <Runtime as frame_system::Config>::Index,
728
	) -> Option<(Call, <UncheckedExtrinsic as ExtrinsicT>::SignaturePayload)> {
729
		use sp_runtime::traits::StaticLookup;
730
		// take the biggest period possible.
731
732
733
734
735
736
737
		let period = BlockHashCount::get()
			.checked_next_power_of_two()
			.map(|c| c / 2)
			.unwrap_or(2) as u64;

		let current_block = System::block_number()
			.saturated_into::<u64>()
738
739
			// The `System::block_number` is initialized with `n+1`,
			// so the actual block number is `n`.
740
741
742
			.saturating_sub(1);
		let tip = 0;
		let extra: SignedExtra = (
743
744
745
746
747
748
749
			frame_system::CheckSpecVersion::<Runtime>::new(),
			frame_system::CheckTxVersion::<Runtime>::new(),
			frame_system::CheckGenesis::<Runtime>::new(),
			frame_system::CheckMortality::<Runtime>::from(generic::Era::mortal(period, current_block)),
			frame_system::CheckNonce::<Runtime>::from(nonce),
			frame_system::CheckWeight::<Runtime>::new(),
			pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(tip),
750
			claims::PrevalidateAttests::<Runtime>::new(),
751
752
		);
		let raw_payload = SignedPayload::new(call, extra).map_err(|e| {
753
			log::warn!("Unable to create signed payload: {:?}", e);
754
		}).ok()?;
755
756
757
		let signature = raw_payload.using_encoded(|payload| {
			C::sign(payload, public)
		})?;
758
		let (call, extra, _) = raw_payload.deconstruct();
759
760
		let address = <Runtime as frame_system::Config>::Lookup::unlookup(account);
		Some((call, (address, signature, extra)))
761
	}