lib.rs 35.9 KB
Newer Older
ddorgan's avatar
ddorgan committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Copyright 2017-2020 Parity Technologies (UK) Ltd.
// 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/>.

//! The Polkadot runtime. This can be compiled with `#[no_std]`, ready for Wasm.

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

Albrecht's avatar
Albrecht committed
23
use pallet_transaction_payment::CurrencyAdapter;
ddorgan's avatar
ddorgan committed
24
use sp_std::prelude::*;
Sergey Pepyakin's avatar
Sergey Pepyakin committed
25
use sp_std::collections::btree_map::BTreeMap;
26
use parity_scale_codec::{Encode, Decode};
27
use primitives::v1::{
28
29
	AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CommittedCandidateReceipt,
	CoreState, GroupRotationInfo, Hash, Id, Moment, Nonce, OccupiedCoreAssumption,
30
	PersistedValidationData, Signature, ValidationCode, ValidatorId, ValidatorIndex,
31
	InboundDownwardMessage, InboundHrmpMessage, SessionInfo,
ddorgan's avatar
ddorgan committed
32
};
33
use runtime_common::{
34
35
	SlowAdjustingFeeUpdate, CurrencyToVote,
	impls::ToAuthor,
36
	BlockHashCount, BlockWeights, BlockLength, RocksDbWeight, OffchainSolutionWeightLimit,
37
	ParachainSessionKeyPlaceholder, AssignmentSessionKeyPlaceholder,
ddorgan's avatar
ddorgan committed
38
39
40
};
use sp_runtime::{
	create_runtime_str, generic, impl_opaque_keys,
41
	ApplyExtrinsicResult, KeyTypeId, Perbill, curve::PiecewiseLinear,
Gavin Wood's avatar
Gavin Wood committed
42
	transaction_validity::{TransactionValidity, TransactionSource, TransactionPriority},
ddorgan's avatar
ddorgan committed
43
	traits::{
44
		BlakeTwo256, Block as BlockT, OpaqueKeys, ConvertInto, AccountIdLookup,
Gavin Wood's avatar
Gavin Wood committed
45
		Extrinsic as ExtrinsicT, SaturatedConversion, Verify,
ddorgan's avatar
ddorgan committed
46
47
48
49
	},
};
#[cfg(feature = "runtime-benchmarks")]
use sp_runtime::RuntimeString;
50
51
use sp_version::RuntimeVersion;
use pallet_grandpa::{AuthorityId as GrandpaId, fg_primitives};
ddorgan's avatar
ddorgan committed
52
#[cfg(any(feature = "std", test))]
53
use sp_version::NativeVersion;
ddorgan's avatar
ddorgan committed
54
55
use sp_core::OpaqueMetadata;
use sp_staking::SessionIndex;
56
use frame_support::{
57
	parameter_types, construct_runtime, debug, RuntimeDebug,
58
	traits::{KeyOwnerProofSystem, Randomness, Filter, InstanceFilter},
59
	weights::Weight,
60
};
61
use pallet_im_online::sr25519::AuthorityId as ImOnlineId;
ddorgan's avatar
ddorgan committed
62
use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId;
63
use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo};
64
use pallet_session::historical as session_historical;
65
use frame_system::{EnsureRoot};
ddorgan's avatar
ddorgan committed
66
67

#[cfg(feature = "std")]
68
pub use pallet_staking::StakerStatus;
ddorgan's avatar
ddorgan committed
69
70
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;
71
72
pub use pallet_timestamp::Call as TimestampCall;
pub use pallet_balances::Call as BalancesCall;
ddorgan's avatar
ddorgan committed
73
74
75
76
77

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

78
79
80
// Weights used in the runtime
mod weights;

ddorgan's avatar
ddorgan committed
81
82
83
84
// Make the WASM binary available.
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));

85
/// Runtime version (Westend).
ddorgan's avatar
ddorgan committed
86
87
88
89
pub const VERSION: RuntimeVersion = RuntimeVersion {
	spec_name: create_runtime_str!("westend"),
	impl_name: create_runtime_str!("parity-westend"),
	authoring_version: 2,
90
	spec_version: 49,
91
	impl_version: 0,
92
	#[cfg(not(feature = "disable-runtime-api"))]
ddorgan's avatar
ddorgan committed
93
	apis: RUNTIME_API_VERSIONS,
94
	#[cfg(feature = "disable-runtime-api")]
95
	apis: version::create_apis_vec![[]],
96
	transaction_version: 4,
ddorgan's avatar
ddorgan committed
97
98
99
100
101
102
103
104
105
106
107
};

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

108
/// Accept all transactions.
109
110
pub struct BaseFilter;
impl Filter<Call> for BaseFilter {
111
112
	fn filter(_: &Call) -> bool {
		true
ddorgan's avatar
ddorgan committed
113
114
115
116
117
	}
}

parameter_types! {
	pub const Version: RuntimeVersion = VERSION;
118
	pub const SS58Prefix: u8 = 42;
ddorgan's avatar
ddorgan committed
119
120
}

121
impl frame_system::Config for Runtime {
122
	type BaseCallFilter = BaseFilter;
123
124
	type BlockWeights = BlockWeights;
	type BlockLength = BlockLength;
ddorgan's avatar
ddorgan committed
125
126
127
128
129
130
131
	type Origin = Origin;
	type Call = Call;
	type Index = Nonce;
	type BlockNumber = BlockNumber;
	type Hash = Hash;
	type Hashing = BlakeTwo256;
	type AccountId = AccountId;
132
	type Lookup = AccountIdLookup<AccountId, ()>;
ddorgan's avatar
ddorgan committed
133
134
135
	type Header = generic::Header<BlockNumber, BlakeTwo256>;
	type Event = Event;
	type BlockHashCount = BlockHashCount;
136
	type DbWeight = RocksDbWeight;
ddorgan's avatar
ddorgan committed
137
	type Version = Version;
138
	type PalletInfo = PalletInfo;
139
	type AccountData = pallet_balances::AccountData<Balance>;
ddorgan's avatar
ddorgan committed
140
141
	type OnNewAccount = ();
	type OnKilledAccount = ();
142
	type SystemWeightInfo = weights::frame_system::WeightInfo<Runtime>;
143
	type SS58Prefix = SS58Prefix;
ddorgan's avatar
ddorgan committed
144
145
}

146
parameter_types! {
147
148
	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) *
		BlockWeights::get().max_block;
149
150
151
	pub const MaxScheduledPerBlock: u32 = 50;
}

152
impl pallet_scheduler::Config for Runtime {
ddorgan's avatar
ddorgan committed
153
154
	type Event = Event;
	type Origin = Origin;
155
	type PalletsOrigin = OriginCaller;
ddorgan's avatar
ddorgan committed
156
	type Call = Call;
157
	type MaximumWeight = MaximumSchedulerWeight;
158
	type ScheduleOrigin = EnsureRoot<AccountId>;
159
	type MaxScheduledPerBlock = MaxScheduledPerBlock;
160
	type WeightInfo = weights::pallet_scheduler::WeightInfo<Runtime>;
ddorgan's avatar
ddorgan committed
161
162
163
164
165
}

parameter_types! {
	pub const EpochDuration: u64 = EPOCH_DURATION_IN_BLOCKS as u64;
	pub const ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK;
166
167
	pub const ReportLongevity: u64 =
		BondingDuration::get() as u64 * SessionsPerEra::get() as u64 * EpochDuration::get();
ddorgan's avatar
ddorgan committed
168
169
}

170
impl pallet_babe::Config for Runtime {
ddorgan's avatar
ddorgan committed
171
172
173
174
	type EpochDuration = EpochDuration;
	type ExpectedBlockTime = ExpectedBlockTime;

	// session module is the trigger
175
	type EpochChangeTrigger = pallet_babe::ExternalTrigger;
176
177
178
179
180

	type KeyOwnerProofSystem = Historical;

	type KeyOwnerProof = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
		KeyTypeId,
181
		pallet_babe::AuthorityId,
182
183
184
185
	)>>::Proof;

	type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
		KeyTypeId,
186
		pallet_babe::AuthorityId,
187
188
189
	)>>::IdentificationTuple;

	type HandleEquivocation =
190
		pallet_babe::EquivocationHandler<Self::KeyOwnerIdentification, Offences, ReportLongevity>;
191
192

	type WeightInfo = ();
ddorgan's avatar
ddorgan committed
193
194
195
196
197
198
}

parameter_types! {
	pub const IndexDeposit: Balance = 1 * DOLLARS;
}

199
impl pallet_indices::Config for Runtime {
ddorgan's avatar
ddorgan committed
200
201
202
203
	type AccountIndex = AccountIndex;
	type Currency = Balances;
	type Deposit = IndexDeposit;
	type Event = Event;
204
	type WeightInfo = weights::pallet_indices::WeightInfo<Runtime>;
ddorgan's avatar
ddorgan committed
205
206
207
208
}

parameter_types! {
	pub const ExistentialDeposit: Balance = 1 * CENTS;
209
	pub const MaxLocks: u32 = 50;
ddorgan's avatar
ddorgan committed
210
211
}

212
impl pallet_balances::Config for Runtime {
ddorgan's avatar
ddorgan committed
213
214
215
216
217
	type Balance = Balance;
	type DustRemoval = ();
	type Event = Event;
	type ExistentialDeposit = ExistentialDeposit;
	type AccountStore = System;
218
	type MaxLocks = MaxLocks;
219
	type WeightInfo = weights::pallet_balances::WeightInfo<Runtime>;
ddorgan's avatar
ddorgan committed
220
221
222
223
224
225
}

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

226
impl pallet_transaction_payment::Config for Runtime {
Albrecht's avatar
Albrecht committed
227
	type OnChargeTransaction = CurrencyAdapter<Balances, ToAuthor<Runtime>>;
ddorgan's avatar
ddorgan committed
228
229
	type TransactionByteFee = TransactionByteFee;
	type WeightToFee = WeightToFee;
230
	type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
ddorgan's avatar
ddorgan committed
231
232
233
234
235
}

parameter_types! {
	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;
}
236
impl pallet_timestamp::Config for Runtime {
ddorgan's avatar
ddorgan committed
237
238
239
	type Moment = u64;
	type OnTimestampSet = Babe;
	type MinimumPeriod = MinimumPeriod;
240
	type WeightInfo = weights::pallet_timestamp::WeightInfo<Runtime>;
ddorgan's avatar
ddorgan committed
241
242
243
244
245
246
247
}

parameter_types! {
	pub const UncleGenerations: u32 = 0;
}

// TODO: substrate#2986 implement this properly
248
impl pallet_authorship::Config for Runtime {
249
	type FindAuthor = pallet_session::FindAccountFromAuthorIndex<Self, Babe>;
ddorgan's avatar
ddorgan committed
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
	type UncleGenerations = UncleGenerations;
	type FilterUncle = ();
	type EventHandler = (Staking, ImOnline);
}

parameter_types! {
	pub const Period: BlockNumber = 10 * MINUTES;
	pub const Offset: BlockNumber = 0;
}

impl_opaque_keys! {
	pub struct SessionKeys {
		pub grandpa: Grandpa,
		pub babe: Babe,
		pub im_online: ImOnline,
265
266
		pub para_validator: ParachainSessionKeyPlaceholder<Runtime>,
		pub para_assignment: AssignmentSessionKeyPlaceholder<Runtime>,
ddorgan's avatar
ddorgan committed
267
268
269
270
271
272
273
274
		pub authority_discovery: AuthorityDiscovery,
	}
}

parameter_types! {
	pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(17);
}

275
impl pallet_session::Config for Runtime {
ddorgan's avatar
ddorgan committed
276
277
	type Event = Event;
	type ValidatorId = AccountId;
278
	type ValidatorIdOf = pallet_staking::StashOf<Self>;
ddorgan's avatar
ddorgan committed
279
280
	type ShouldEndSession = Babe;
	type NextSessionRotation = Babe;
281
	type SessionManager = pallet_session::historical::NoteHistoricalRoot<Self, Staking>;
ddorgan's avatar
ddorgan committed
282
283
284
	type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
	type Keys = SessionKeys;
	type DisabledValidatorsThreshold = DisabledValidatorsThreshold;
285
	type WeightInfo = weights::pallet_session::WeightInfo<Runtime>;
ddorgan's avatar
ddorgan committed
286
287
}

288
impl pallet_session::historical::Config for Runtime {
289
290
	type FullIdentification = pallet_staking::Exposure<AccountId, Balance>;
	type FullIdentificationOf = pallet_staking::ExposureOf<Runtime>;
ddorgan's avatar
ddorgan committed
291
292
}

293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
parameter_types! {
	// no signed phase for now, just unsigned.
	pub const SignedPhase: u32 = 0;
	// NOTE: length of unsigned phase is, for now, different than `ElectionLookahead` to make sure
	// that we won't run OCW threads at the same time with staking.
	pub const UnsignedPhase: u32 = ElectionLookahead::get() / 2;

	// fallback: no need to do on-chain phragmen while we re on a dry-run.
	pub const Fallback: pallet_election_provider_multi_phase::FallbackStrategy =
		pallet_election_provider_multi_phase::FallbackStrategy::Nothing;

	pub SolutionImprovementThreshold: Perbill = Perbill::from_rational_approximation(1u32, 10_000);

	// miner configs
	pub const MultiPhaseUnsignedPriority: TransactionPriority = StakingUnsignedPriority::get() - 1u64;
	pub const MinerMaxIterations: u32 = 10;
}

impl pallet_election_provider_multi_phase::Config for Runtime {
	type Event = Event;
	type Currency = Balances;
	type SignedPhase = SignedPhase;
	type UnsignedPhase = UnsignedPhase;
	type SolutionImprovementThreshold = MinSolutionScoreBump;
	type MinerMaxIterations = MinerMaxIterations;
	type MinerMaxWeight = OffchainSolutionWeightLimit; // For now use the one from staking.
	type MinerTxPriority = MultiPhaseUnsignedPriority;
	type DataProvider = Staking;
	type OnChainAccuracy = Perbill;
	type CompactSolution = pallet_staking::CompactAssignments;
	type Fallback = Fallback;
	type WeightInfo = pallet_election_provider_multi_phase::weights::SubstrateWeight<Runtime>;
	type BenchmarkingConfig = ();
}

ddorgan's avatar
ddorgan committed
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
pallet_staking_reward_curve::build! {
	const REWARD_CURVE: PiecewiseLinear<'static> = curve!(
		min_inflation: 0_025_000,
		max_inflation: 0_100_000,
		ideal_stake: 0_500_000,
		falloff: 0_050_000,
		max_piece_count: 40,
		test_precision: 0_005_000,
	);
}

parameter_types! {
	// Six sessions in an era (6 hours).
	pub const SessionsPerEra: SessionIndex = 6;
	// 28 eras for unbonding (7 days).
343
	pub const BondingDuration: pallet_staking::EraIndex = 28;
344
	// 27 eras in which slashes can be cancelled (slightly less than 7 days).
345
	pub const SlashDeferDuration: pallet_staking::EraIndex = 27;
ddorgan's avatar
ddorgan committed
346
347
348
349
	pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE;
	pub const MaxNominatorRewardedPerValidator: u32 = 64;
	// quarter of the last session will be for election.
	pub const ElectionLookahead: BlockNumber = EPOCH_DURATION_IN_BLOCKS / 4;
350
	pub const MaxIterations: u32 = 10;
351
	pub MinSolutionScoreBump: Perbill = Perbill::from_rational_approximation(5u32, 10_000);
ddorgan's avatar
ddorgan committed
352
353
}

354
impl pallet_staking::Config for Runtime {
ddorgan's avatar
ddorgan committed
355
356
	type Currency = Balances;
	type UnixTime = Timestamp;
357
	type CurrencyToVote = CurrencyToVote;
ddorgan's avatar
ddorgan committed
358
359
360
361
362
363
364
365
	type RewardRemainder = ();
	type Event = Event;
	type Slash = ();
	type Reward = ();
	type SessionsPerEra = SessionsPerEra;
	type BondingDuration = BondingDuration;
	type SlashDeferDuration = SlashDeferDuration;
	// A majority of the council can cancel the slash.
366
	type SlashCancelOrigin = EnsureRoot<AccountId>;
ddorgan's avatar
ddorgan committed
367
368
369
370
371
372
373
	type SessionInterface = Self;
	type RewardCurve = RewardCurve;
	type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator;
	type NextNewSession = Session;
	type ElectionLookahead = ElectionLookahead;
	type Call = Call;
	type UnsignedPriority = StakingUnsignedPriority;
374
	type MaxIterations = MaxIterations;
375
	type MinSolutionScoreBump = MinSolutionScoreBump;
376
	type OffchainSolutionWeightLimit = OffchainSolutionWeightLimit;
377
	type ElectionProvider = ElectionProviderMultiPhase;
378
	type WeightInfo = weights::pallet_staking::WeightInfo<Runtime>;
ddorgan's avatar
ddorgan committed
379
380
381
382
383
384
385
386
387
388
389
390
391
392
}

parameter_types! {
	pub const LaunchPeriod: BlockNumber = 7 * DAYS;
	pub const VotingPeriod: BlockNumber = 7 * DAYS;
	pub const FastTrackVotingPeriod: BlockNumber = 3 * HOURS;
	pub const MinimumDeposit: Balance = 1 * DOLLARS;
	pub const EnactmentPeriod: BlockNumber = 8 * DAYS;
	pub const CooloffPeriod: BlockNumber = 7 * DAYS;
	// One cent: $10,000 / MB
	pub const PreimageByteDeposit: Balance = 10 * MILLICENTS;
	pub const InstantAllowed: bool = true;
}

393
parameter_types! {
394
	pub OffencesWeightSoftLimit: Weight = Perbill::from_percent(60) * BlockWeights::get().max_block;
395
396
}

397
impl pallet_offences::Config for Runtime {
ddorgan's avatar
ddorgan committed
398
	type Event = Event;
399
	type IdentificationTuple = pallet_session::historical::IdentificationTuple<Self>;
ddorgan's avatar
ddorgan committed
400
	type OnOffenceHandler = Staking;
401
	type WeightSoftLimit = OffencesWeightSoftLimit;
ddorgan's avatar
ddorgan committed
402
403
}

404
impl pallet_authority_discovery::Config for Runtime {}
ddorgan's avatar
ddorgan committed
405
406
407
408
409
410
411
412
413
414

parameter_types! {
	pub const SessionDuration: BlockNumber = EPOCH_DURATION_IN_BLOCKS as _;
}

parameter_types! {
	pub const StakingUnsignedPriority: TransactionPriority = TransactionPriority::max_value() / 2;
	pub const ImOnlineUnsignedPriority: TransactionPriority = TransactionPriority::max_value();
}

415
impl pallet_im_online::Config for Runtime {
ddorgan's avatar
ddorgan committed
416
417
	type AuthorityId = ImOnlineId;
	type Event = Event;
418
	type ValidatorSet = Historical;
ddorgan's avatar
ddorgan committed
419
420
421
	type ReportUnresponsiveness = Offences;
	type SessionDuration = SessionDuration;
	type UnsignedPriority = StakingUnsignedPriority;
422
	type WeightInfo = weights::pallet_im_online::WeightInfo<Runtime>;
ddorgan's avatar
ddorgan committed
423
424
}

425
impl pallet_grandpa::Config for Runtime {
ddorgan's avatar
ddorgan committed
426
	type Event = Event;
427
428
429
430
431
432
433
434
435
436
437
438
	type Call = Call;

	type KeyOwnerProofSystem = Historical;

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

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

439
440
	type HandleEquivocation =
		pallet_grandpa::EquivocationHandler<Self::KeyOwnerIdentification, Offences, ReportLongevity>;
441
442

	type WeightInfo = ();
ddorgan's avatar
ddorgan committed
443
444
}

445
446
/// Submits a transaction with the node's public and signature type. Adheres to the signed extension
/// format of the chain.
447
impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime where
448
449
	Call: From<LocalCall>,
{
450
	fn create_transaction<C: frame_system::offchain::AppCrypto<Self::Public, Self::Signature>>(
451
452
453
		call: Call,
		public: <Signature as Verify>::Signer,
		account: AccountId,
454
		nonce: <Runtime as frame_system::Config>::Index,
455
	) -> Option<(Call, <UncheckedExtrinsic as ExtrinsicT>::SignaturePayload)> {
456
		use sp_runtime::traits::StaticLookup;
457
		// take the biggest period possible.
458
459
460
461
462
463
464
		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>()
465
466
			// The `System::block_number` is initialized with `n+1`,
			// so the actual block number is `n`.
467
468
469
			.saturating_sub(1);
		let tip = 0;
		let extra: SignedExtra = (
470
471
472
473
474
475
476
			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),
477
478
		);
		let raw_payload = SignedPayload::new(call, extra).map_err(|e| {
479
			debug::warn!("Unable to create signed payload: {:?}", e);
480
		}).ok()?;
481
482
483
		let signature = raw_payload.using_encoded(|payload| {
			C::sign(payload, public)
		})?;
484
		let (call, extra, _) = raw_payload.deconstruct();
485
486
		let address = <Runtime as frame_system::Config>::Lookup::unlookup(account);
		Some((call, (address, signature, extra)))
487
	}
ddorgan's avatar
ddorgan committed
488
489
}

490
impl frame_system::offchain::SigningTypes for Runtime {
491
492
493
494
	type Public = <Signature as Verify>::Signer;
	type Signature = Signature;
}

495
impl<C> frame_system::offchain::SendTransactionTypes<C> for Runtime where
496
497
498
499
500
501
	Call: From<C>,
{
	type OverarchingCall = Call;
	type Extrinsic = UncheckedExtrinsic;
}

ddorgan's avatar
ddorgan committed
502
503
504
505
506
507
508
parameter_types! {
	// Minimum 100 bytes/KSM deposited (1 CENT/byte)
	pub const BasicDeposit: Balance = 10 * DOLLARS;       // 258 bytes on-chain
	pub const FieldDeposit: Balance = 250 * CENTS;        // 66 bytes on-chain
	pub const SubAccountDeposit: Balance = 2 * DOLLARS;   // 53 bytes on-chain
	pub const MaxSubAccounts: u32 = 100;
	pub const MaxAdditionalFields: u32 = 100;
509
	pub const MaxRegistrars: u32 = 20;
ddorgan's avatar
ddorgan committed
510
511
}

512
impl pallet_identity::Config for Runtime {
ddorgan's avatar
ddorgan committed
513
514
515
516
517
518
519
520
	type Event = Event;
	type Currency = Balances;
	type Slashed = ();
	type BasicDeposit = BasicDeposit;
	type FieldDeposit = FieldDeposit;
	type SubAccountDeposit = SubAccountDeposit;
	type MaxSubAccounts = MaxSubAccounts;
	type MaxAdditionalFields = MaxAdditionalFields;
521
	type MaxRegistrars = MaxRegistrars;
522
523
	type RegistrarOrigin = frame_system::EnsureRoot<AccountId>;
	type ForceOrigin = frame_system::EnsureRoot<AccountId>;
524
	type WeightInfo = weights::pallet_identity::WeightInfo<Runtime>;
ddorgan's avatar
ddorgan committed
525
526
}

527
impl pallet_utility::Config for Runtime {
528
529
	type Event = Event;
	type Call = Call;
530
	type WeightInfo = weights::pallet_utility::WeightInfo<Runtime>;
531
532
}

ddorgan's avatar
ddorgan committed
533
parameter_types! {
534
535
	// One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes.
	pub const DepositBase: Balance = deposit(1, 88);
ddorgan's avatar
ddorgan committed
536
	// Additional storage item size of 32 bytes.
537
	pub const DepositFactor: Balance = deposit(0, 32);
ddorgan's avatar
ddorgan committed
538
539
540
	pub const MaxSignatories: u16 = 100;
}

541
impl pallet_multisig::Config for Runtime {
ddorgan's avatar
ddorgan committed
542
543
544
	type Event = Event;
	type Call = Call;
	type Currency = Balances;
545
546
	type DepositBase = DepositBase;
	type DepositFactor = DepositFactor;
ddorgan's avatar
ddorgan committed
547
	type MaxSignatories = MaxSignatories;
548
	type WeightInfo = weights::pallet_multisig::WeightInfo<Runtime>;
ddorgan's avatar
ddorgan committed
549
550
551
552
553
554
555
556
557
}

parameter_types! {
	pub const ConfigDepositBase: Balance = 5 * DOLLARS;
	pub const FriendDepositFactor: Balance = 50 * CENTS;
	pub const MaxFriends: u16 = 9;
	pub const RecoveryDeposit: Balance = 5 * DOLLARS;
}

558
impl pallet_recovery::Config for Runtime {
ddorgan's avatar
ddorgan committed
559
560
561
562
563
564
565
566
567
568
569
570
571
	type Event = Event;
	type Call = Call;
	type Currency = Balances;
	type ConfigDepositBase = ConfigDepositBase;
	type FriendDepositFactor = FriendDepositFactor;
	type MaxFriends = MaxFriends;
	type RecoveryDeposit = RecoveryDeposit;
}

parameter_types! {
	pub const MinVestedTransfer: Balance = 100 * DOLLARS;
}

572
impl pallet_vesting::Config for Runtime {
ddorgan's avatar
ddorgan committed
573
574
575
576
	type Event = Event;
	type Currency = Balances;
	type BlockNumberToBalance = ConvertInto;
	type MinVestedTransfer = MinVestedTransfer;
577
	type WeightInfo = weights::pallet_vesting::WeightInfo<Runtime>;
ddorgan's avatar
ddorgan committed
578
579
}

580
impl pallet_sudo::Config for Runtime {
ddorgan's avatar
ddorgan committed
581
582
583
584
	type Event = Event;
	type Call = Call;
}

585
586
587
588
589
590
parameter_types! {
	// One storage item; key size 32, value size 8; .
	pub const ProxyDepositBase: Balance = deposit(1, 8);
	// Additional storage item size of 33 bytes.
	pub const ProxyDepositFactor: Balance = deposit(0, 33);
	pub const MaxProxies: u16 = 32;
591
592
593
	pub const AnnouncementDepositBase: Balance = deposit(1, 8);
	pub const AnnouncementDepositFactor: Balance = deposit(0, 66);
	pub const MaxPending: u16 = 32;
594
595
596
597
598
599
600
601
}

/// The type used to represent the kinds of proxying allowed.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, RuntimeDebug)]
pub enum ProxyType {
	Any,
	NonTransfer,
	Staking,
602
	SudoBalances,
Chevdor's avatar
Chevdor committed
603
	IdentityJudgement,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
604
	CancelProxy,
605
606
607
608
609
610
}
impl Default for ProxyType { fn default() -> Self { Self::Any } }
impl InstanceFilter<Call> for ProxyType {
	fn filter(&self, c: &Call) -> bool {
		match self {
			ProxyType::Any => true,
611
612
613
614
			ProxyType::NonTransfer => matches!(c,
				Call::System(..) |
				Call::Babe(..) |
				Call::Timestamp(..) |
615
616
617
				Call::Indices(pallet_indices::Call::claim(..)) |
				Call::Indices(pallet_indices::Call::free(..)) |
				Call::Indices(pallet_indices::Call::freeze(..)) |
618
619
620
621
622
623
624
625
626
627
628
				// Specifically omitting Indices `transfer`, `force_transfer`
				// Specifically omitting the entire Balances pallet
				Call::Authorship(..) |
				Call::Staking(..) |
				Call::Offences(..) |
				Call::Session(..) |
				Call::Grandpa(..) |
				Call::ImOnline(..) |
				Call::AuthorityDiscovery(..) |
				Call::Utility(..) |
				Call::Identity(..) |
629
630
631
632
633
634
				Call::Recovery(pallet_recovery::Call::as_recovered(..)) |
				Call::Recovery(pallet_recovery::Call::vouch_recovery(..)) |
				Call::Recovery(pallet_recovery::Call::claim_recovery(..)) |
				Call::Recovery(pallet_recovery::Call::close_recovery(..)) |
				Call::Recovery(pallet_recovery::Call::remove_recovery(..)) |
				Call::Recovery(pallet_recovery::Call::cancel_recovered(..)) |
635
				// Specifically omitting Recovery `create_recovery`, `initiate_recovery`
636
637
				Call::Vesting(pallet_vesting::Call::vest(..)) |
				Call::Vesting(pallet_vesting::Call::vest_other(..)) |
638
639
640
641
642
				// Specifically omitting Vesting `vested_transfer`, and `force_vested_transfer`
				Call::Scheduler(..) |
				// Specifically omitting Sudo pallet
				Call::Proxy(..) |
				Call::Multisig(..)
643
644
			),
			ProxyType::Staking => matches!(c,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
645
646
647
				Call::Staking(..) |
				Call::Session(..) |
				Call::Utility(..)
648
			),
649
			ProxyType::SudoBalances => match c {
650
				Call::Sudo(pallet_sudo::Call::sudo(ref x)) => matches!(x.as_ref(), &Call::Balances(..)),
Gavin Wood's avatar
Gavin Wood committed
651
				Call::Utility(..) => true,
652
653
				_ => false,
			},
Chevdor's avatar
Chevdor committed
654
			ProxyType::IdentityJudgement => matches!(c,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
655
656
				Call::Identity(pallet_identity::Call::provide_judgement(..)) |
				Call::Utility(..)
Shawn Tabrizi's avatar
Shawn Tabrizi committed
657
658
			),
			ProxyType::CancelProxy => matches!(c,
659
				Call::Proxy(pallet_proxy::Call::reject_announcement(..))
Chevdor's avatar
Chevdor committed
660
			)
661
662
663
664
665
666
667
668
669
		}
	}
	fn is_superset(&self, o: &Self) -> bool {
		match (self, o) {
			(x, y) if x == y => true,
			(ProxyType::Any, _) => true,
			(_, ProxyType::Any) => false,
			(ProxyType::NonTransfer, _) => true,
			_ => false,
670
671
672
673
		}
	}
}

674
impl pallet_proxy::Config for Runtime {
675
676
677
678
679
680
681
	type Event = Event;
	type Call = Call;
	type Currency = Balances;
	type ProxyType = ProxyType;
	type ProxyDepositBase = ProxyDepositBase;
	type ProxyDepositFactor = ProxyDepositFactor;
	type MaxProxies = MaxProxies;
682
	type WeightInfo = weights::pallet_proxy::WeightInfo<Runtime>;
683
684
685
686
	type MaxPending = MaxPending;
	type CallHasher = BlakeTwo256;
	type AnnouncementDepositBase = AnnouncementDepositBase;
	type AnnouncementDepositFactor = AnnouncementDepositFactor;
687
688
}

ddorgan's avatar
ddorgan committed
689
690
691
construct_runtime! {
	pub enum Runtime where
		Block = Block,
692
		NodeBlock = primitives::v1::Block,
ddorgan's avatar
ddorgan committed
693
694
695
		UncheckedExtrinsic = UncheckedExtrinsic
	{
		// Basic stuff; balances is uncallable initially.
696
697
		System: frame_system::{Module, Call, Storage, Config, Event<T>} = 0,
		RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Module, Storage} = 25,
ddorgan's avatar
ddorgan committed
698
699

		// Must be before session.
700
		Babe: pallet_babe::{Module, Call, Storage, Config, ValidateUnsigned} = 1,
ddorgan's avatar
ddorgan committed
701

702
703
704
705
		Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent} = 2,
		Indices: pallet_indices::{Module, Call, Storage, Config<T>, Event<T>} = 3,
		Balances: pallet_balances::{Module, Call, Storage, Config<T>, Event<T>} = 4,
		TransactionPayment: pallet_transaction_payment::{Module, Storage} = 26,
ddorgan's avatar
ddorgan committed
706
707

		// Consensus support.
708
709
710
711
712
713
714
715
		Authorship: pallet_authorship::{Module, Call, Storage} = 5,
		Staking: pallet_staking::{Module, Call, Storage, Config<T>, Event<T>, ValidateUnsigned} = 6,
		Offences: pallet_offences::{Module, Call, Storage, Event} = 7,
		Historical: session_historical::{Module} = 27,
		Session: pallet_session::{Module, Call, Storage, Event, Config<T>} = 8,
		Grandpa: pallet_grandpa::{Module, Call, Storage, Config, Event, ValidateUnsigned} = 10,
		ImOnline: pallet_im_online::{Module, Call, Storage, Event<T>, ValidateUnsigned, Config<T>} = 11,
		AuthorityDiscovery: pallet_authority_discovery::{Module, Call, Config} = 12,
ddorgan's avatar
ddorgan committed
716
717

		// Utility module.
718
		Utility: pallet_utility::{Module, Call, Event} = 16,
ddorgan's avatar
ddorgan committed
719
720

		// Less simple identity module.
721
		Identity: pallet_identity::{Module, Call, Storage, Event<T>} = 17,
ddorgan's avatar
ddorgan committed
722
723

		// Social recovery module.
724
		Recovery: pallet_recovery::{Module, Call, Storage, Event<T>} = 18,
ddorgan's avatar
ddorgan committed
725
726

		// Vesting. Usable initially, but removed once all vesting is finished.
727
		Vesting: pallet_vesting::{Module, Call, Storage, Event<T>, Config<T>} = 19,
ddorgan's avatar
ddorgan committed
728
729

		// System scheduler.
730
		Scheduler: pallet_scheduler::{Module, Call, Storage, Event<T>} = 20,
ddorgan's avatar
ddorgan committed
731
732

		// Sudo.
733
		Sudo: pallet_sudo::{Module, Call, Storage, Event<T>, Config<T>} = 21,
734
735

		// Proxy module. Late addition.
736
		Proxy: pallet_proxy::{Module, Call, Storage, Event<T>} = 22,
737
738

		// Multisig module. Late addition.
739
		Multisig: pallet_multisig::{Module, Call, Storage, Event<T>} = 23,
740
741
742

		// Election pallet. Only works with staking, but placed here to maintain indices.
		ElectionProviderMultiPhase: pallet_election_provider_multi_phase::{Module, Call, Storage, Event<T>, ValidateUnsigned} = 24,
ddorgan's avatar
ddorgan committed
743
744
745
746
	}
}

/// The address format for describing accounts.
747
pub type Address = sp_runtime::MultiAddress<AccountId, ()>;
ddorgan's avatar
ddorgan committed
748
749
750
751
752
753
754
755
756
757
/// Block header type as expected by this runtime.
pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
/// Block type as expected by this runtime.
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
/// A Block signed with a Justification
pub type SignedBlock = generic::SignedBlock<Block>;
/// BlockId type as expected by this runtime.
pub type BlockId = generic::BlockId<Block>;
/// The SignedExtension to the basic transaction logic.
pub type SignedExtra = (
758
759
760
761
762
763
764
	frame_system::CheckSpecVersion<Runtime>,
	frame_system::CheckTxVersion<Runtime>,
	frame_system::CheckGenesis<Runtime>,
	frame_system::CheckMortality<Runtime>,
	frame_system::CheckNonce<Runtime>,
	frame_system::CheckWeight<Runtime>,
	pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
ddorgan's avatar
ddorgan committed
765
766
767
768
769
770
);
/// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;
/// Extrinsic type that has already been checked.
pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Nonce, Call>;
/// Executive: handles dispatch to the various modules.
771
772
773
774
775
776
pub type Executive = frame_executive::Executive<
	Runtime,
	Block,
	frame_system::ChainContext<Runtime>,
	Runtime,
	AllModules,
777
	()
778
>;
779
780
/// The payload being signed in transactions.
pub type SignedPayload = generic::SignedPayload<Call, SignedExtra>;
ddorgan's avatar
ddorgan committed
781

782
783
784
pub struct CustomOnRuntimeUpgrade;
impl frame_support::traits::OnRuntimeUpgrade for CustomOnRuntimeUpgrade {
	fn on_runtime_upgrade() -> frame_support::weights::Weight {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
785
		0
786
787
788
	}
}

789
#[cfg(not(feature = "disable-runtime-api"))]
ddorgan's avatar
ddorgan committed
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
sp_api::impl_runtime_apis! {
	impl sp_api::Core<Block> for Runtime {
		fn version() -> RuntimeVersion {
			VERSION
		}

		fn execute_block(block: Block) {
			Executive::execute_block(block)
		}

		fn initialize_block(header: &<Block as BlockT>::Header) {
			Executive::initialize_block(header)
		}
	}

	impl sp_api::Metadata<Block> for Runtime {
		fn metadata() -> OpaqueMetadata {
			Runtime::metadata().into()
		}
	}

	impl block_builder_api::BlockBuilder<Block> for Runtime {
		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
			Executive::apply_extrinsic(extrinsic)
		}

		fn finalize_block() -> <Block as BlockT>::Header {
			Executive::finalize_block()
		}

		fn inherent_extrinsics(data: inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
			data.create_extrinsics()
		}

		fn check_inherents(
			block: Block,
			data: inherents::InherentData,
		) -> inherents::CheckInherentsResult {
			data.check_extrinsics(&block)
		}

		fn random_seed() -> <Block as BlockT>::Hash {
			RandomnessCollectiveFlip::random_seed()
		}
	}

	impl tx_pool_api::runtime_api::TaggedTransactionQueue<Block> for Runtime {
		fn validate_transaction(
			source: TransactionSource,
			tx: <Block as BlockT>::Extrinsic,
		) -> TransactionValidity {
			Executive::validate_transaction(source, tx)
		}
	}

	impl offchain_primitives::OffchainWorkerApi<Block> for Runtime {
		fn offchain_worker(header: &<Block as BlockT>::Header) {
			Executive::offchain_worker(header)
		}
	}

851
852
853
	impl primitives::v1::ParachainHost<Block, Hash, BlockNumber> for Runtime {
		fn validators() -> Vec<ValidatorId> {
			Vec::new()
ddorgan's avatar
ddorgan committed
854
		}
855
856
857

		fn validator_groups() -> (Vec<Vec<ValidatorIndex>>, GroupRotationInfo<BlockNumber>) {
			(Vec::new(), GroupRotationInfo { session_start_block: 0, group_rotation_frequency: 0, now: 0 })
ddorgan's avatar
ddorgan committed
858
		}
859

860
		fn availability_cores() -> Vec<CoreState<Hash, BlockNumber>> {
861
			Vec::new()
ddorgan's avatar
ddorgan committed
862
		}
863
864
865

		fn persisted_validation_data(_: Id, _: OccupiedCoreAssumption)
			-> Option<PersistedValidationData<BlockNumber>> {
866
			None
ddorgan's avatar
ddorgan committed
867
		}
868

869
870
871
872
		fn historical_validation_code(_: Id, _: BlockNumber) -> Option<ValidationCode> {
			None
		}

873
874
		fn check_validation_outputs(
			_: Id,
875
			_: primitives::v1::CandidateCommitments
876
877
878
879
		) -> bool {
			false
		}

880
881
882
883
		fn session_index_for_child() -> SessionIndex {
			0
		}

884
885
886
887
		fn session_info(_: SessionIndex) -> Option<SessionInfo> {
			None
		}

888
		fn validation_code(_: Id, _: OccupiedCoreAssumption) -> Option<ValidationCode> {
889
			None
ddorgan's avatar
ddorgan committed
890
		}
891
892
893

		fn candidate_pending_availability(_: Id) -> Option<CommittedCandidateReceipt<Hash>> {
			None
ddorgan's avatar
ddorgan committed
894
		}
895
896

		fn candidate_events() -> Vec<CandidateEvent<Hash>> {
897
			Vec::new()
898
		}
899

900
901
		fn dmq_contents(
			_recipient: Id,
Sergey Pepyakin's avatar
Sergey Pepyakin committed
902
		) -> Vec<InboundDownwardMessage<BlockNumber>> {
903
904
			Vec::new()
		}
Sergey Pepyakin's avatar
Sergey Pepyakin committed
905
906
907
908
909
910

		fn inbound_hrmp_channels_contents(
			_recipient: Id
		) -> BTreeMap<Id, Vec<InboundHrmpMessage<BlockNumber>>> {
			BTreeMap::new()
		}
ddorgan's avatar
ddorgan committed
911
912
913
914
915
916
	}

	impl fg_primitives::GrandpaApi<Block> for Runtime {
		fn grandpa_authorities() -> Vec<(GrandpaId, u64)> {
			Grandpa::grandpa_authorities()
		}
917

918
		fn submit_report_equivocation_unsigned_extrinsic(
919
920
921
922
923
924
925
926
			equivocation_proof: fg_primitives::EquivocationProof<
				<Block as BlockT>::Hash,
				sp_runtime::traits::NumberFor<Block>,
			>,
			key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,
		) -> Option<()> {
			let key_owner_proof = key_owner_proof.decode()?;

927
			Grandpa::submit_unsigned_equivocation_report(
928
929
930
931
932
933
934
935
936
				equivocation_proof,
				key_owner_proof,
			)
		}

		fn generate_key_ownership_proof(
			_set_id: fg_primitives::SetId,
			authority_id: fg_primitives::AuthorityId,
		) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {
937
			use parity_scale_codec::Encode;
938
939
940
941
942

			Historical::prove((fg_primitives::KEY_TYPE, authority_id))
				.map(|p| p.encode())
				.map(fg_primitives::OpaqueKeyOwnershipProof::new)
		}
ddorgan's avatar
ddorgan committed
943
944
945
	}

	impl babe_primitives::BabeApi<Block> for Runtime {
946
		fn configuration() -> babe_primitives::BabeGenesisConfiguration {
ddorgan's avatar
ddorgan committed
947
948
949
950
951
			// The choice of `c` parameter (where `1 - c` represents the
			// probability of a slot being empty), is done in accordance to the
			// slot duration and expected target block time, for safely
			// resisting network delays of maximum two seconds.
			// <https://research.web3.foundation/en/latest/polkadot/BABE/Babe/#6-practical-results>
952
			babe_primitives::BabeGenesisConfiguration {
ddorgan's avatar
ddorgan committed
953
954
955
956
957
				slot_duration: Babe::slot_duration(),
				epoch_length: EpochDuration::get(),
				c: PRIMARY_PROBABILITY,
				genesis_authorities: Babe::authorities(),
				randomness: Babe::randomness(),
958
				allowed_slots: babe_primitives::AllowedSlots::PrimaryAndSecondaryPlainSlots,
ddorgan's avatar
ddorgan committed
959
960
961
			}
		}

Bastian Köcher's avatar
Bastian Köcher committed
962
		fn current_epoch_start() -> babe_primitives::Slot {
ddorgan's avatar
ddorgan committed
963
964
			Babe::current_epoch_start()
		}
965

966
967
968
969
		fn current_epoch() -> babe_primitives::Epoch {
			Babe::current_epoch()
		}

970
971
972
973
		fn next_epoch() -> babe_primitives::Epoch {
			Babe::next_epoch()
		}

974
		fn generate_key_ownership_proof(
Bastian Köcher's avatar
Bastian Köcher committed
975
			_slot: babe_primitives::Slot,
976
977
			authority_id: babe_primitives::AuthorityId,
		) -> Option<babe_primitives::OpaqueKeyOwnershipProof> {
978
			use parity_scale_codec::Encode;
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995

			Historical::prove((babe_primitives::KEY_TYPE, authority_id))
				.map(|p| p.encode())
				.map(babe_primitives::OpaqueKeyOwnershipProof::new)
		}

		fn submit_report_equivocation_unsigned_extrinsic(
			equivocation_proof: babe_primitives::EquivocationProof<<Block as BlockT>::Header>,
			key_owner_proof: babe_primitives::OpaqueKeyOwnershipProof,
		) -> Option<()> {
			let key_owner_proof = key_owner_proof.decode()?;

			Babe::submit_unsigned_equivocation_report(
				equivocation_proof,
				key_owner_proof,
			)
		}
ddorgan's avatar
ddorgan committed
996
997
998
999
1000
	}

	impl authority_discovery_primitives::AuthorityDiscoveryApi<Block> for Runtime {
		fn authorities() -> Vec<AuthorityDiscoveryId> {
			AuthorityDiscovery::authorities()
For faster browsing, not all history is shown. View entire blame