#![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"] #![allow(clippy::type_complexity)] #![allow(clippy::large_enum_variant)] #![allow(clippy::upper_case_acronyms)] #![allow(clippy::from_over_into)] // Make the WASM binary available. #[cfg(feature = "std")] include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); use pallet_grandpa::fg_primitives; use pallet_grandpa::{AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList}; use sp_api::impl_runtime_apis; use sp_authority_discovery::AuthorityId as AuthorityDiscoveryId; use sp_core::{ crypto::KeyTypeId, u32_trait::{_2, _3, _4}, OpaqueMetadata, }; use sp_runtime::traits::{ BlakeTwo256, Block as BlockT, IdentifyAccount, IdentityLookup, NumberFor, OpaqueKeys, Verify, }; use sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, traits::Zero, transaction_validity::{TransactionPriority, TransactionSource, TransactionValidity}, ApplyExtrinsicResult, ModuleId, MultiSignature, Percent, }; use sp_std::prelude::*; #[cfg(feature = "std")] use sp_version::NativeVersion; use sp_version::RuntimeVersion; use frame_system::{limits}; // A few exports that help ease life for downstream crates. pub use frame_support::{ construct_runtime, parameter_types, traits::{Filter, KeyOwnerProofSystem, LockIdentifier, Randomness, U128CurrencyToVote}, weights::{ constants::{BlockExecutionWeight, RocksDbWeight, WEIGHT_PER_SECOND}, DispatchClass, IdentityFee, Pays, Weight, }, StorageValue, }; pub use pallet_balances::Call as BalancesCall; pub use pallet_timestamp::Call as TimestampCall; #[cfg(any(feature = "std", test))] pub use sp_runtime::BuildStorage; pub use sp_runtime::{Perbill, Permill}; use frame_system::{EnsureOneOf, EnsureRoot}; use sp_runtime::curve::PiecewiseLinear; use pallet_session::historical as session_historical; use module_amm_rpc_runtime_api as amm_rpc; use orml_currencies::BasicCurrencyAdapter; use orml_traits::parameter_type_with_key; pub use primitives::{Amount, AssetId, Balance, Moment, CORE_ASSET_ID}; /// Import HydraDX pallets pub use pallet_asset_registry; pub use pallet_claims; pub use pallet_faucet; use pallet_transaction_multi_payment::{weights::WeightInfo, MultiCurrencyAdapter}; /// An index to a block. pub type BlockNumber = u32; /// Alias to 512-bit hash when used in the context of a transaction signature on the chain. pub type Signature = MultiSignature; /// Some way of identifying an account on the chain. We intentionally make it equivalent /// to the public key of our transaction signing scheme. pub type AccountId = <::Signer as IdentifyAccount>::AccountId; /// The type for looking up accounts. We don't expect more than 4 billion of them, but you /// never know... pub type AccountIndex = u32; /// Index of a transaction in the chain. pub type Index = u32; /// A hash of some data used by the chain. pub type Hash = sp_core::H256; /// Digest item type. pub type DigestItem = generic::DigestItem; /// Opaque types. These are used by the CLI to instantiate machinery that don't need to know /// the specifics of the runtime. They can then be made to be agnostic over specific formats /// of data like extrinsics, allowing for them to continue syncing the network through upgrades /// to even the core data structures. pub mod opaque { use super::*; pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic; /// Opaque block header type. pub type Header = generic::Header; /// Opaque block type. pub type Block = generic::Block; /// Opaque block identifier type. pub type BlockId = generic::BlockId; impl_opaque_keys! { pub struct SessionKeys { pub grandpa: Grandpa, pub babe: Babe, pub im_online: ImOnline, pub authority_discovery: AuthorityDiscovery, } } } impl_opaque_keys! { pub struct SessionKeys { pub grandpa: Grandpa, pub babe: Babe, pub im_online: ImOnline, pub authority_discovery: AuthorityDiscovery, } } pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("hydra-dx"), impl_name: create_runtime_str!("hydra-dx"), authoring_version: 1, spec_version: 3, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 1, }; /// We assume that an on-initialize consumes 2.5% of the weight on average, hence a single extrinsic /// will not be allowed to consume more than `AvailableBlockRatio - 2.5%`. pub const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_perthousand(25); /// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used /// by Operational extrinsics. const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75); /// We allow for 2 seconds of compute with a 6 second average block time. pub const MAXIMUM_BLOCK_WEIGHT: Weight = 2 * WEIGHT_PER_SECOND; /// The version information used to identify this runtime when compiled natively. #[cfg(feature = "std")] pub fn native_version() -> NativeVersion { NativeVersion { runtime_version: VERSION, can_author_with: Default::default(), } } pub struct BaseFilter; impl Filter for BaseFilter { fn filter(call: &Call) -> bool { match call { Call::Council(_) | Call::Faucet(_) | Call::Balances(_) | Call::Currencies(_) | Call::Tokens(_) | Call::AssetRegistry(_) | Call::Offences(_) | Call::AMM(_) | Call::MultiTransactionPayment(_) | Call::Exchange(_) => false, Call::System(_) | Call::RandomnessCollectiveFlip(_) | Call::Claims(_) | Call::Elections(_) | Call::Babe(_) | Call::Treasury(_) | Call::Tips(_) | Call::Timestamp(_) | Call::Authorship(_) | Call::Staking(_) | Call::Session(_) | Call::Grandpa(_) | Call::AuthorityDiscovery(_) | Call::ImOnline(_) | Call::ElectionProviderMultiPhase(_) | Call::Scheduler(_) | Call::Sudo(_) => true, } } } parameter_types! { pub const BlockHashCount: BlockNumber = 2400; pub const Version: RuntimeVersion = VERSION; /// Maximum length of block. Up to 5MB. pub BlockLength: limits::BlockLength = limits::BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO); /// Block weights base values and limits. pub BlockWeights: limits::BlockWeights = limits::BlockWeights::builder() .base_block(BlockExecutionWeight::get()) .for_class(DispatchClass::all(), |weights| { weights.base_extrinsic = ExtrinsicBaseWeight::get(); }) .for_class(DispatchClass::Normal, |weights| { weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT); }) .for_class(DispatchClass::Operational, |weights| { weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT); // Operational transactions have an extra reserved space, so that they // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`. weights.reserved = Some( MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT, ); }) .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO) .build_or_panic(); pub ExtrinsicPaymentExtraWeight: Weight = ::WeightInfo::swap_currency(); pub ExtrinsicBaseWeight: Weight = frame_support::weights::constants::ExtrinsicBaseWeight::get() + ExtrinsicPaymentExtraWeight::get(); pub const SS58Prefix: u8 = 63; } // Configure FRAME pallets to include in runtime. impl frame_system::Config for Runtime { /// The basic call filter to use in dispatchable. type BaseCallFilter = BaseFilter; /// The identifier used to distinguish between accounts. type AccountId = AccountId; /// The aggregated dispatch type that is available for extrinsics. type Call = Call; /// The lookup mechanism to get account ID from whatever is passed in dispatchers. type Lookup = IdentityLookup; /// The index type for storing how many extrinsics an account has signed. type Index = Index; /// The index type for blocks. type BlockNumber = BlockNumber; /// The type for hashing blocks and tries. type Hash = Hash; /// The hashing algorithm used. type Hashing = BlakeTwo256; /// The header type. type Header = generic::Header; /// The ubiquitous event type. type Event = Event; /// The ubiquitous origin type. type Origin = Origin; /// Maximum number of block number to block hash mappings to keep (oldest pruned first). type BlockHashCount = BlockHashCount; type BlockWeights = BlockWeights; type BlockLength = BlockLength; /// The weight of database operations that the runtime can invoke. type DbWeight = RocksDbWeight; /// The weight of the overhead invoked on the block import process, independent of the /// extrinsics included in that block. /// Version of the runtime. type Version = Version; /// Converts a module to the index of the module in `construct_runtime!`. /// /// This type is being generated by `construct_runtime!`. type PalletInfo = PalletInfo; /// What to do if a new account is created. type OnNewAccount = (); /// What to do if an account is fully reaped from the system. type OnKilledAccount = (); /// The data to be stored in an account. type AccountData = pallet_balances::AccountData; /// Weight information for the extrinsics of this pallet. type SystemWeightInfo = (); type SS58Prefix = SS58Prefix; } impl pallet_grandpa::Config for Runtime { type Event = Event; type Call = Call; type KeyOwnerProofSystem = (); type KeyOwnerProof = >::Proof; type KeyOwnerIdentification = >::IdentificationTuple; type HandleEquivocation = (); type WeightInfo = (); } parameter_types! { pub const MinimumPeriod: u64 = SLOT_DURATION / 2; pub const HDXAssetId: AssetId = CORE_ASSET_ID; } impl pallet_timestamp::Config for Runtime { /// A timestamp: milliseconds since the unix epoch. type Moment = u64; type OnTimestampSet = Babe; type MinimumPeriod = MinimumPeriod; type WeightInfo = (); } parameter_types! { pub const ExistentialDeposit: u128 = 0; pub const MaxLocks: u32 = 50; } impl pallet_balances::Config for Runtime { type MaxLocks = MaxLocks; /// The type for recording an account's balance. type Balance = Balance; /// The ubiquitous event type. type Event = Event; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; type WeightInfo = (); } parameter_types! { pub const TransactionByteFee: Balance = 1; pub const MultiPaymentCurrencySetFee: Pays = Pays::No; } impl pallet_transaction_payment::Config for Runtime { type OnChargeTransaction = MultiCurrencyAdapter; type TransactionByteFee = TransactionByteFee; type WeightToFee = IdentityFee; type FeeMultiplierUpdate = (); } impl pallet_transaction_multi_payment::Config for Runtime { type Event = Event; type Currency = Balances; type MultiCurrency = Currencies; type AMMPool = AMM; type WeightInfo = pallet_transaction_multi_payment::weights::HydraWeight; type WithdrawFeeForSetCurrency = MultiPaymentCurrencySetFee; type WeightToFee = IdentityFee; } impl pallet_sudo::Config for Runtime { type Event = Event; type Call = Call; } parameter_type_with_key! { pub ExistentialDeposits: |_currency_id: AssetId| -> Balance { Zero::zero() }; } /// ORML Configurations impl orml_tokens::Config for Runtime { type Event = Event; type Balance = Balance; type Amount = Amount; type CurrencyId = AssetId; type WeightInfo = (); type ExistentialDeposits = ExistentialDeposits; type OnDust = (); } impl orml_currencies::Config for Runtime { type Event = Event; type MultiCurrency = Tokens; type NativeCurrency = BasicCurrencyAdapter; type GetNativeCurrencyId = HDXAssetId; type WeightInfo = (); } /// HydraDX Pallets configurations impl pallet_asset_registry::Config for Runtime { type AssetId = AssetId; } parameter_types! { pub ExchangeFee: fee::Fee = fee::Fee::default(); } impl pallet_amm::Config for Runtime { type Event = Event; type AssetPairAccountId = pallet_amm::AssetPairAccountId; type Currency = Currencies; type HDXAssetId = HDXAssetId; type WeightInfo = pallet_amm::weights::HydraWeight; type GetExchangeFee = ExchangeFee; } parameter_types! { pub ClaimMessagePrefix: &'static [u8] = b"I hereby claim all my HDX tokens to wallet:"; } impl pallet_claims::Config for Runtime { type Event = Event; type Currency = Balances; type Prefix = ClaimMessagePrefix; type WeightInfo = pallet_claims::weights::HackHydraWeight; type CurrencyBalance = Balance; } impl pallet_exchange::Config for Runtime { type Event = Event; type AMMPool = AMM; type Resolver = Exchange; type Currency = Currencies; type WeightInfo = pallet_exchange::weights::HydraWeight; } impl pallet_faucet::Config for Runtime { type Event = Event; type Currency = Currencies; } pub mod constants; /// Staking pallets configurations pub mod impls; use constants::{currency::*, time::*}; use pallet_im_online::sr25519::AuthorityId as ImOnlineId; pub use pallet_staking::StakerStatus; use primitives::fee; parameter_types! { pub const UncleGenerations: BlockNumber = 5; } impl pallet_authorship::Config for Runtime { type FindAuthor = pallet_session::FindAccountFromAuthorIndex; type UncleGenerations = UncleGenerations; type FilterUncle = (); type EventHandler = (Staking, ImOnline); } pallet_staking_reward_curve::build! { const REWARD_CURVE: PiecewiseLinear<'static> = curve!( min_inflation: 0_040_000, max_inflation: 0_120_000, ideal_stake: 0_900_000, falloff: 1_000_000, max_piece_count: 40, test_precision: 0_005_000, ); } parameter_types! { pub const SessionsPerEra: sp_staking::SessionIndex = 6; pub const BondingDuration: pallet_staking::EraIndex = 24 * 28; pub const SlashDeferDuration: pallet_staking::EraIndex = 24 * 7; // 1/4 the bonding duration. pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE; pub const MaxNominatorRewardedPerValidator: u32 = 64; pub const ElectionLookahead: BlockNumber = EPOCH_DURATION_IN_BLOCKS / 4; pub const MaxIterations: u32 = 10; // 0.05%. The higher the value, the more strict solution acceptance becomes. pub MinSolutionScoreBump: Perbill = Perbill::from_rational_approximation(5u32, 10_000); } impl pallet_staking::Config for Runtime { type Currency = Balances; type UnixTime = Timestamp; type CurrencyToVote = U128CurrencyToVote; type ElectionProvider = ElectionProviderMultiPhase; type RewardRemainder = Treasury; type Event = Event; type Slash = Treasury; type Reward = (); type SessionsPerEra = SessionsPerEra; type BondingDuration = BondingDuration; type SlashDeferDuration = SlashDeferDuration; // A super-majority of the council can cancel the slash. type SlashCancelOrigin = pallet_collective::EnsureProportionAtLeast<_3, _4, AccountId, CouncilCollective>; type SessionInterface = Self; type RewardCurve = RewardCurve; type NextNewSession = Session; type ElectionLookahead = ElectionLookahead; type Call = Call; type MaxIterations = MaxIterations; type MinSolutionScoreBump = MinSolutionScoreBump; type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator; type UnsignedPriority = StakingUnsignedPriority; type OffchainSolutionWeightLimit = OffchainSolutionWeightLimit; type WeightInfo = (); } 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; // fallback: no need to do on-chain phragmen initially. 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; pub MinerMaxWeight: Weight = BlockWeights::get() .get(DispatchClass::Normal) .max_extrinsic.expect("Normal extrinsics have a weight limit configured; qed") .saturating_sub(BlockExecutionWeight::get()); } 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 = MinerMaxWeight; 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; type BenchmarkingConfig = (); } parameter_types! { pub const ProposalBond: Permill = Permill::from_percent(5); pub const ProposalBondMinimum: Balance = DOLLARS; pub const SpendPeriod: BlockNumber = DAYS; pub const Burn: Permill = Permill::from_percent(50); pub const DataDepositPerByte: Balance = CENTS; pub const TipCountdown: BlockNumber = DAYS; pub const TipFindersFee: Percent = Percent::from_percent(20); pub const TipReportDepositBase: Balance = DOLLARS; pub const TipReportDepositPerByte: Balance = CENTS; pub const MaximumReasonLength: u32 = 16384; pub const TreasuryModuleId: ModuleId = ModuleId(*b"py/trsry"); pub OffchainSolutionWeightLimit: Weight = BlockWeights::get().max_block .saturating_sub(BlockExecutionWeight::get()) .saturating_sub(ExtrinsicBaseWeight::get()); } impl pallet_treasury::Config for Runtime { type ModuleId = TreasuryModuleId; type Currency = Balances; type ApproveOrigin = EnsureOneOf< AccountId, EnsureRoot, pallet_collective::EnsureMembers<_4, AccountId, CouncilCollective>, >; type RejectOrigin = EnsureOneOf< AccountId, EnsureRoot, pallet_collective::EnsureMembers<_2, AccountId, CouncilCollective>, >; //type TipReportDepositPerByte = TipReportDepositPerByte; type Event = Event; type OnSlash = (); //type ProposalRejection = (); type ProposalBond = ProposalBond; type ProposalBondMinimum = ProposalBondMinimum; type SpendPeriod = SpendPeriod; type Burn = Burn; type BurnDestination = (); type WeightInfo = (); type SpendFunds = (); } impl pallet_tips::Config for Runtime { type Event = Event; type DataDepositPerByte = DataDepositPerByte; type MaximumReasonLength = MaximumReasonLength; type Tippers = Elections; type TipCountdown = TipCountdown; type TipFindersFee = TipFindersFee; type TipReportDepositBase = TipReportDepositBase; type WeightInfo = (); } parameter_types! { pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(17); } impl pallet_session::Config for Runtime { type Event = Event; 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 = opaque::SessionKeys; type DisabledValidatorsThreshold = DisabledValidatorsThreshold; type WeightInfo = (); } impl pallet_session::historical::Config for Runtime { type FullIdentification = pallet_staking::Exposure; type FullIdentificationOf = pallet_staking::ExposureOf; } parameter_types! { pub const CandidacyBond: Balance = 10 * DOLLARS; pub const VotingBond: Balance = DOLLARS; pub const TermDuration: BlockNumber = 7 * DAYS; pub const DesiredMembers: u32 = 13; pub const DesiredRunnersUp: u32 = 7; pub const ElectionsPhragmenModuleId: LockIdentifier = *b"phrelect"; } impl pallet_elections_phragmen::Config for Runtime { type Event = Event; type ModuleId = ElectionsPhragmenModuleId; 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 = (); type VotingBondFactor = (); type LoserCandidate = (); type KickedMember = (); type DesiredMembers = DesiredMembers; type DesiredRunnersUp = DesiredRunnersUp; type TermDuration = TermDuration; type WeightInfo = (); } parameter_types! { 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 KeyOwnerProofSystem = Historical; type KeyOwnerProof = >::Proof; type KeyOwnerIdentification = >::IdentificationTuple; type HandleEquivocation = pallet_babe::EquivocationHandler; type WeightInfo = (); } parameter_types! { pub const CouncilMotionDuration: BlockNumber = 5 * DAYS; pub const CouncilMaxProposals: u32 = 100; pub const ProposalVotesRequired: u32 = 3; pub const ProposalMininumDeposit: Balance = 0; } type CouncilCollective = pallet_collective::Instance1; impl pallet_collective::Config for Runtime { type Origin = Origin; type Proposal = Call; type Event = Event; type MotionDuration = CouncilMotionDuration; type MaxProposals = CouncilMaxProposals; type MaxMembers = (); type DefaultVote = pallet_collective::PrimeDefaultVote; type WeightInfo = (); } impl pallet_authority_discovery::Config for Runtime {} parameter_types! { pub const SessionDuration: BlockNumber = EPOCH_DURATION_IN_SLOTS as _; pub const ImOnlineUnsignedPriority: TransactionPriority = TransactionPriority::max_value(); /// We prioritize im-online heartbeats over election solution submission. pub const StakingUnsignedPriority: TransactionPriority = TransactionPriority::max_value() / 2; } impl frame_system::offchain::SendTransactionTypes for Runtime where Call: From, { type Extrinsic = UncheckedExtrinsic; type OverarchingCall = Call; } impl pallet_im_online::Config for Runtime { type AuthorityId = ImOnlineId; type Event = Event; type SessionDuration = SessionDuration; type ValidatorSet = Historical; type ReportUnresponsiveness = Offences; type UnsignedPriority = ImOnlineUnsignedPriority; type WeightInfo = (); } parameter_types! { pub OffencesWeightSoftLimit: Weight = Perbill::from_percent(60) * BlockWeights::get().max_block; } impl pallet_offences::Config for Runtime { type Event = Event; type IdentificationTuple = pallet_session::historical::IdentificationTuple; type OnOffenceHandler = Staking; type WeightSoftLimit = OffencesWeightSoftLimit; } parameter_types! { pub MaximumSchedulerWeight: Weight = Perbill::from_percent(10) * BlockWeights::get().max_block; pub const MaxScheduledPerBlock: u32 = 50; } impl pallet_scheduler::Config for Runtime { type Event = Event; type Origin = Origin; type PalletsOrigin = OriginCaller; type Call = Call; type MaximumWeight = MaximumSchedulerWeight; type ScheduleOrigin = EnsureRoot; type MaxScheduledPerBlock = MaxScheduledPerBlock; type WeightInfo = (); } // Create the runtime by composing the FRAME pallets that were previously configured. construct_runtime!( pub enum Runtime where Block = Block, NodeBlock = opaque::Block, UncheckedExtrinsic = UncheckedExtrinsic { System: frame_system::{Module, Call, Config, Storage, Event}, RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Module, Call, Storage}, Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent}, Grandpa: pallet_grandpa::{Module, Call, Storage, Config, Event}, Balances: pallet_balances::{Module, Call, Storage, Config, Event}, TransactionPayment: pallet_transaction_payment::{Module, Storage}, Sudo: pallet_sudo::{Module, Call, Config, Storage, Event}, Scheduler: pallet_scheduler::{Module, Call, Storage, Event}, //Staking related modules Authorship: pallet_authorship::{Module, Call, Storage, Inherent}, Staking: pallet_staking::{Module, Call, Config, Storage, Event, ValidateUnsigned}, ElectionProviderMultiPhase: pallet_election_provider_multi_phase::{Module, Call, Storage, Event, ValidateUnsigned}, Treasury: pallet_treasury::{Module, Call, Storage, Config, Event}, Babe: pallet_babe::{Module, Call, Storage, Config, ValidateUnsigned}, Session: pallet_session::{Module, Call, Storage, Event, Config}, Elections: pallet_elections_phragmen::{Module, Call, Storage, Event, Config}, Council: pallet_collective::::{Module, Call, Storage, Origin, Event, Config}, AuthorityDiscovery: pallet_authority_discovery::{Module, Call, Config}, ImOnline: pallet_im_online::{Module, Call, Storage, Event, ValidateUnsigned, Config}, Offences: pallet_offences::{Module, Call, Storage, Event}, Historical: session_historical::{Module}, Tips: pallet_tips::{Module, Call, Storage, Event}, // ORML related modules Tokens: orml_tokens::{Module, Storage, Call, Event, Config}, Currencies: orml_currencies::{Module, Call, Event}, // HydraDX related modules AssetRegistry: pallet_asset_registry::{Module, Call, Storage, Config}, AMM: pallet_amm::{Module, Call, Storage, Event}, Claims: pallet_claims::{Module, Call, Storage, Event, Config}, Exchange: pallet_exchange::{Module, Call, Storage, Event}, Faucet: pallet_faucet::{Module, Call, Storage, Config, Event}, MultiTransactionPayment: pallet_transaction_multi_payment::{Module, Call, Storage, Event}, } ); /// The address format for describing accounts. pub type Address = AccountId; /// 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. pub type SignedExtra = ( frame_system::CheckSpecVersion, frame_system::CheckTxVersion, frame_system::CheckGenesis, frame_system::CheckEra, frame_system::CheckNonce, frame_system::CheckWeight, pallet_transaction_payment::ChargeTransactionPayment, pallet_claims::ValidateClaim, ); /// Unchecked extrinsic type as expected by this runtime. pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; /// 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, AllModules>; impl_runtime_apis! { impl sp_consensus_babe::BabeApi for Runtime { fn configuration() -> sp_consensus_babe::BabeGenesisConfiguration { // 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. // sp_consensus_babe::BabeGenesisConfiguration { slot_duration: Babe::slot_duration(), epoch_length: EpochDuration::get(), c: PRIMARY_PROBABILITY, genesis_authorities: Babe::authorities(), randomness: Babe::randomness(), allowed_slots: sp_consensus_babe::AllowedSlots::PrimaryAndSecondaryPlainSlots, } } 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_number: 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 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 { 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: sp_inherents::InherentData) -> Vec<::Extrinsic> { data.create_extrinsics() } fn check_inherents( block: Block, data: sp_inherents::InherentData, ) -> sp_inherents::CheckInherentsResult { data.check_extrinsics(&block) } fn random_seed() -> ::Hash { RandomnessCollectiveFlip::random_seed() } } impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { fn validate_transaction( source: TransactionSource, tx: ::Extrinsic, ) -> TransactionValidity { Executive::validate_transaction(source, tx) } } impl sp_offchain::OffchainWorkerApi for Runtime { fn offchain_worker(header: &::Header) { Executive::offchain_worker(header) } } impl sp_session::SessionKeys for Runtime { fn generate_session_keys(seed: Option>) -> Vec { opaque::SessionKeys::generate(seed) } fn decode_session_keys( encoded: Vec, ) -> Option, KeyTypeId)>> { opaque::SessionKeys::decode_into_raw_public_keys(&encoded) } } impl fg_primitives::GrandpaApi for Runtime { fn grandpa_authorities() -> GrandpaAuthorityList { Grandpa::grandpa_authorities() } fn submit_report_equivocation_unsigned_extrinsic( _equivocation_proof: fg_primitives::EquivocationProof< ::Hash, NumberFor, >, _key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof, ) -> Option<()> { None } fn generate_key_ownership_proof( _set_id: fg_primitives::SetId, _authority_id: GrandpaId, ) -> Option { // NOTE: this is the only implementation possible since we've // defined our key owner proof type as a bottom type (i.e. a type // with no values). None } } 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 for Runtime { fn query_info( uxt: ::Extrinsic, len: u32, ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo { TransactionPayment::query_info(uxt, len) } fn query_fee_details(uxt: ::Extrinsic, len: u32) -> pallet_transaction_payment_rpc_runtime_api::FeeDetails { TransactionPayment::query_fee_details(uxt, len) } } impl amm_rpc::AMMApi< Block, AccountId, AssetId, Balance, > for Runtime { fn get_pool_balances( pool_address: AccountId, ) -> Vec> { let mut vec = Vec::new(); let pool_balances = AMM::get_pool_balances(pool_address).unwrap(); for b in pool_balances { let item = amm_rpc::BalanceInfo{ asset: Some(b.0), amount: b.1 }; vec.push(item); } vec } } #[cfg(feature = "runtime-benchmarks")] impl frame_benchmarking::Benchmark for Runtime { fn dispatch_benchmark( config: frame_benchmarking::BenchmarkConfig ) -> Result, sp_runtime::RuntimeString> { use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey}; use pallet_exchange_benchmarking::Module as ExchangeBench; use frame_system_benchmarking::Module as SystemBench; use pallet_multi_payment_benchmarking::Module as MultiBench; impl frame_system_benchmarking::Config for Runtime {} impl pallet_exchange_benchmarking::Config for Runtime {} impl pallet_multi_payment_benchmarking::Config for Runtime {} let whitelist: Vec = vec![ // Block Number hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(), // Total Issuance hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(), // Execution Phase hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(), // Event Count hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(), // System Events hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(), ]; let mut batches = Vec::::new(); let params = (&config, &whitelist); add_benchmark!(params, batches, amm, AMM); add_benchmark!(params, batches, claims, Claims); add_benchmark!(params, batches, transaction_multi_payment, MultiBench::); add_benchmark!(params, batches, frame_system, SystemBench::); add_benchmark!(params, batches, exchange, ExchangeBench::); add_benchmark!(params, batches, pallet_balances, Balances); add_benchmark!(params, batches, pallet_timestamp, Timestamp); if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) } Ok(batches) } } }