// This file is part of Substrate. // Copyright (C) 2018-2021 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 // This program 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. // This program 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 this program. If not, see . //! The Substrate 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. #![recursion_limit = "256"] use sp_std::prelude::*; use frame_support::{ construct_runtime, parameter_types, RuntimeDebug, traits::{ KeyOwnerProofSystem, U128CurrencyToVote, EqualPrivilegeOnly, OnRuntimeUpgrade, }, weights::{constants::RocksDbWeight, ConstantMultiplier, Weight}, }; use frame_system::{EnsureRoot, EnsureSigned, EnsureRootWithSuccess, EnsureWithSuccess}; use frame_support::{ traits::{ ConstU32, InstanceFilter, Contains, EitherOf, EitherOfDiverse, AsEnsureOriginWithArg, tokens::nonfungibles_v2::Inspect, }, PalletId, }; use codec::{Encode, Decode, MaxEncodedLen}; use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; pub use node_primitives::{AccountId, Signature}; use node_primitives::{Balance, BlockNumber, Hash, Index, Moment}; use sp_api::impl_runtime_apis; use sp_runtime::{ ApplyExtrinsicResult, impl_opaque_keys, generic, create_runtime_str, }; use frame_election_provider_support::{onchain, SequentialPhragmen}; use pallet_election_provider_multi_phase::SolutionAccuracyOf; use sp_runtime::transaction_validity::{TransactionValidity, TransactionSource}; use sp_runtime::traits::{self, BlakeTwo256, Block as BlockT, SaturatedConversion, ConvertInto, OpaqueKeys, NumberFor, AccountIdLookup, Get}; use sp_version::RuntimeVersion; #[cfg(any(feature = "std", test))] use sp_version::NativeVersion; use pallet_grandpa::{AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList}; use pallet_grandpa::fg_primitives; use pallet_im_online::sr25519::AuthorityId as ImOnlineId; use sp_authority_discovery::AuthorityId as AuthorityDiscoveryId; use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo}; pub use pallet_transaction_payment::{Multiplier, TargetedFeeAdjustment, CurrencyAdapter}; use pallet_session::{historical as pallet_session_historical}; use sp_inherents::{InherentData, CheckInherentsResult}; use static_assertions::const_assert; #[cfg(any(feature = "std", test))] pub use sp_runtime::BuildStorage; #[cfg(any(feature = "std", test))] pub use pallet_balances::Call as BalancesCall; #[cfg(any(feature = "std", test))] pub use frame_system::Call as SystemCall; #[cfg(any(feature = "std", test))] pub use pallet_staking::StakerStatus; // Runtime common stuff use runtime_common::*; use runtime_common::impls::*; use runtime_common::constants::{time::*, fee::*}; use sp_runtime::generic::Era; use sp_io::hashing::sha2_256; // Bridge migration use migrations::bridge_adjust::BridgeAdjust; mod weights; /// Generated voter bag information. mod voter_bags; // Make the WASM binary available. #[cfg(feature = "std")] include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); /// Wasm binary unwrapped. If built with `SKIP_WASM_BUILD`, the function panics. #[cfg(feature = "std")] pub fn wasm_binary_unwrap() -> &'static [u8] { WASM_BINARY.expect("Development wasm binary is not available. This means the client is \ built with `SKIP_WASM_BUILD` flag and it is only usable for \ production chains. Please rebuild with the flag disabled.") } /// Runtime version. pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("xxnetwork"), impl_name: create_runtime_str!("xxlabs-xxnetwork"), authoring_version: 0, // Per convention: if the runtime behavior changes, increment spec_version // and set impl_version to 0. If only runtime // implementation changes and behavior does not, then leave spec_version as // is and increment impl_version. spec_version: 206, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 1, state_version: 0, }; /// The BABE epoch configuration at genesis. pub const BABE_GENESIS_EPOCH_CONFIG: sp_consensus_babe::BabeEpochConfiguration = sp_consensus_babe::BabeEpochConfiguration { c: PRIMARY_PROBABILITY, allowed_slots: sp_consensus_babe::AllowedSlots::PrimaryAndSecondaryPlainSlots }; /// Native version. #[cfg(any(feature = "std", test))] pub fn native_version() -> NativeVersion { NativeVersion { runtime_version: VERSION, can_author_with: Default::default(), } } parameter_types! { pub const Version: RuntimeVersion = VERSION; pub const SS58Prefix: u8 = 55; } pub struct BaseFilter; impl Contains for BaseFilter { fn contains(call: &RuntimeCall) -> bool { // These modules are all allowed to be called by transactions match call { // Disable uniques pallet, since Nfts one should be used instead RuntimeCall::Uniques(_) => false, // System pallets RuntimeCall::System(_) | RuntimeCall::Scheduler(_) | RuntimeCall::Preimage(_) | // Block production and Balances RuntimeCall::Babe(_) | RuntimeCall::Balances(_) | RuntimeCall::Timestamp(_) | // Consensus support RuntimeCall::Staking(_) | RuntimeCall::ElectionProviderMultiPhase(_) | RuntimeCall::Session(_) | RuntimeCall::Grandpa(_) | RuntimeCall::ImOnline(_) | RuntimeCall::VoterList(_) | // Governance RuntimeCall::Democracy(_) | RuntimeCall::Council(_) | RuntimeCall::TechnicalCommittee(_) | RuntimeCall::Elections(_) | RuntimeCall::TechnicalMembership(_) | RuntimeCall::Treasury(_) | // Claims RuntimeCall::Claims(_) | // Misc RuntimeCall::Vesting(_) | RuntimeCall::Utility(_) | RuntimeCall::Identity(_) | RuntimeCall::Proxy(_) | RuntimeCall::Bounties(_) | RuntimeCall::ChildBounties(_) | RuntimeCall::Tips(_) | RuntimeCall::Multisig(_) | RuntimeCall::Recovery(_) | RuntimeCall::Assets(_) | RuntimeCall::Nfts(_) | // XX Network RuntimeCall::XXCmix(_) | RuntimeCall::XXCustody(_) | RuntimeCall::XXEconomics(_) | RuntimeCall::XXBetanetRewards(_) | RuntimeCall::XXPublic(_) | // ChainBridge and Swap RuntimeCall::ChainBridge(_) | RuntimeCall::Swap(_) => true, } } } impl frame_system::Config for Runtime { type BaseCallFilter = BaseFilter; type BlockWeights = BlockWeights; type BlockLength = BlockLength; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; type Index = Index; type BlockNumber = BlockNumber; type Hash = Hash; type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = AccountIdLookup; type Header = generic::Header; type RuntimeEvent = RuntimeEvent; type BlockHashCount = BlockHashCount; type DbWeight = RocksDbWeight; type Version = Version; type PalletInfo = PalletInfo; type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); type SystemWeightInfo = weights::frame_system::WeightInfo; type SS58Prefix = SS58Prefix; type OnSetCode = (); type MaxConsumers = ConstU32<16>; } impl pallet_utility::Config for Runtime { type RuntimeEvent = RuntimeEvent; type RuntimeCall = RuntimeCall; type PalletsOrigin = OriginCaller; type WeightInfo = weights::pallet_utility::WeightInfo; } /// The type used to represent the kinds of proxying allowed. #[derive( Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, RuntimeDebug, MaxEncodedLen, scale_info::TypeInfo, )] pub enum ProxyType { Any, NonTransfer, Governance, Staking, Voting, } impl Default for ProxyType { fn default() -> Self { Self::Any } } impl InstanceFilter for ProxyType { fn filter(&self, c: &RuntimeCall) -> bool { match self { ProxyType::Any => true, ProxyType::NonTransfer => !matches!( c, RuntimeCall::Assets(..) | RuntimeCall::Uniques(..) | RuntimeCall::Nfts(..) | RuntimeCall::Balances(..) | RuntimeCall::Vesting(pallet_vesting::Call::vested_transfer { .. }) ), ProxyType::Governance => matches!( c, RuntimeCall::Democracy(..) | RuntimeCall::Council(..) | RuntimeCall::TechnicalCommittee(..) | RuntimeCall::Elections(..) | RuntimeCall::Treasury(..) | RuntimeCall::Preimage(..) | RuntimeCall::Bounties(_) | RuntimeCall::ChildBounties(_) ), ProxyType::Staking => matches!(c, RuntimeCall::Staking(..)), ProxyType::Voting => matches!( c, RuntimeCall::Democracy(pallet_democracy::Call::vote { .. } | pallet_democracy::Call::remove_vote { .. }) | RuntimeCall::Elections(pallet_elections_phragmen::Call::vote { .. } | pallet_elections_phragmen::Call::remove_voter { .. }) ), } } 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, } } } impl pallet_proxy::Config for Runtime { type RuntimeEvent = RuntimeEvent; type RuntimeCall = RuntimeCall; type Currency = Balances; type ProxyType = ProxyType; type ProxyDepositBase = ProxyDepositBase; type ProxyDepositFactor = ProxyDepositFactor; type MaxProxies = MaxProxies; type WeightInfo = weights::pallet_proxy::WeightInfo; type MaxPending = MaxPending; type CallHasher = BlakeTwo256; type AnnouncementDepositBase = AnnouncementDepositBase; type AnnouncementDepositFactor = AnnouncementDepositFactor; } impl pallet_scheduler::Config for Runtime { type RuntimeEvent = RuntimeEvent; type RuntimeOrigin = RuntimeOrigin; type PalletsOrigin = OriginCaller; type RuntimeCall = RuntimeCall; type MaximumWeight = MaximumSchedulerWeight; type ScheduleOrigin = EnsureRoot; type MaxScheduledPerBlock = MaxScheduledPerBlock; type WeightInfo = weights::pallet_scheduler::WeightInfo; type OriginPrivilegeCmp = EqualPrivilegeOnly; type Preimages = Preimage; } impl pallet_preimage::Config for Runtime { type WeightInfo = weights::pallet_preimage::WeightInfo; type RuntimeEvent = RuntimeEvent; type Currency = Balances; type ManagerOrigin = EnsureRoot; type BaseDeposit = PreimageBaseDeposit; type ByteDeposit = PreimageByteDeposit; } // Epoch duration is 8 hours in prod, 4 minutes in dev (fast-runtime) const EPOCH_DURATION_IN_BLOCKS: BlockNumber = prod_or_fast!(8*HOURS, 4*MINUTES); parameter_types! { // NOTE: Currently it is not possible to change the epoch duration after the chain has started. // Attempting to do so will brick block production. pub const EpochDuration: u64 = EPOCH_DURATION_IN_BLOCKS as u64; pub const ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK; pub const ReportLongevity: u64 = BondingDuration::get() as u64 * SessionsPerEra::get() as u64 * EpochDuration::get(); } impl pallet_babe::Config for Runtime { type EpochDuration = EpochDuration; type ExpectedBlockTime = ExpectedBlockTime; type EpochChangeTrigger = pallet_babe::ExternalTrigger; type DisabledValidators = Session; type WeightInfo = (); type MaxAuthorities = MaxAuthorities; type KeyOwnerProof = >::Proof; type EquivocationReportSystem = pallet_babe::EquivocationReportSystem; } impl pallet_balances::Config for Runtime { type Balance = Balance; type DustRemoval = (); type RuntimeEvent = RuntimeEvent; type ExistentialDeposit = ExistentialDeposit; type AccountStore = frame_system::Pallet; type WeightInfo = weights::pallet_balances::WeightInfo; type MaxLocks = MaxLocks; type MaxReserves = MaxReserves; type ReserveIdentifier = [u8; 8]; } impl pallet_transaction_payment::Config for Runtime { type RuntimeEvent = RuntimeEvent; type OnChargeTransaction = CurrencyAdapter>; type OperationalFeeMultiplier = OperationalFeeMultiplier; type WeightToFee = WeightToFee; type LengthToFee = ConstantMultiplier; type FeeMultiplierUpdate = TargetedFeeAdjustment; } parameter_types! { pub const MinimumPeriod: Moment = SLOT_DURATION / 2; } impl pallet_timestamp::Config for Runtime { type Moment = Moment; type OnTimestampSet = Babe; type MinimumPeriod = MinimumPeriod; type WeightInfo = weights::pallet_timestamp::WeightInfo; } impl pallet_authorship::Config for Runtime { type FindAuthor = pallet_session::FindAccountFromAuthorIndex; type EventHandler = (Staking, ImOnline); } impl_opaque_keys! { pub struct SessionKeys { pub grandpa: Grandpa, pub babe: Babe, pub im_online: ImOnline, pub authority_discovery: AuthorityDiscovery, } } impl pallet_session::Config for Runtime { type RuntimeEvent = RuntimeEvent; type ValidatorId = ::AccountId; type ValidatorIdOf = pallet_staking::StashOf; type ShouldEndSession = Babe; type NextSessionRotation = Babe; type SessionManager = pallet_session::historical::NoteHistoricalRoot; type SessionHandler = ::KeyTypeIdProviders; type Keys = SessionKeys; type WeightInfo = weights::pallet_session::WeightInfo; } impl pallet_session::historical::Config for Runtime { type FullIdentification = pallet_staking::Exposure; type FullIdentificationOf = pallet_staking::ExposureOf; } parameter_types! { pub const RewardsPoolId: PalletId = PalletId(*b"xx/rwrds"); pub const EraDuration: BlockNumber = SessionsPerEra::get() * EPOCH_DURATION_IN_BLOCKS; pub const PayoutFrequency: BlockNumber = 1 * WEEKS; pub const CustodyDuration: BlockNumber = 3 * YEARS; pub const GovernanceCustodyDuration: BlockNumber = 1 * YEARS; pub const CustodyProxy: ProxyType = ProxyType::Voting; pub const TestnetId: PalletId = PalletId(*b"xx/tstnt"); pub const SaleId: PalletId = PalletId(*b"xx//sale"); } type EnsureTechnicalUnanimity = EitherOfDiverse< pallet_collective::EnsureProportionAtLeast, EnsureRoot, >; type EnsureTwoThirdsCouncil = EitherOfDiverse< pallet_collective::EnsureProportionAtLeast, EnsureRoot, >; impl xx_economics::Config for Runtime { // General config type RuntimeEvent = RuntimeEvent; type Currency = Balances; type CustodyHandler = XXCustody; type PublicAccountsHandler = XXPublic; // Rewards Pool config type RewardsPoolId = RewardsPoolId; // rewards remainder are taken from pool (until empty) and passed to Treasury type RewardRemainder = Treasury; // Inflation config type EraDuration = EraDuration; // Admin is technical committee unanimity type AdminOrigin = EnsureTechnicalUnanimity; type WeightInfo = weights::xx_economics::WeightInfo; } impl xx_team_custody::Config for Runtime { // General config type RuntimeEvent = RuntimeEvent; type Currency = Balances; // Custody config type PayoutFrequency = PayoutFrequency; type CustodyDuration = CustodyDuration; type GovernanceCustodyDuration = GovernanceCustodyDuration; type CustodyProxy = CustodyProxy; type BlockNumberToBalance = ConvertInto; // Admin is technical committee unanimity type AdminOrigin = EnsureTechnicalUnanimity; // Weight information for extrinsics in this pallet. type WeightInfo = weights::xx_team_custody::WeightInfo; } impl xx_cmix::Config for Runtime { // General config type RuntimeEvent = RuntimeEvent; // CMIX Variables can be changed by 2/3 Council type CmixVariablesOrigin = EnsureTwoThirdsCouncil; // Admin is 2/3 technical committee type AdminOrigin = EnsureTwoThirdsTechnical; // Weight information for extrinsics in this pallet. type WeightInfo = weights::xx_cmix::WeightInfo; } impl xx_public::Config for Runtime { type RuntimeEvent = RuntimeEvent; type VestingSchedule = Vesting; type TestnetId = TestnetId; type SaleId = SaleId; // Admin is technical committee unanimity type AdminOrigin = EnsureTechnicalUnanimity; // Weight information for extrinsics in this pallet. type WeightInfo = weights::xx_public::WeightInfo; } pub struct OnChainSeqPhragmen; impl onchain::Config for OnChainSeqPhragmen { type System = Runtime; type Solver = SequentialPhragmen< AccountId, pallet_election_provider_multi_phase::SolutionAccuracyOf, >; type DataProvider = ::DataProvider; type WeightInfo = weights::frame_election_provider_support::WeightInfo; type MaxWinners = ::MaxWinners; type VotersBound = MaxOnChainElectingVoters; type TargetsBound = MaxOnChainElectableTargets; } pub struct StakingBenchmarkingConfig; impl pallet_staking::BenchmarkingConfig for StakingBenchmarkingConfig { type MaxNominators = ConstU32<1000>; type MaxValidators = ConstU32<1000>; } impl pallet_staking::Config for Runtime { type MaxNominations = MaxNominations; type Currency = Balances; type CurrencyBalance = Balance; type UnixTime = Timestamp; type CurrencyToVote = U128CurrencyToVote; type CmixHandler = XXCmix; type CustodyHandler = XXCustody; type RewardRemainder = xx_economics::rewards::RewardRemainderAdapter; type RuntimeEvent = RuntimeEvent; type Slash = Treasury; // send the slashed funds to the treasury. type Reward = XXEconomics; // rewards are taken from the rewards pool (and then minted once pool is empty) type SessionsPerEra = SessionsPerEra; type BondingDuration = BondingDuration; type SlashDeferDuration = SlashDeferDuration; /// A super-majority of the council can cancel the slash. type AdminOrigin = EitherOfDiverse< EnsureRoot, pallet_collective::EnsureProportionAtLeast >; type SessionInterface = Self; type EraPayout = XXEconomics; // era payout is calculated according to inflation parameters type NextNewSession = Session; type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator; type OffendingValidatorsThreshold = OffendingValidatorsThreshold; type ElectionProvider = ElectionProviderMultiPhase; type GenesisElectionProvider = onchain::OnChainExecution; // Use Bags List Pallet type VoterList = VoterList; type TargetList = pallet_staking::UseValidatorsMap; type MaxUnlockingChunks = ConstU32<32>; type HistoryDepth = ConstU32<84>; type OnStakerSlash = (); type WeightInfo = weights::pallet_staking::WeightInfo; type BenchmarkingConfig = StakingBenchmarkingConfig; } parameter_types! { // phase durations. 1/4 of the last session for each. pub const SignedPhase: u32 = EPOCH_DURATION_IN_BLOCKS / 4; pub const UnsignedPhase: u32 = EPOCH_DURATION_IN_BLOCKS / 4; pub OffchainRepeat: BlockNumber = UnsignedPhase::get() / 32; } impl pallet_election_provider_multi_phase::MinerConfig for Runtime { type AccountId = AccountId; type MaxLength = MinerMaxLength; type MaxWeight = MinerMaxWeight; type Solution = NposSolution16; type MaxVotesPerVoter = < ::DataProvider as frame_election_provider_support::ElectionDataProvider >::MaxVotesPerVoter; type MaxWinners = MaxActiveValidators; // The unsigned submissions have to respect the weight of the submit_unsigned call, thus their // weight estimate function is wired to this call's weight. fn solution_weight(v: u32, t: u32, a: u32, d: u32) -> Weight { < ::WeightInfo as pallet_election_provider_multi_phase::WeightInfo >::submit_unsigned(v, t, a, d) } } impl pallet_election_provider_multi_phase::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Currency = Balances; type EstimateCallFee = TransactionPayment; type UnsignedPhase = UnsignedPhase; type SignedPhase = SignedPhase; type BetterUnsignedThreshold = BetterUnsignedThreshold; type BetterSignedThreshold = (); type OffchainRepeat = OffchainRepeat; type MinerTxPriority = MultiPhaseUnsignedPriority; type MinerConfig = Self; type SignedMaxSubmissions = SignedMaxSubmissions; type SignedMaxWeight = MinerMaxWeight; type SignedRewardBase = SignedRewardBase; type SignedDepositBase = SignedDepositBase; type SignedDepositByte = SignedDepositByte; type SignedMaxRefunds = SignedMaxRefunds; type SignedDepositWeight = (); type SlashHandler = (); type RewardHandler = XXEconomics; type DataProvider = Staking; type Fallback = onchain::OnChainExecution; type GovernanceFallback = onchain::OnChainExecution; type Solver = SequentialPhragmen, OffchainRandomBalancing>; type ForceOrigin = EnsureTwoThirdsCouncil; type MaxElectableTargets = MaxElectableTargets; type MaxWinners = MaxActiveValidators; type MaxElectingVoters = MaxElectingVoters; type BenchmarkingConfig = BenchmarkConfig; type WeightInfo = weights::pallet_election_provider_multi_phase::WeightInfo; } parameter_types! { pub const BagThresholds: &'static [u64] = &voter_bags::THRESHOLDS; } impl pallet_bags_list::Config for Runtime { type RuntimeEvent = RuntimeEvent; type ScoreProvider = Staking; type WeightInfo = weights::pallet_bags_list::WeightInfo; type BagThresholds = BagThresholds; type Score = sp_npos_elections::VoteWeight; } parameter_types! { pub const LaunchPeriod: BlockNumber = 7 * DAYS; pub const VotingPeriod: BlockNumber = 7 * DAYS; pub const FastTrackVotingPeriod: BlockNumber = 3 * HOURS; pub const InstantAllowed: bool = true; pub const EnactmentPeriod: BlockNumber = 7 * DAYS; pub const CooloffPeriod: BlockNumber = 7 * DAYS; } type EnsureTwoThirdsTechnical = EitherOfDiverse< EnsureRoot, pallet_collective::EnsureProportionAtLeast, >; type EnsureRootOrSixtyCouncil = EitherOfDiverse< EnsureRoot, pallet_collective::EnsureProportionAtLeast, >; impl pallet_democracy::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Currency = Balances; type EnactmentPeriod = EnactmentPeriod; type LaunchPeriod = LaunchPeriod; type VotingPeriod = VotingPeriod; type VoteLockingPeriod = EnactmentPeriod; type MinimumDeposit = MinimumDeposit; /// A straight majority of the council can decide what their next motion is. type ExternalOrigin = EitherOfDiverse< pallet_collective::EnsureProportionAtLeast, EnsureRoot, >; /// A 60% super-majority can have the next scheduled referendum be a straight majority-carries vote. type ExternalMajorityOrigin = EnsureRootOrSixtyCouncil; /// A unanimous council can have the next scheduled referendum be a straight default-carries /// (NTB) vote. type ExternalDefaultOrigin = EitherOfDiverse< pallet_collective::EnsureProportionAtLeast, EnsureRoot, >; /// Two thirds of the technical committee can have an ExternalMajority/ExternalDefault vote /// be tabled immediately and with a shorter voting/enactment period. type FastTrackOrigin = EnsureTwoThirdsTechnical; type InstantOrigin = EnsureTechnicalUnanimity; type InstantAllowed = InstantAllowed; type FastTrackVotingPeriod = FastTrackVotingPeriod; // To cancel a proposal which has been passed, 2/3 of the council must agree to it. type CancellationOrigin = EnsureTwoThirdsCouncil; type BlacklistOrigin = EnsureRoot; // To cancel a proposal before it has been passed, the technical committee must be unanimous or // Root must agree. type CancelProposalOrigin = EnsureTechnicalUnanimity; // Any single technical committee member may veto a coming council proposal, however they can // only do it once and it lasts only for the cool-off period. type VetoOrigin = pallet_collective::EnsureMember; type CooloffPeriod = CooloffPeriod; type Slash = Treasury; type Scheduler = Scheduler; type PalletsOrigin = OriginCaller; type MaxVotes = MaxVotes; type WeightInfo = weights::pallet_democracy::WeightInfo; type MaxProposals = MaxProposals; type Preimages = Preimage; type MaxDeposits = ConstU32<100>; type MaxBlacklisted = ConstU32<100>; type SubmitOrigin = EnsureSigned; } type CouncilCollective = pallet_collective::Instance1; impl pallet_collective::Config for Runtime { type RuntimeOrigin = RuntimeOrigin; type Proposal = RuntimeCall; type RuntimeEvent = RuntimeEvent; type MotionDuration = CouncilMotionDuration; type MaxProposals = CouncilMaxProposals; type MaxMembers = CouncilMaxMembers; type DefaultVote = pallet_collective::PrimeDefaultVote; type WeightInfo = weights::pallet_collective::WeightInfo; type SetMembersOrigin = EnsureRoot; } parameter_types! { pub const DesiredMembers: u32 = 13; pub const DesiredRunnersUp: u32 = 10; } // Make sure that there are no more than `MaxMembers` members elected via elections-phragmen. const_assert!(DesiredMembers::get() <= CouncilMaxMembers::get()); impl pallet_elections_phragmen::Config for Runtime { type RuntimeEvent = RuntimeEvent; type PalletId = ElectionsPhragmenPalletId; type Currency = Balances; type ChangeMembers = Council; // NOTE: this implies that council's genesis members cannot be set directly and must come from // this module. type InitializeMembers = Council; type CurrencyToVote = U128CurrencyToVote; type CandidacyBond = CandidacyBond; type VotingBondBase = VotingBondBase; type VotingBondFactor = VotingBondFactor; type LoserCandidate = Treasury; type KickedMember = Treasury; type DesiredMembers = DesiredMembers; type DesiredRunnersUp = DesiredRunnersUp; type TermDuration = TermDuration; type MaxVoters = MaxVoters; type MaxVotesPerVoter = MaxVotesPerVoter; type MaxCandidates = MaxCandidates; type WeightInfo = weights::pallet_elections_phragmen::WeightInfo; } type TechnicalCollective = pallet_collective::Instance2; impl pallet_collective::Config for Runtime { type RuntimeOrigin = RuntimeOrigin; type Proposal = RuntimeCall; type RuntimeEvent = RuntimeEvent; type MotionDuration = TechnicalMotionDuration; type MaxProposals = TechnicalMaxProposals; type MaxMembers = TechnicalMaxMembers; type DefaultVote = pallet_collective::PrimeDefaultVote; type WeightInfo = weights::pallet_collective::WeightInfo; type SetMembersOrigin = EnsureRoot; } type EnsureRootOrHalfCouncil = EitherOfDiverse< EnsureRoot, pallet_collective::EnsureProportionMoreThan >; impl pallet_membership::Config for Runtime { type RuntimeEvent = RuntimeEvent; type AddOrigin = EnsureRootOrHalfCouncil; type RemoveOrigin = EnsureRootOrHalfCouncil; type SwapOrigin = EnsureRootOrHalfCouncil; type ResetOrigin = EnsureRootOrHalfCouncil; type PrimeOrigin = EnsureRootOrHalfCouncil; type MembershipInitialized = TechnicalCommittee; type MembershipChanged = TechnicalCommittee; type MaxMembers = TechnicalMaxMembers; type WeightInfo = weights::pallet_membership::WeightInfo; } parameter_types! { pub const RootSpendOriginMaxAmount: Balance = Balance::MAX; pub const CouncilSpendOriginMaxAmount: Balance = Balance::MAX; } impl pallet_treasury::Config for Runtime { type Currency = Balances; type ApproveOrigin = EnsureRootOrSixtyCouncil; type RejectOrigin = EnsureRootOrHalfCouncil; type RuntimeEvent = RuntimeEvent; type OnSlash = Treasury; type ProposalBond = ProposalBond; type ProposalBondMinimum = ProposalBondMinimum; type ProposalBondMaximum = ProposalBondMaximum; type SpendPeriod = SpendPeriod; type Burn = Burn; type PalletId = TreasuryPalletId; type BurnDestination = (); type WeightInfo = weights::pallet_treasury::WeightInfo; type SpendFunds = Bounties; type MaxApprovals = MaxApprovals; type SpendOrigin = EitherOf< EnsureRootWithSuccess, EnsureWithSuccess< pallet_collective::EnsureProportionAtLeast, AccountId, CouncilSpendOriginMaxAmount, >, >; } impl pallet_bounties::Config for Runtime { type BountyDepositBase = BountyDepositBase; type BountyDepositPayoutDelay = BountyDepositPayoutDelay; type BountyUpdatePeriod = BountyUpdatePeriod; type CuratorDepositMultiplier = CuratorDepositMultiplier; type CuratorDepositMin = CuratorDepositMin; type CuratorDepositMax = CuratorDepositMax; type BountyValueMinimum = BountyValueMinimum; type ChildBountyManager = ChildBounties; type DataDepositPerByte = DataDepositPerByte; type RuntimeEvent = RuntimeEvent; type MaximumReasonLength = MaximumReasonLength; type WeightInfo = weights::pallet_bounties::WeightInfo; } impl pallet_child_bounties::Config for Runtime { type RuntimeEvent = RuntimeEvent; type MaxActiveChildBountyCount = MaxActiveChildBountyCount; type ChildBountyValueMinimum = ChildBountyValueMinimum; type WeightInfo = weights::pallet_child_bounties::WeightInfo; } impl pallet_tips::Config for Runtime { type RuntimeEvent = RuntimeEvent; type MaximumReasonLength = MaximumReasonLength; type DataDepositPerByte = DataDepositPerByte; type TipCountdown = TipCountdown; type TipFindersFee = TipFindersFee; type TipReportDepositBase = TipReportDepositBase; type Tippers = Elections; type WeightInfo = weights::pallet_tips::WeightInfo; } impl frame_system::offchain::CreateSignedTransaction for Runtime where RuntimeCall: From, { fn create_transaction>( call: RuntimeCall, public: ::Signer, account: AccountId, nonce: Index, ) -> Option<(RuntimeCall, ::SignaturePayload)> { use sp_runtime::traits::StaticLookup; let tip = 0; // take the biggest period possible. 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::() // The `System::block_number` is initialized with `n+1`, // so the actual block number is `n`. .saturating_sub(1); let era = Era::mortal(period, current_block); let extra = ( frame_system::CheckNonZeroSender::::new(), frame_system::CheckSpecVersion::::new(), frame_system::CheckTxVersion::::new(), frame_system::CheckGenesis::::new(), frame_system::CheckEra::::from(era), frame_system::CheckNonce::::from(nonce), frame_system::CheckWeight::::new(), pallet_transaction_payment::ChargeTransactionPayment::::from(tip), claims::PrevalidateAttests::::new(), ); let raw_payload = SignedPayload::new(call, extra) .map_err(|e| { log::warn!("Unable to create signed payload: {:?}", e); }) .ok()?; let signature = raw_payload .using_encoded(|payload| { C::sign(payload, public) })?; let (call, extra, _) = raw_payload.deconstruct(); let address = ::Lookup::unlookup(account); Some((call, (address, signature.into(), extra))) } } impl frame_system::offchain::SigningTypes for Runtime { type Public = ::Signer; type Signature = Signature; } impl frame_system::offchain::SendTransactionTypes for Runtime where RuntimeCall: From, { type Extrinsic = UncheckedExtrinsic; type OverarchingCall = RuntimeCall; } impl pallet_im_online::Config for Runtime { type AuthorityId = ImOnlineId; type MaxKeys = MaxKeys; type MaxPeerInHeartbeats = MaxPeerInHeartbeats; type MaxPeerDataEncodingSize = MaxPeerDataEncodingSize; type RuntimeEvent = RuntimeEvent; type ValidatorSet = Historical; type NextSessionRotation = Babe; type ReportUnresponsiveness = Offences; type UnsignedPriority = ImOnlineUnsignedPriority; type WeightInfo = weights::pallet_im_online::WeightInfo; } impl pallet_offences::Config for Runtime { type RuntimeEvent = RuntimeEvent; type IdentificationTuple = pallet_session::historical::IdentificationTuple; type OnOffenceHandler = Staking; } impl pallet_authority_discovery::Config for Runtime { type MaxAuthorities = MaxAuthorities; } parameter_types! { pub const MaxSetIdSessionEntries: u32 = BondingDuration::get() * SessionsPerEra::get(); } impl pallet_grandpa::Config for Runtime { type RuntimeEvent = RuntimeEvent; type WeightInfo = (); type MaxAuthorities = MaxAuthorities; type MaxSetIdSessionEntries = MaxSetIdSessionEntries; type KeyOwnerProof = >::Proof; type EquivocationReportSystem = pallet_grandpa::EquivocationReportSystem; } impl pallet_identity::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Currency = Balances; type BasicDeposit = BasicDeposit; type FieldDeposit = FieldDeposit; type SubAccountDeposit = SubAccountDeposit; type MaxSubAccounts = MaxSubAccounts; type MaxAdditionalFields = MaxAdditionalFields; type MaxRegistrars = MaxRegistrars; type Slashed = Treasury; type ForceOrigin = EnsureRootOrHalfCouncil; type RegistrarOrigin = EnsureRootOrHalfCouncil; type WeightInfo = weights::pallet_identity::WeightInfo; } impl pallet_vesting::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Currency = Balances; type BlockNumberToBalance = ConvertInto; type MinVestedTransfer = MinVestedTransfer; type WeightInfo = weights::pallet_vesting::WeightInfo; type UnvestedFundsAllowedWithdrawReasons = UnvestedFundsAllowedWithdrawReasons; const MAX_VESTING_SCHEDULES: u32 = 28; } parameter_types! { pub Prefix: &'static [u8] = b"Pay xx coins to the xx network account:"; } impl claims::Config for Runtime { type RuntimeEvent = RuntimeEvent; type VestingSchedule = Vesting; type Prefix = Prefix; /// Tech committee unanimity can move a claim type MoveClaimOrigin = EnsureTwoThirdsTechnical; type RewardHandler = XXBetanetRewards; type WeightInfo = weights::claims::WeightInfo; } parameter_types! { pub const ChainId: u8 = 0; pub const ProposalLifetime: BlockNumber = 1 * HOURS; pub const BridgePalletId: PalletId = PalletId(*b"cb/bridg"); pub TokenID: chainbridge::ResourceId = chainbridge::derive_resource_id(0, &sha2_256(b"xx coin")); } // Chain Bridge Pallet impl chainbridge::Config for Runtime { type PalletId = BridgePalletId; type RuntimeEvent = RuntimeEvent; type AdminOrigin = EnsureTwoThirdsTechnical; type Proposal = RuntimeCall; type ChainId = ChainId; type ProposalLifetime = ProposalLifetime; } // Swap pallet impl swap::Config for Runtime { type RuntimeEvent = RuntimeEvent; type BridgeOrigin = chainbridge::EnsureBridge; type Currency = Balances; type NativeTokenId = TokenID; type AdminOrigin = EnsureTwoThirdsTechnical; type WeightInfo = weights::swap::WeightInfo; } parameter_types! { pub const BetanetStakingRewardsBlock: BlockNumber = 30 * DAYS; } // xx betanet rewards impl xx_betanet_rewards::Config for Runtime { type RuntimeEvent = RuntimeEvent; type EnactmentBlock = BetanetStakingRewardsBlock; type Reward = XXEconomics; type WeightInfo = weights::xx_betanet_rewards::WeightInfo; } impl pallet_multisig::Config for Runtime { type RuntimeEvent = RuntimeEvent; type RuntimeCall = RuntimeCall; type Currency = Balances; type DepositBase = DepositBase; type DepositFactor = DepositFactor; type MaxSignatories = ConstU32<100>; type WeightInfo = weights::pallet_multisig::WeightInfo; } impl pallet_recovery::Config for Runtime { type RuntimeEvent = RuntimeEvent; type RuntimeCall = RuntimeCall; type Currency = Balances; type ConfigDepositBase = ConfigDepositBase; type FriendDepositFactor = FriendDepositFactor; type MaxFriends = MaxFriends; type RecoveryDeposit = RecoveryDeposit; type WeightInfo = weights::pallet_recovery::WeightInfo; } impl pallet_assets::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Balance = u64; type AssetId = u32; type AssetIdParameter = codec::Compact; type Currency = Balances; type CreateOrigin = AsEnsureOriginWithArg>; type ForceOrigin = EnsureRoot; type AssetDeposit = AssetDeposit; type AssetAccountDeposit = AssetAccountDeposit; type MetadataDepositBase = MetadataDepositBase; type MetadataDepositPerByte = MetadataDepositPerByte; type ApprovalDeposit = ApprovalDeposit; type StringLimit = StringLimit; type Freezer = (); type Extra = (); type CallbackHandle = (); type WeightInfo = weights::pallet_assets::WeightInfo; type RemoveItemsLimit = ConstU32<1000>; #[cfg(feature = "runtime-benchmarks")] type BenchmarkHelper = (); } impl pallet_uniques::Config for Runtime { type RuntimeEvent = RuntimeEvent; type CollectionId = u32; type ItemId = u32; type Currency = Balances; type ForceOrigin = frame_system::EnsureRoot; type CollectionDeposit = CollectionDeposit; type ItemDeposit = ItemDeposit; type MetadataDepositBase = MetadataDepositBase; type AttributeDepositBase = MetadataDepositBase; type DepositPerByte = MetadataDepositPerByte; type StringLimit = StringLimit; type KeyLimit = KeyLimit; type ValueLimit = ValueLimit; type WeightInfo = weights::pallet_uniques::WeightInfo; #[cfg(feature = "runtime-benchmarks")] type Helper = (); type CreateOrigin = AsEnsureOriginWithArg>; type Locker = (); } parameter_types! { pub Features: pallet_nfts::PalletFeatures = pallet_nfts::PalletFeatures::all_enabled(); } impl pallet_nfts::Config for Runtime { type RuntimeEvent = RuntimeEvent; type CollectionId = u32; type ItemId = u32; type Currency = Balances; type ForceOrigin = frame_system::EnsureRoot; type CollectionDeposit = CollectionDeposit; type ItemDeposit = ItemDeposit; type MetadataDepositBase = MetadataDepositBase; type AttributeDepositBase = MetadataDepositBase; type DepositPerByte = MetadataDepositPerByte; type StringLimit = StringLimit; type KeyLimit = KeyLimit; type ValueLimit = ValueLimit; type ApprovalsLimit = ApprovalsLimit; type ItemAttributesApprovalsLimit = ItemAttributesApprovalsLimit; type MaxTips = MaxTips; type MaxDeadlineDuration = MaxDeadlineDuration; type MaxAttributesPerCall = MaxAttributesPerCall; type Features = Features; type OffchainSignature = Signature; type OffchainPublic = ::Signer; type WeightInfo = weights::pallet_nfts::WeightInfo; #[cfg(feature = "runtime-benchmarks")] type Helper = (); type CreateOrigin = AsEnsureOriginWithArg>; type Locker = (); } construct_runtime!( pub enum Runtime where Block = Block, NodeBlock = node_primitives::Block, UncheckedExtrinsic = UncheckedExtrinsic { // System pallets System: frame_system::{Pallet, Call, Config, Storage, Event} = 0, Scheduler: pallet_scheduler::{Pallet, Call, Storage, Event} = 1, // Block production, balances and transaction fees Babe: pallet_babe::{Pallet, Call, Storage, Config, ValidateUnsigned} = 2, Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 3, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event} = 4, TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Event} = 24, // Consensus support: Staking, Block Finality, Sessions and Eras Authorship: pallet_authorship::{Pallet, Storage} = 5, Staking: pallet_staking::{Pallet, Call, Config, Storage, Event} = 6, ElectionProviderMultiPhase: pallet_election_provider_multi_phase::{Pallet, Call, Storage, Event, ValidateUnsigned} = 7, VoterList: pallet_bags_list::{Pallet, Call, Storage, Event} = 41, Offences: pallet_offences::{Pallet, Storage, Event} = 8, Historical: pallet_session_historical::{Pallet} = 25, Session: pallet_session::{Pallet, Call, Storage, Event, Config} = 9, Grandpa: pallet_grandpa::{Pallet, Call, Storage, Config, Event, ValidateUnsigned} = 10, ImOnline: pallet_im_online::{Pallet, Call, Storage, Event, ValidateUnsigned, Config} = 11, AuthorityDiscovery: pallet_authority_discovery::{Pallet, Config} = 12, // Governance Democracy: pallet_democracy::{Pallet, Call, Storage, Config, Event} = 13, Council: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config} = 14, TechnicalCommittee: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config} = 15, Elections: pallet_elections_phragmen::{Pallet, Call, Storage, Event, Config} = 16, TechnicalMembership: pallet_membership::::{Pallet, Call, Storage, Event, Config} = 17, Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event} = 18, // Token Claims Claims: claims::{Pallet, Call, Storage, Event, Config, ValidateUnsigned} = 19, // Vesting Vesting: pallet_vesting::{Pallet, Call, Storage, Event, Config} = 20, // Utilities (for example batch call) Utility: pallet_utility::{Pallet, Call, Event} = 21, // Identity registry Identity: pallet_identity::{Pallet, Call, Storage, Event} = 22, // Proxy (allows setting up proxy accounts) Proxy: pallet_proxy::{Pallet, Call, Storage, Event} = 23, // Bounties Bounties: pallet_bounties::{Pallet, Call, Storage, Event} = 26, // Tips Tips: pallet_tips::{Pallet, Call, Storage, Event} = 27, // Chain Bridge ChainBridge: chainbridge::{Pallet, Call, Storage, Event} = 28, // Swap pallet Swap: swap::{Pallet, Call, Storage, Config, Event} = 29, // xx network pallets XXCmix: xx_cmix::{Pallet, Call, Storage, Config, Event} = 30, XXEconomics: xx_economics::{Pallet, Call, Storage, Config, Event} = 31, XXCustody: xx_team_custody::{Pallet, Call, Storage, Config, Event} = 32, XXBetanetRewards: xx_betanet_rewards::{Pallet, Call, Storage, Config, Event} = 33, XXPublic: xx_public::{Pallet, Call, Storage, Config, Event} = 34, Multisig: pallet_multisig::{Pallet, Call, Storage, Event} = 35, Recovery: pallet_recovery::{Pallet, Call, Storage, Event} = 36, Assets: pallet_assets::{Pallet, Call, Storage, Event, Config} = 37, Uniques: pallet_uniques::{Pallet, Call, Storage, Event} = 38, Preimage: pallet_preimage::{Pallet, Call, Storage, Event} = 39, ChildBounties: pallet_child_bounties = 40, Nfts: pallet_nfts = 42, } ); /// The address format for describing accounts. pub type Address = sp_runtime::MultiAddress; /// Block header type as expected by this runtime. pub type Header = generic::Header; /// Block type as expected by this runtime. pub type Block = generic::Block; /// A Block signed with a Justification pub type SignedBlock = generic::SignedBlock; /// BlockId type as expected by this runtime. pub type BlockId = generic::BlockId; /// The SignedExtension to the basic transaction logic. /// /// When you change this, you **MUST** modify [`sign`] in `bin/node/testing/src/keyring.rs`! /// /// [`sign`]: <../../testing/src/keyring.rs.html> pub type SignedExtra = ( frame_system::CheckNonZeroSender, frame_system::CheckSpecVersion, frame_system::CheckTxVersion, frame_system::CheckGenesis, frame_system::CheckEra, frame_system::CheckNonce, frame_system::CheckWeight, pallet_transaction_payment::ChargeTransactionPayment, claims::PrevalidateAttests, ); /// Unchecked extrinsic type as expected by this runtime. pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; /// The payload being signed in transactions. pub type SignedPayload = generic::SignedPayload; /// Extrinsic type that has already been checked. pub type CheckedExtrinsic = generic::CheckedExtrinsic; /// Executive: handles dispatch to the various modules. pub type Executive = frame_executive::Executive< Runtime, Block, frame_system::ChainContext, Runtime, AllPalletsWithSystem, Migrations, >; parameter_types! { pub const InactiveAccounts: Vec = Vec::new(); } pub type Migrations = ( pallet_staking::migrations::v10::MigrateFromV7dot5ToV10, pallet_staking::migrations::v11::MigrateToV11< Runtime, VoterList, StakingMigrationV11OldPallet, >, pallet_staking::migrations::v12::MigrateToV12, pallet_staking::migrations::v13::MigrateToV13, pallet_preimage::migration::v1::Migration, SchedulerMigrationV2ToV4, pallet_democracy::migrations::v1::Migration, pallet_multisig::migrations::v1::MigrateToV1, pallet_election_provider_multi_phase::migrations::v1::MigrateToV1, pallet_assets::migration::v1::MigrateToV1, pallet_balances::migration::MigrateManyToTrackInactive, // Remove stale entries in the set id -> session index storage map (after // this release they will be properly pruned after the bonding duration has // elapsed) pallet_grandpa::migrations::CleanupSetIdSessionMap, UniquesMigration, // Bridge adjustment BridgeAdjust, ); pub struct StakingMigrationV11OldPallet; impl Get<&'static str> for StakingMigrationV11OldPallet { fn get() -> &'static str { "VoterList" } } // Migration for scheduler pallet to be bounded pub struct SchedulerMigrationV2ToV4; impl OnRuntimeUpgrade for SchedulerMigrationV2ToV4 { fn on_runtime_upgrade() -> Weight { Scheduler::migrate_v2_to_v4() } } // Uniques pallet migration pub struct UniquesMigration; impl OnRuntimeUpgrade for UniquesMigration { fn on_runtime_upgrade() -> Weight { pallet_uniques::migration::migrate_to_v1::() } } #[cfg(feature = "runtime-benchmarks")] #[macro_use] extern crate frame_benchmarking; #[cfg(feature = "runtime-benchmarks")] mod benches { define_benchmarks!( [frame_benchmarking, BaselineBench::] [pallet_assets, Assets] [pallet_bags_list, VoterList] [pallet_balances, Balances] [pallet_bounties, Bounties] [pallet_child_bounties, ChildBounties] [pallet_collective, Council] [pallet_democracy, Democracy] [pallet_election_provider_multi_phase, ElectionProviderMultiPhase] [frame_election_provider_support, EPSBench::] [pallet_elections_phragmen, Elections] [pallet_identity, Identity] [pallet_im_online, ImOnline] [pallet_membership, TechnicalMembership] [pallet_multisig, Multisig] [pallet_offences, OffencesBench::] [pallet_preimage, Preimage] [pallet_proxy, Proxy] [pallet_recovery, Recovery] [pallet_scheduler, Scheduler] [pallet_session, SessionBench::] [pallet_staking, Staking] [frame_system, SystemBench::] [pallet_timestamp, Timestamp] [pallet_tips, Tips] [pallet_treasury, Treasury] [pallet_uniques, Uniques] [pallet_nfts, Nfts] [pallet_utility, Utility] [pallet_vesting, Vesting] // xx network [claims, Claims] [swap, Swap] [xx_cmix, XXCmix] [xx_public, XXPublic] [xx_team_custody, XXCustody] [xx_economics, XXEconomics] [xx_betanet_rewards, XXBetanetRewards] ); } impl_runtime_apis! { impl sp_api::Core for Runtime { fn version() -> RuntimeVersion { VERSION } fn execute_block(block: Block) { Executive::execute_block(block); } fn initialize_block(header: &::Header) { Executive::initialize_block(header) } } impl sp_api::Metadata for Runtime { fn metadata() -> OpaqueMetadata { OpaqueMetadata::new(Runtime::metadata().into()) } } impl sp_block_builder::BlockBuilder for Runtime { fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { Executive::apply_extrinsic(extrinsic) } fn finalize_block() -> ::Header { Executive::finalize_block() } fn inherent_extrinsics(data: InherentData) -> Vec<::Extrinsic> { data.create_extrinsics() } fn check_inherents(block: Block, data: InherentData) -> CheckInherentsResult { data.check_extrinsics(&block) } } impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { fn validate_transaction( source: TransactionSource, tx: ::Extrinsic, block_hash: ::Hash, ) -> TransactionValidity { Executive::validate_transaction(source, tx, block_hash) } } impl sp_offchain::OffchainWorkerApi for Runtime { fn offchain_worker(header: &::Header) { Executive::offchain_worker(header) } } impl fg_primitives::GrandpaApi for Runtime { fn grandpa_authorities() -> GrandpaAuthorityList { Grandpa::grandpa_authorities() } fn current_set_id() -> fg_primitives::SetId { Grandpa::current_set_id() } fn submit_report_equivocation_unsigned_extrinsic( equivocation_proof: fg_primitives::EquivocationProof< ::Hash, NumberFor, >, key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof, ) -> Option<()> { let key_owner_proof = key_owner_proof.decode()?; Grandpa::submit_unsigned_equivocation_report( equivocation_proof, key_owner_proof, ) } fn generate_key_ownership_proof( _set_id: fg_primitives::SetId, authority_id: GrandpaId, ) -> Option { use codec::Encode; Historical::prove((fg_primitives::KEY_TYPE, authority_id)) .map(|p| p.encode()) .map(fg_primitives::OpaqueKeyOwnershipProof::new) } } impl sp_consensus_babe::BabeApi for Runtime { fn configuration() -> sp_consensus_babe::BabeConfiguration { let epoch_config = Babe::epoch_config().unwrap_or(BABE_GENESIS_EPOCH_CONFIG); sp_consensus_babe::BabeConfiguration { slot_duration: Babe::slot_duration(), epoch_length: EpochDuration::get(), c: epoch_config.c, authorities: Babe::authorities().to_vec(), randomness: Babe::randomness(), allowed_slots: epoch_config.allowed_slots, } } fn current_epoch_start() -> sp_consensus_babe::Slot { Babe::current_epoch_start() } fn current_epoch() -> sp_consensus_babe::Epoch { Babe::current_epoch() } fn next_epoch() -> sp_consensus_babe::Epoch { Babe::next_epoch() } fn generate_key_ownership_proof( _slot: sp_consensus_babe::Slot, authority_id: sp_consensus_babe::AuthorityId, ) -> Option { use codec::Encode; Historical::prove((sp_consensus_babe::KEY_TYPE, authority_id)) .map(|p| p.encode()) .map(sp_consensus_babe::OpaqueKeyOwnershipProof::new) } fn submit_report_equivocation_unsigned_extrinsic( equivocation_proof: sp_consensus_babe::EquivocationProof<::Header>, key_owner_proof: sp_consensus_babe::OpaqueKeyOwnershipProof, ) -> Option<()> { let key_owner_proof = key_owner_proof.decode()?; Babe::submit_unsigned_equivocation_report( equivocation_proof, key_owner_proof, ) } } impl sp_authority_discovery::AuthorityDiscoveryApi for Runtime { fn authorities() -> Vec { AuthorityDiscovery::authorities() } } impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { fn account_nonce(account: AccountId) -> Index { System::account_nonce(account) } } impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi< Block, Balance, > for Runtime { fn query_info(uxt: ::Extrinsic, len: u32) -> RuntimeDispatchInfo { TransactionPayment::query_info(uxt, len) } fn query_fee_details(uxt: ::Extrinsic, len: u32) -> FeeDetails { TransactionPayment::query_fee_details(uxt, len) } fn query_weight_to_fee(weight: Weight) -> Balance { TransactionPayment::weight_to_fee(weight) } fn query_length_to_fee(length: u32) -> Balance { TransactionPayment::length_to_fee(length) } } impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi for Runtime { fn query_call_info(call: RuntimeCall, len: u32) -> RuntimeDispatchInfo { TransactionPayment::query_call_info(call, len) } fn query_call_fee_details(call: RuntimeCall, len: u32) -> FeeDetails { TransactionPayment::query_call_fee_details(call, len) } fn query_weight_to_fee(weight: Weight) -> Balance { TransactionPayment::weight_to_fee(weight) } fn query_length_to_fee(length: u32) -> Balance { TransactionPayment::length_to_fee(length) } } impl pallet_nfts_runtime_api::NftsApi for Runtime { fn owner(collection: u32, item: u32) -> Option { >::owner(&collection, &item) } fn collection_owner(collection: u32) -> Option { >::collection_owner(&collection) } fn attribute( collection: u32, item: u32, key: Vec, ) -> Option> { >::attribute(&collection, &item, &key) } fn custom_attribute( account: AccountId, collection: u32, item: u32, key: Vec, ) -> Option> { >::custom_attribute( &account, &collection, &item, &key, ) } fn system_attribute( collection: u32, item: u32, key: Vec, ) -> Option> { >::system_attribute(&collection, &item, &key) } fn collection_attribute(collection: u32, key: Vec) -> Option> { >::collection_attribute(&collection, &key) } } impl sp_session::SessionKeys for Runtime { fn generate_session_keys(seed: Option>) -> Vec { SessionKeys::generate(seed) } fn decode_session_keys( encoded: Vec, ) -> Option, KeyTypeId)>> { SessionKeys::decode_into_raw_public_keys(&encoded) } } #[cfg(feature = "try-runtime")] impl frame_try_runtime::TryRuntime for Runtime { fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) { // NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to // have a backtrace here. If any of the pre/post migration checks fail, we shall stop // right here and right now. let weight = Executive::try_runtime_upgrade(checks).unwrap(); (weight, BlockWeights::get().max_block) } fn execute_block( block: Block, state_root_check: bool, signature_check: bool, select: frame_try_runtime::TryStateSelect ) -> Weight { // NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to // have a backtrace here. Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap() } } #[cfg(feature = "runtime-benchmarks")] impl frame_benchmarking::Benchmark for Runtime { fn benchmark_metadata(extra: bool) -> ( Vec, Vec, ) { use frame_benchmarking::{baseline, Benchmarking, BenchmarkList}; use frame_support::traits::StorageInfoTrait; use pallet_session_benchmarking::Pallet as SessionBench; use pallet_offences_benchmarking::Pallet as OffencesBench; use pallet_election_provider_support_benchmarking::Pallet as EPSBench; use frame_system_benchmarking::Pallet as SystemBench; use baseline::Pallet as BaselineBench; let mut list = Vec::::new(); list_benchmarks!(list, extra); let storage_info = AllPalletsWithSystem::storage_info(); return (list, storage_info) } fn dispatch_benchmark( config: frame_benchmarking::BenchmarkConfig ) -> Result, sp_runtime::RuntimeString> { use frame_benchmarking::{baseline, Benchmarking, BenchmarkBatch, TrackedStorageKey}; use pallet_session_benchmarking::Pallet as SessionBench; use pallet_offences_benchmarking::Pallet as OffencesBench; use pallet_election_provider_support_benchmarking::Pallet as EPSBench; use frame_system_benchmarking::Pallet as SystemBench; use baseline::Pallet as BaselineBench; impl pallet_session_benchmarking::Config for Runtime {} impl pallet_offences_benchmarking::Config for Runtime {} impl pallet_election_provider_support_benchmarking::Config for Runtime {} impl frame_system_benchmarking::Config for Runtime {} impl baseline::Config for Runtime {} use frame_support::traits::WhitelistedStorageKeys; let mut whitelist: Vec = AllPalletsWithSystem::whitelisted_storage_keys(); let treasury_key = frame_system::Account::::hashed_key_for(Treasury::account_id()); whitelist.push(treasury_key.to_vec().into()); let mut batches = Vec::::new(); let params = (&config, &whitelist); add_benchmarks!(params, batches); Ok(batches) } } } #[cfg(test)] mod tests { use super::*; use frame_system::offchain::CreateSignedTransaction; #[test] fn validate_transaction_submitter_bounds() { fn is_submit_signed_transaction() where T: CreateSignedTransaction, {} is_submit_signed_transaction::(); } }