subspace_runtime/
lib.rs

1#![cfg_attr(not(feature = "std"), no_std)]
2#![feature(const_trait_impl, variant_count)]
3// `generic_const_exprs` is an incomplete feature
4#![allow(incomplete_features)]
5// TODO: This feature is not actually used in this crate, but is added as a workaround for
6//  https://github.com/rust-lang/rust/issues/133199
7#![feature(generic_const_exprs)]
8// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
9#![recursion_limit = "256"]
10// TODO: remove when upstream issue is fixed
11#![allow(
12    non_camel_case_types,
13    reason = "https://github.com/rust-lang/rust-analyzer/issues/16514"
14)]
15
16mod domains;
17mod fees;
18mod object_mapping;
19mod weights;
20
21extern crate alloc;
22
23// Make the WASM binary available.
24#[cfg(feature = "std")]
25include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
26
27use crate::fees::{OnChargeTransaction, TransactionByteFee};
28use crate::object_mapping::extract_block_object_mapping;
29use alloc::borrow::Cow;
30use core::mem;
31use core::num::NonZeroU64;
32use domain_runtime_primitives::opaque::Header as DomainHeader;
33use domain_runtime_primitives::{
34    AccountIdConverter, BlockNumber as DomainNumber, EthereumAccountId, Hash as DomainHash,
35    MAX_OUTGOING_MESSAGES, maximum_domain_block_weight,
36};
37use frame_support::genesis_builder_helper::{build_state, get_preset};
38use frame_support::inherent::ProvideInherent;
39use frame_support::traits::fungible::HoldConsideration;
40use frame_support::traits::{
41    ConstU8, ConstU16, ConstU32, ConstU64, Currency, EitherOfDiverse, EqualPrivilegeOnly,
42    Everything, Get, LinearStoragePrice, OnUnbalanced, VariantCount,
43};
44use frame_support::weights::constants::ParityDbWeight;
45use frame_support::weights::{ConstantMultiplier, Weight};
46use frame_support::{PalletId, construct_runtime, parameter_types};
47use frame_system::EnsureRoot;
48use frame_system::limits::{BlockLength, BlockWeights};
49use frame_system::pallet_prelude::RuntimeCallFor;
50use pallet_collective::{EnsureMember, EnsureProportionAtLeast};
51pub use pallet_rewards::RewardPoint;
52pub use pallet_subspace::{AllowAuthoringBy, EnableRewardsAt};
53use pallet_transporter::EndpointHandler;
54use parity_scale_codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
55use scale_info::TypeInfo;
56use sp_api::impl_runtime_apis;
57use sp_consensus_slots::{Slot, SlotDuration};
58use sp_consensus_subspace::{ChainConstants, PotParameters, SignedVote, SolutionRanges, Vote};
59use sp_core::crypto::KeyTypeId;
60use sp_core::{ConstBool, H256, OpaqueMetadata};
61use sp_domains::bundle::BundleVersion;
62use sp_domains::bundle_producer_election::BundleProducerElectionParams;
63use sp_domains::execution_receipt::{
64    ExecutionReceiptFor, ExecutionReceiptVersion, SealedSingletonReceipt,
65};
66use sp_domains::{
67    BundleAndExecutionReceiptVersion, ChannelId, DomainAllowlistUpdates, DomainId,
68    DomainInstanceData, EpochIndex, INITIAL_DOMAIN_TX_RANGE, OperatorId, OperatorPublicKey,
69    PermissionedActionAllowedBy,
70};
71use sp_domains_fraud_proof::fraud_proof::FraudProof;
72use sp_domains_fraud_proof::storage_proof::{
73    FraudProofStorageKeyProvider, FraudProofStorageKeyRequest,
74};
75use sp_messenger::endpoint::{Endpoint, EndpointHandler as EndpointHandlerT, EndpointId};
76use sp_messenger::messages::{
77    BlockMessagesQuery, ChainId, ChannelStateWithNonce, CrossDomainMessage, MessageId, MessageKey,
78    MessagesWithStorageKey, Nonce as XdmNonce,
79};
80use sp_messenger::{ChannelNonce, XdmId};
81use sp_messenger_host_functions::{StorageKeyRequest, get_storage_key};
82use sp_mmr_primitives::EncodableOpaqueLeaf;
83use sp_runtime::traits::{
84    AccountIdConversion, AccountIdLookup, BlakeTwo256, ConstU128, Keccak256, NumberFor,
85};
86use sp_runtime::transaction_validity::{TransactionSource, TransactionValidity};
87use sp_runtime::type_with_default::TypeWithDefault;
88use sp_runtime::{AccountId32, ApplyExtrinsicResult, ExtrinsicInclusionMode, Perbill, generic};
89use sp_std::collections::btree_map::BTreeMap;
90use sp_std::collections::btree_set::BTreeSet;
91use sp_std::marker::PhantomData;
92use sp_std::prelude::*;
93use sp_subspace_mmr::ConsensusChainMmrLeafProof;
94use sp_subspace_mmr::subspace_mmr_runtime_interface::consensus_block_hash;
95use sp_version::RuntimeVersion;
96use static_assertions::const_assert;
97use subspace_core_primitives::objects::BlockObjectMapping;
98use subspace_core_primitives::pieces::Piece;
99use subspace_core_primitives::segments::{
100    HistorySize, SegmentCommitment, SegmentHeader, SegmentIndex,
101};
102use subspace_core_primitives::solutions::{
103    SolutionRange, pieces_to_solution_range, solution_range_to_pieces,
104};
105use subspace_core_primitives::{PublicKey, Randomness, SlotNumber, U256};
106pub use subspace_runtime_primitives::extension::BalanceTransferCheckExtension;
107use subspace_runtime_primitives::extension::{BalanceTransferChecks, MaybeBalancesCall};
108use subspace_runtime_primitives::utility::{
109    DefaultNonceProvider, MaybeMultisigCall, MaybeNestedCall, MaybeUtilityCall,
110};
111use subspace_runtime_primitives::{
112    AI3, AccountId, BLOCK_WEIGHT_FOR_2_SEC, Balance, BlockHashFor, BlockNumber,
113    ConsensusEventSegmentSize, ExtrinsicFor, FindBlockRewardAddress, Hash, HeaderFor,
114    HoldIdentifier, MAX_BLOCK_LENGTH, MIN_REPLICATION_FACTOR, Moment, NORMAL_DISPATCH_RATIO, Nonce,
115    SHANNON, SLOT_PROBABILITY, Signature, SlowAdjustingFeeUpdate, TargetBlockFullness,
116    XdmAdjustedWeightToFee, XdmFeeMultipler, maximum_normal_block_length,
117};
118
119sp_runtime::impl_opaque_keys! {
120    pub struct SessionKeys {
121    }
122}
123
124/// How many pieces one sector is supposed to contain (max)
125const MAX_PIECES_IN_SECTOR: u16 = 1000;
126
127// To learn more about runtime versioning and what each of the following value means:
128//   https://paritytech.github.io/polkadot-sdk/master/sp_version/struct.RuntimeVersion.html
129#[sp_version::runtime_version]
130pub const VERSION: RuntimeVersion = RuntimeVersion {
131    spec_name: Cow::Borrowed("subspace"),
132    impl_name: Cow::Borrowed("subspace"),
133    authoring_version: 0,
134    spec_version: 8,
135    impl_version: 0,
136    apis: RUNTIME_API_VERSIONS,
137    transaction_version: 1,
138    system_version: 2,
139};
140
141// TODO: Many of below constants should probably be updatable but currently they are not
142
143// NOTE: Currently it is not possible to change the slot duration after the chain has started.
144//       Attempting to do so will brick block production.
145const SLOT_DURATION: u64 = 1000;
146
147/// Number of slots between slot arrival and when corresponding block can be produced.
148const BLOCK_AUTHORING_DELAY: SlotNumber = 4;
149
150/// Interval, in blocks, between blockchain entropy injection into proof of time chain.
151const POT_ENTROPY_INJECTION_INTERVAL: BlockNumber = 50;
152
153/// Interval, in entropy injection intervals, where to take entropy for injection from.
154const POT_ENTROPY_INJECTION_LOOKBACK_DEPTH: u8 = 2;
155
156/// Delay after block, in slots, when entropy injection takes effect.
157const POT_ENTROPY_INJECTION_DELAY: SlotNumber = 15;
158
159// Entropy injection interval must be bigger than injection delay or else we may end up in a
160// situation where we'll need to do more than one injection at the same slot
161const_assert!(POT_ENTROPY_INJECTION_INTERVAL as u64 > POT_ENTROPY_INJECTION_DELAY);
162// Entropy injection delay must be bigger than block authoring delay or else we may include
163// invalid future proofs in parent block, +1 ensures we do not have unnecessary reorgs that will
164// inevitably happen otherwise
165const_assert!(POT_ENTROPY_INJECTION_DELAY > BLOCK_AUTHORING_DELAY + 1);
166
167/// Era duration in blocks.
168const ERA_DURATION_IN_BLOCKS: BlockNumber = 2016;
169
170/// Tx range is adjusted every DOMAIN_TX_RANGE_ADJUSTMENT_INTERVAL blocks.
171const TX_RANGE_ADJUSTMENT_INTERVAL_BLOCKS: u64 = 100;
172
173// We assume initial plot size starts with a single sector.
174const INITIAL_SOLUTION_RANGE: SolutionRange =
175    pieces_to_solution_range(MAX_PIECES_IN_SECTOR as u64, SLOT_PROBABILITY);
176
177/// Number of votes expected per block.
178///
179/// This impacts solution range for votes in consensus.
180const EXPECTED_VOTES_PER_BLOCK: u32 = 9;
181
182/// Number of latest archived segments that are considered "recent history".
183const RECENT_SEGMENTS: HistorySize = HistorySize::new(NonZeroU64::new(5).expect("Not zero; qed"));
184/// Fraction of pieces from the "recent history" (`recent_segments`) in each sector.
185const RECENT_HISTORY_FRACTION: (HistorySize, HistorySize) = (
186    HistorySize::new(NonZeroU64::new(1).expect("Not zero; qed")),
187    HistorySize::new(NonZeroU64::new(10).expect("Not zero; qed")),
188);
189/// Minimum lifetime of a plotted sector, measured in archived segment.
190const MIN_SECTOR_LIFETIME: HistorySize =
191    HistorySize::new(NonZeroU64::new(4).expect("Not zero; qed"));
192
193parameter_types! {
194    pub const Version: RuntimeVersion = VERSION;
195    pub const BlockHashCount: BlockNumber = 250;
196    /// We allow for 2 seconds of compute with a 6 second average block time.
197    pub SubspaceBlockWeights: BlockWeights = BlockWeights::with_sensible_defaults(BLOCK_WEIGHT_FOR_2_SEC, NORMAL_DISPATCH_RATIO);
198    /// We allow for 3.75 MiB for `Normal` extrinsic with 5 MiB maximum block length.
199    pub SubspaceBlockLength: BlockLength = maximum_normal_block_length();
200}
201
202pub type SS58Prefix = ConstU16<6094>;
203
204// Configure FRAME pallets to include in runtime.
205
206impl frame_system::Config for Runtime {
207    /// The basic call filter to use in dispatchable.
208    ///
209    /// `Everything` is used here as we use the signed extension
210    /// `DisablePallets` as the actual call filter.
211    type BaseCallFilter = Everything;
212    /// Block & extrinsics weights: base values and limits.
213    type BlockWeights = SubspaceBlockWeights;
214    /// The maximum length of a block (in bytes).
215    type BlockLength = SubspaceBlockLength;
216    /// The identifier used to distinguish between accounts.
217    type AccountId = AccountId;
218    /// The aggregated dispatch type that is available for extrinsics.
219    type RuntimeCall = RuntimeCall;
220    /// The aggregated `RuntimeTask` type.
221    type RuntimeTask = RuntimeTask;
222    /// The lookup mechanism to get account ID from whatever is passed in dispatchers.
223    type Lookup = AccountIdLookup<AccountId, ()>;
224    /// The type for storing how many extrinsics an account has signed.
225    type Nonce = TypeWithDefault<Nonce, DefaultNonceProvider<System, Nonce>>;
226    /// The type for hashing blocks and tries.
227    type Hash = Hash;
228    /// The hashing algorithm used.
229    type Hashing = BlakeTwo256;
230    /// The block type.
231    type Block = Block;
232    /// The ubiquitous event type.
233    type RuntimeEvent = RuntimeEvent;
234    /// The ubiquitous origin type.
235    type RuntimeOrigin = RuntimeOrigin;
236    /// Maximum number of block number to block hash mappings to keep (oldest pruned first).
237    type BlockHashCount = BlockHashCount;
238    /// The weight of database operations that the runtime can invoke.
239    type DbWeight = ParityDbWeight;
240    /// Version of the runtime.
241    type Version = Version;
242    /// Converts a module to the index of the module in `construct_runtime!`.
243    ///
244    /// This type is being generated by `construct_runtime!`.
245    type PalletInfo = PalletInfo;
246    /// What to do if a new account is created.
247    type OnNewAccount = ();
248    /// What to do if an account is fully reaped from the system.
249    type OnKilledAccount = ();
250    /// The data to be stored in an account.
251    type AccountData = pallet_balances::AccountData<Balance>;
252    /// Weight information for the extrinsics of this pallet.
253    type SystemWeightInfo = weights::frame_system::WeightInfo<Runtime>;
254    /// This is used as an identifier of the chain.
255    type SS58Prefix = SS58Prefix;
256    /// The set code logic.
257    type OnSetCode = subspace_runtime_primitives::SetCode<Runtime, Domains>;
258    type SingleBlockMigrations = ();
259    type MultiBlockMigrator = ();
260    type PreInherents = ();
261    type PostInherents = ();
262    type PostTransactions = ();
263    type MaxConsumers = ConstU32<16>;
264    type ExtensionsWeightInfo = frame_system::SubstrateExtensionsWeight<Runtime>;
265    type EventSegmentSize = ConsensusEventSegmentSize;
266}
267
268parameter_types! {
269    pub const BlockAuthoringDelay: SlotNumber = BLOCK_AUTHORING_DELAY;
270    pub const PotEntropyInjectionInterval: BlockNumber = POT_ENTROPY_INJECTION_INTERVAL;
271    pub const PotEntropyInjectionLookbackDepth: u8 = POT_ENTROPY_INJECTION_LOOKBACK_DEPTH;
272    pub const PotEntropyInjectionDelay: SlotNumber = POT_ENTROPY_INJECTION_DELAY;
273    pub const EraDuration: u32 = ERA_DURATION_IN_BLOCKS;
274    pub const SlotProbability: (u64, u64) = SLOT_PROBABILITY;
275    pub const ExpectedVotesPerBlock: u32 = EXPECTED_VOTES_PER_BLOCK;
276    pub const RecentSegments: HistorySize = RECENT_SEGMENTS;
277    pub const RecentHistoryFraction: (HistorySize, HistorySize) = RECENT_HISTORY_FRACTION;
278    pub const MinSectorLifetime: HistorySize = MIN_SECTOR_LIFETIME;
279    // Disable solution range adjustment at the start of chain.
280    // Root origin must enable later
281    pub const ShouldAdjustSolutionRange: bool = false;
282    pub const BlockSlotCount: u32 = 6;
283}
284
285pub struct ConfirmationDepthK;
286
287impl Get<BlockNumber> for ConfirmationDepthK {
288    fn get() -> BlockNumber {
289        pallet_runtime_configs::ConfirmationDepthK::<Runtime>::get()
290    }
291}
292
293impl pallet_subspace::Config for Runtime {
294    type RuntimeEvent = RuntimeEvent;
295    type SubspaceOrigin = pallet_subspace::EnsureSubspaceOrigin;
296    type BlockAuthoringDelay = BlockAuthoringDelay;
297    type PotEntropyInjectionInterval = PotEntropyInjectionInterval;
298    type PotEntropyInjectionLookbackDepth = PotEntropyInjectionLookbackDepth;
299    type PotEntropyInjectionDelay = PotEntropyInjectionDelay;
300    type EraDuration = EraDuration;
301    type InitialSolutionRange = ConstU64<INITIAL_SOLUTION_RANGE>;
302    type SlotProbability = SlotProbability;
303    type ConfirmationDepthK = ConfirmationDepthK;
304    type RecentSegments = RecentSegments;
305    type RecentHistoryFraction = RecentHistoryFraction;
306    type MinSectorLifetime = MinSectorLifetime;
307    type ExpectedVotesPerBlock = ExpectedVotesPerBlock;
308    type MaxPiecesInSector = ConstU16<{ MAX_PIECES_IN_SECTOR }>;
309    type ShouldAdjustSolutionRange = ShouldAdjustSolutionRange;
310    type EraChangeTrigger = pallet_subspace::NormalEraChange;
311    type WeightInfo = weights::pallet_subspace::WeightInfo<Runtime>;
312    type BlockSlotCount = BlockSlotCount;
313    type ExtensionWeightInfo = weights::pallet_subspace_extension::WeightInfo<Runtime>;
314}
315
316impl pallet_timestamp::Config for Runtime {
317    /// A timestamp: milliseconds since the unix epoch.
318    type Moment = Moment;
319    type OnTimestampSet = ();
320    type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>;
321    type WeightInfo = weights::pallet_timestamp::WeightInfo<Runtime>;
322}
323
324parameter_types! {
325    // Computed as ED = Account data size * Price per byte, where
326    // Price per byte = Min Number of validators * Storage duration (years) * Storage cost per year
327    // Account data size (80 bytes)
328    // Min Number of redundant validators (100) - For a stable and redundant blockchain we need at least a certain number of full nodes/collators.
329    // Storage duration (1 year) - It is theoretically unlimited, accounts will stay around while the chain is alive.
330    // Storage cost per year of (12 * 1e-9 * 0.1 ) - SSD storage on cloud hosting costs about 0.1 USD per Gb per month
331    pub const ExistentialDeposit: Balance = 10_000_000_000_000 * SHANNON;
332}
333
334#[derive(
335    PartialEq,
336    Eq,
337    Clone,
338    Encode,
339    Decode,
340    TypeInfo,
341    MaxEncodedLen,
342    Ord,
343    PartialOrd,
344    Copy,
345    Debug,
346    DecodeWithMemTracking,
347)]
348pub struct HoldIdentifierWrapper(HoldIdentifier);
349
350impl pallet_domains::HoldIdentifier<Runtime> for HoldIdentifierWrapper {
351    fn staking_staked() -> Self {
352        Self(HoldIdentifier::DomainStaking)
353    }
354
355    fn domain_instantiation_id() -> Self {
356        Self(HoldIdentifier::DomainInstantiation)
357    }
358
359    fn storage_fund_withdrawal() -> Self {
360        Self(HoldIdentifier::DomainStorageFund)
361    }
362}
363
364impl pallet_messenger::HoldIdentifier<Runtime> for HoldIdentifierWrapper {
365    fn messenger_channel() -> Self {
366        Self(HoldIdentifier::MessengerChannel)
367    }
368}
369
370impl VariantCount for HoldIdentifierWrapper {
371    const VARIANT_COUNT: u32 = mem::variant_count::<HoldIdentifier>() as u32;
372}
373
374impl pallet_balances::Config for Runtime {
375    type RuntimeFreezeReason = RuntimeFreezeReason;
376    type MaxLocks = ConstU32<50>;
377    type MaxReserves = ();
378    type ReserveIdentifier = [u8; 8];
379    /// The type for recording an account's balance.
380    type Balance = Balance;
381    /// The ubiquitous event type.
382    type RuntimeEvent = RuntimeEvent;
383    type DustRemoval = ();
384    type ExistentialDeposit = ExistentialDeposit;
385    type AccountStore = System;
386    type WeightInfo = weights::pallet_balances::WeightInfo<Runtime>;
387    type FreezeIdentifier = ();
388    type MaxFreezes = ();
389    type RuntimeHoldReason = HoldIdentifierWrapper;
390    type DoneSlashHandler = ();
391}
392
393parameter_types! {
394    pub CreditSupply: Balance = Balances::total_issuance();
395    pub TotalSpacePledged: u128 = {
396        let pieces = solution_range_to_pieces(Subspace::solution_ranges().current, SLOT_PROBABILITY);
397        pieces as u128 * Piece::SIZE as u128
398    };
399    pub BlockchainHistorySize: u128 = u128::from(Subspace::archived_history_size());
400    pub DynamicCostOfStorage: bool = RuntimeConfigs::enable_dynamic_cost_of_storage();
401    pub TransactionWeightFee: Balance = 100_000 * SHANNON;
402}
403
404impl pallet_transaction_fees::Config for Runtime {
405    type RuntimeEvent = RuntimeEvent;
406    type MinReplicationFactor = ConstU16<MIN_REPLICATION_FACTOR>;
407    type CreditSupply = CreditSupply;
408    type TotalSpacePledged = TotalSpacePledged;
409    type BlockchainHistorySize = BlockchainHistorySize;
410    type Currency = Balances;
411    type FindBlockRewardAddress = Subspace;
412    type DynamicCostOfStorage = DynamicCostOfStorage;
413    type WeightInfo = pallet_transaction_fees::weights::SubstrateWeight<Runtime>;
414}
415
416impl pallet_transaction_payment::Config for Runtime {
417    type RuntimeEvent = RuntimeEvent;
418    type OnChargeTransaction = OnChargeTransaction;
419    type OperationalFeeMultiplier = ConstU8<5>;
420    type WeightToFee = ConstantMultiplier<Balance, TransactionWeightFee>;
421    type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
422    type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Runtime, TargetBlockFullness>;
423    type WeightInfo = weights::pallet_transaction_payment::WeightInfo<Runtime>;
424}
425
426impl pallet_utility::Config for Runtime {
427    type RuntimeEvent = RuntimeEvent;
428    type RuntimeCall = RuntimeCall;
429    type PalletsOrigin = OriginCaller;
430    type WeightInfo = weights::pallet_utility::WeightInfo<Runtime>;
431}
432
433impl MaybeBalancesCall<Runtime> for RuntimeCall {
434    fn maybe_balance_call(&self) -> Option<&pallet_balances::Call<Runtime>> {
435        match self {
436            RuntimeCall::Balances(call) => Some(call),
437            _ => None,
438        }
439    }
440}
441
442impl BalanceTransferChecks for Runtime {
443    fn is_balance_transferable() -> bool {
444        let enabled = RuntimeConfigs::enable_balance_transfers();
445        // For benchmarks, always return disabled, so the extension runs its checks.
446        // But in the extension, we always return success, so benchmarks run transfers as well.
447        if cfg!(feature = "runtime-benchmarks") {
448            false
449        } else {
450            enabled
451        }
452    }
453}
454
455impl MaybeMultisigCall<Runtime> for RuntimeCall {
456    /// If this call is a `pallet_multisig::Call<Runtime>` call, returns the inner call.
457    fn maybe_multisig_call(&self) -> Option<&pallet_multisig::Call<Runtime>> {
458        match self {
459            RuntimeCall::Multisig(call) => Some(call),
460            _ => None,
461        }
462    }
463}
464
465impl MaybeUtilityCall<Runtime> for RuntimeCall {
466    /// If this call is a `pallet_utility::Call<Runtime>` call, returns the inner call.
467    fn maybe_utility_call(&self) -> Option<&pallet_utility::Call<Runtime>> {
468        match self {
469            RuntimeCall::Utility(call) => Some(call),
470            _ => None,
471        }
472    }
473}
474
475impl MaybeNestedCall<Runtime> for RuntimeCall {
476    /// If this call is a nested runtime call, returns the inner call(s).
477    ///
478    /// Ignored calls (such as `pallet_utility::Call::__Ignore`) should be yielded themsevles, but
479    /// their contents should not be yielded.
480    fn maybe_nested_call(&self) -> Option<Vec<&RuntimeCallFor<Runtime>>> {
481        // We currently ignore privileged calls, because privileged users can already change
482        // runtime code. This includes sudo, collective, and scheduler nested `RuntimeCall`s,
483        // and democracy nested `BoundedCall`s.
484
485        // It is ok to return early, because each call can only belong to one pallet.
486        let calls = self.maybe_nested_utility_calls();
487        if calls.is_some() {
488            return calls;
489        }
490
491        let calls = self.maybe_nested_multisig_calls();
492        if calls.is_some() {
493            return calls;
494        }
495
496        None
497    }
498}
499
500impl pallet_sudo::Config for Runtime {
501    type RuntimeEvent = RuntimeEvent;
502    type RuntimeCall = RuntimeCall;
503    type WeightInfo = weights::pallet_sudo::WeightInfo<Runtime>;
504}
505
506pub type CouncilCollective = pallet_collective::Instance1;
507
508// Macro to implement 'Get' trait for each field of 'CouncilDemocracyConfigParams'
509macro_rules! impl_get_council_democracy_field_block_number {
510    ($field_type_name:ident, $field:ident) => {
511        pub struct $field_type_name;
512
513        impl Get<BlockNumber> for $field_type_name {
514            fn get() -> BlockNumber {
515                pallet_runtime_configs::CouncilDemocracyConfig::<Runtime>::get().$field
516            }
517        }
518    };
519}
520
521impl_get_council_democracy_field_block_number! {CouncilMotionDuration, council_motion_duration}
522
523parameter_types! {
524    // maximum dispatch weight of a given council motion
525    // currently set to 50% of maximum block weight
526    pub MaxProposalWeight: Weight = Perbill::from_percent(50) * SubspaceBlockWeights::get().max_block;
527}
528
529pub type EnsureRootOr<O> = EitherOfDiverse<EnsureRoot<AccountId>, O>;
530pub type AllCouncil = EnsureProportionAtLeast<AccountId, CouncilCollective, 1, 1>;
531pub type TwoThirdsCouncil = EnsureProportionAtLeast<AccountId, CouncilCollective, 2, 3>;
532pub type HalfCouncil = EnsureProportionAtLeast<AccountId, CouncilCollective, 1, 2>;
533
534// TODO: update params for mainnnet
535impl pallet_collective::Config<CouncilCollective> for Runtime {
536    type DefaultVote = pallet_collective::PrimeDefaultVote;
537    type MaxMembers = ConstU32<100>;
538    type MaxProposalWeight = MaxProposalWeight;
539    type MaxProposals = ConstU32<100>;
540    /// Duration of voting for a given council motion.
541    type MotionDuration = CouncilMotionDuration;
542    type Proposal = RuntimeCall;
543    type RuntimeEvent = RuntimeEvent;
544    type RuntimeOrigin = RuntimeOrigin;
545    type SetMembersOrigin = EnsureRootOr<AllCouncil>;
546    type WeightInfo = weights::pallet_collective::WeightInfo<Runtime>;
547    type DisapproveOrigin = TwoThirdsCouncil;
548    type KillOrigin = TwoThirdsCouncil;
549    /// Kind of consideration(amount to hold/freeze) on Collective account who initiated the proposal.
550    /// Currently set to zero.
551    type Consideration = ();
552}
553
554// TODO: update params for mainnnet
555parameter_types! {
556    pub PreimageBaseDeposit: Balance = 100 * AI3;
557    pub PreimageByteDeposit: Balance = AI3;
558    pub const PreImageHoldReason: HoldIdentifierWrapper = HoldIdentifierWrapper(HoldIdentifier::Preimage);
559}
560
561impl pallet_preimage::Config for Runtime {
562    type Consideration = HoldConsideration<
563        AccountId,
564        Balances,
565        PreImageHoldReason,
566        LinearStoragePrice<PreimageBaseDeposit, PreimageByteDeposit, Balance>,
567    >;
568    type Currency = Balances;
569    type ManagerOrigin = EnsureRoot<AccountId>;
570    type RuntimeEvent = RuntimeEvent;
571    type WeightInfo = weights::pallet_preimage::WeightInfo<Runtime>;
572}
573
574parameter_types! {
575    pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * SubspaceBlockWeights::get().max_block;
576    // Retry a scheduled item every 10 blocks (2 minutes) until the preimage exists.
577    pub const NoPreimagePostponement: Option<u32> = Some(10);
578}
579
580// Call preimages for the democracy and scheduler pallets can be stored as a binary blob. These
581// blobs are only fetched and decoded in the future block when the call is actually run. This
582// means any member of the council (or sudo) can schedule an invalid subspace runtime call. These
583// calls can cause a stack limit exceeded error in a future block. (Or other kinds of errors.)
584//
585// This risk is acceptable because those accounts are privileged, and those pallets already have
586// to deal with invalid stored calls (for example, stored before an upgrade, but run after).
587//
588// Invalid domain runtime calls will be rejected by the domain runtime extrinsic format checks,
589// even if they are scheduled/democratized in the subspace runtime.
590impl pallet_scheduler::Config for Runtime {
591    type MaxScheduledPerBlock = ConstU32<50>;
592    type MaximumWeight = MaximumSchedulerWeight;
593    type OriginPrivilegeCmp = EqualPrivilegeOnly;
594    type PalletsOrigin = OriginCaller;
595    type Preimages = Preimage;
596    type RuntimeCall = RuntimeCall;
597    type RuntimeEvent = RuntimeEvent;
598    type RuntimeOrigin = RuntimeOrigin;
599    type ScheduleOrigin = EnsureRoot<AccountId>;
600    type WeightInfo = weights::pallet_scheduler::WeightInfo<Runtime>;
601    type BlockNumberProvider = System;
602}
603
604type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;
605
606pub struct DemocracySlash;
607impl OnUnbalanced<NegativeImbalance> for DemocracySlash {
608    fn on_nonzero_unbalanced(slashed: NegativeImbalance) {
609        Balances::resolve_creating(&TreasuryAccount::get(), slashed);
610    }
611}
612
613impl_get_council_democracy_field_block_number! {CooloffPeriod, democracy_cooloff_period}
614impl_get_council_democracy_field_block_number! {EnactmentPeriod, democracy_enactment_period}
615impl_get_council_democracy_field_block_number! {FastTrackVotingPeriod, democracy_fast_track_voting_period}
616impl_get_council_democracy_field_block_number! {LaunchPeriod, democracy_launch_period}
617impl_get_council_democracy_field_block_number! {VoteLockingPeriod, democracy_vote_locking_period}
618impl_get_council_democracy_field_block_number! {VotingPeriod, democracy_voting_period}
619
620// TODO: update params for mainnnet
621impl pallet_democracy::Config for Runtime {
622    type BlacklistOrigin = EnsureRoot<AccountId>;
623    /// To cancel a proposal before it has been passed and slash its backers, must be root.
624    type CancelProposalOrigin = EnsureRoot<AccountId>;
625    /// Origin to cancel a proposal.
626    type CancellationOrigin = EnsureRootOr<TwoThirdsCouncil>;
627    /// Period in blocks where an external proposal may not be re-submitted
628    /// after being vetoed.
629    type CooloffPeriod = CooloffPeriod;
630    type Currency = Balances;
631    /// The minimum period of locking and the period between a proposal being
632    /// approved and enacted.
633    type EnactmentPeriod = EnactmentPeriod;
634    /// A unanimous council can have the next scheduled referendum be a straight
635    /// default-carries (negative turnout biased) vote.
636    /// 100% council vote.
637    type ExternalDefaultOrigin = AllCouncil;
638    /// A simple majority can have the next scheduled referendum be a straight
639    /// majority-carries vote.
640    /// 50% of council votes.
641    type ExternalMajorityOrigin = HalfCouncil;
642    /// A simple majority of the council can decide what their next motion is.
643    /// 50% council votes.
644    type ExternalOrigin = HalfCouncil;
645    /// Half of the council can have an ExternalMajority/ExternalDefault vote
646    /// be tabled immediately and with a shorter voting/enactment period.
647    type FastTrackOrigin = EnsureRootOr<HalfCouncil>;
648    /// Voting period for Fast track voting.
649    type FastTrackVotingPeriod = FastTrackVotingPeriod;
650    type InstantAllowed = ConstBool<true>;
651    type InstantOrigin = EnsureRootOr<AllCouncil>;
652    /// How often (in blocks) new public referenda are launched.
653    type LaunchPeriod = LaunchPeriod;
654    type MaxBlacklisted = ConstU32<100>;
655    type MaxDeposits = ConstU32<100>;
656    type MaxProposals = ConstU32<100>;
657    type MaxVotes = ConstU32<100>;
658    /// The minimum amount to be used as a deposit for a public referendum
659    /// proposal.
660    type MinimumDeposit = ConstU128<{ 1000 * AI3 }>;
661    type PalletsOrigin = OriginCaller;
662    type Preimages = Preimage;
663    type RuntimeEvent = RuntimeEvent;
664    type Scheduler = Scheduler;
665    /// Handler for the unbalanced reduction when slashing a preimage deposit.
666    type Slash = DemocracySlash;
667    /// Origin used to submit proposals.
668    /// Currently set to Council member so that no one can submit new proposals except council through democracy
669    type SubmitOrigin = EnsureMember<AccountId, CouncilCollective>;
670    /// Any single council member may veto a coming council proposal, however they
671    /// can only do it once and it lasts only for the cooloff period.
672    type VetoOrigin = EnsureMember<AccountId, CouncilCollective>;
673    type VoteLockingPeriod = VoteLockingPeriod;
674    /// How often (in blocks) to check for new votes.
675    type VotingPeriod = VotingPeriod;
676    type WeightInfo = pallet_democracy::weights::SubstrateWeight<Runtime>;
677}
678
679parameter_types! {
680    pub const SelfChainId: ChainId = ChainId::Consensus;
681}
682
683pub struct OnXDMRewards;
684
685impl sp_messenger::OnXDMRewards<Balance> for OnXDMRewards {
686    fn on_xdm_rewards(reward: Balance) {
687        if let Some(block_author) = Subspace::find_block_reward_address() {
688            let _ = Balances::deposit_creating(&block_author, reward);
689        }
690    }
691
692    fn on_chain_protocol_fees(chain_id: ChainId, fees: Balance) {
693        // on consensus chain, reward the domain operators
694        // balance is already on this consensus runtime
695        if let ChainId::Domain(domain_id) = chain_id {
696            Domains::reward_domain_operators(domain_id, fees)
697        }
698    }
699}
700
701pub struct MmrProofVerifier;
702
703impl sp_subspace_mmr::MmrProofVerifier<mmr::Hash, NumberFor<Block>, Hash> for MmrProofVerifier {
704    fn verify_proof_and_extract_leaf(
705        mmr_leaf_proof: ConsensusChainMmrLeafProof<NumberFor<Block>, Hash, mmr::Hash>,
706    ) -> Option<mmr::Leaf> {
707        let mmr_root = SubspaceMmr::mmr_root_hash(mmr_leaf_proof.consensus_block_number)?;
708        Self::verify_proof_stateless(mmr_root, mmr_leaf_proof)
709    }
710
711    fn verify_proof_stateless(
712        mmr_root: mmr::Hash,
713        mmr_leaf_proof: ConsensusChainMmrLeafProof<NumberFor<Block>, Hash, mmr::Hash>,
714    ) -> Option<mmr::Leaf> {
715        let ConsensusChainMmrLeafProof {
716            opaque_mmr_leaf,
717            proof,
718            ..
719        } = mmr_leaf_proof;
720
721        pallet_mmr::verify_leaves_proof::<mmr::Hashing, _>(
722            mmr_root,
723            vec![mmr::DataOrHash::Data(
724                EncodableOpaqueLeaf(opaque_mmr_leaf.0.clone()).into_opaque_leaf(),
725            )],
726            proof,
727        )
728        .ok()?;
729
730        let leaf: mmr::Leaf = opaque_mmr_leaf.into_opaque_leaf().try_decode()?;
731
732        Some(leaf)
733    }
734}
735
736pub struct StorageKeys;
737
738impl sp_messenger::StorageKeys for StorageKeys {
739    fn confirmed_domain_block_storage_key(domain_id: DomainId) -> Option<Vec<u8>> {
740        Some(Domains::confirmed_domain_block_storage_key(domain_id))
741    }
742
743    fn outbox_storage_key(chain_id: ChainId, message_key: MessageKey) -> Option<Vec<u8>> {
744        get_storage_key(StorageKeyRequest::OutboxStorageKey {
745            chain_id,
746            message_key,
747        })
748    }
749
750    fn inbox_responses_storage_key(chain_id: ChainId, message_key: MessageKey) -> Option<Vec<u8>> {
751        get_storage_key(StorageKeyRequest::InboxResponseStorageKey {
752            chain_id,
753            message_key,
754        })
755    }
756}
757
758parameter_types! {
759    // TODO: update value
760    pub const ChannelReserveFee: Balance = 100 * AI3;
761    pub const ChannelInitReservePortion: Perbill = Perbill::from_percent(20);
762    pub const MaxOutgoingMessages: u32 = MAX_OUTGOING_MESSAGES;
763}
764
765// ensure the max outgoing messages is not 0.
766const_assert!(MaxOutgoingMessages::get() >= 1);
767
768pub struct DomainRegistration;
769impl sp_messenger::DomainRegistration for DomainRegistration {
770    fn is_domain_registered(domain_id: DomainId) -> bool {
771        Domains::is_domain_registered(domain_id)
772    }
773}
774
775impl pallet_messenger::Config for Runtime {
776    type RuntimeEvent = RuntimeEvent;
777    type SelfChainId = SelfChainId;
778
779    fn get_endpoint_handler(endpoint: &Endpoint) -> Option<Box<dyn EndpointHandlerT<MessageId>>> {
780        if endpoint == &Endpoint::Id(TransporterEndpointId::get()) {
781            Some(Box::new(EndpointHandler(PhantomData::<Runtime>)))
782        } else {
783            None
784        }
785    }
786
787    type Currency = Balances;
788    type WeightInfo = weights::pallet_messenger::WeightInfo<Runtime>;
789    type WeightToFee = ConstantMultiplier<Balance, TransactionWeightFee>;
790    type AdjustedWeightToFee = XdmAdjustedWeightToFee<Runtime>;
791    type FeeMultiplier = XdmFeeMultipler;
792    type OnXDMRewards = OnXDMRewards;
793    type MmrHash = mmr::Hash;
794    type MmrProofVerifier = MmrProofVerifier;
795    #[cfg(feature = "runtime-benchmarks")]
796    type StorageKeys = sp_messenger::BenchmarkStorageKeys;
797    #[cfg(not(feature = "runtime-benchmarks"))]
798    type StorageKeys = StorageKeys;
799    type DomainOwner = Domains;
800    type HoldIdentifier = HoldIdentifierWrapper;
801    type ChannelReserveFee = ChannelReserveFee;
802    type ChannelInitReservePortion = ChannelInitReservePortion;
803    type DomainRegistration = DomainRegistration;
804    type MaxOutgoingMessages = MaxOutgoingMessages;
805    type MessengerOrigin = pallet_messenger::EnsureMessengerOrigin;
806    type NoteChainTransfer = Transporter;
807    type ExtensionWeightInfo = pallet_messenger::extensions::weights::SubstrateWeight<
808        Runtime,
809        // NOTE: use `()` as `FromConsensusWeightInfo` since the consensus chain should
810        // never process XDM that come from the consensus chain itself.
811        (),
812        weights::pallet_messenger_from_domains_extension::WeightInfo<Runtime>,
813    >;
814}
815
816impl<C> frame_system::offchain::CreateTransactionBase<C> for Runtime
817where
818    RuntimeCall: From<C>,
819{
820    type Extrinsic = UncheckedExtrinsic;
821    type RuntimeCall = RuntimeCall;
822}
823
824impl<C> frame_system::offchain::CreateInherent<C> for Runtime
825where
826    RuntimeCall: From<C>,
827{
828    fn create_inherent(call: Self::RuntimeCall) -> Self::Extrinsic {
829        UncheckedExtrinsic::new_bare(call)
830    }
831}
832
833impl<C> subspace_runtime_primitives::CreateUnsigned<C> for Runtime
834where
835    RuntimeCall: From<C>,
836{
837    fn create_unsigned(call: Self::RuntimeCall) -> Self::Extrinsic {
838        create_unsigned_general_extrinsic(call)
839    }
840}
841
842parameter_types! {
843    pub const TransporterEndpointId: EndpointId = 1;
844    pub const MinimumTransfer: Balance = AI3;
845}
846
847impl pallet_transporter::Config for Runtime {
848    type RuntimeEvent = RuntimeEvent;
849    type SelfChainId = SelfChainId;
850    type SelfEndpointId = TransporterEndpointId;
851    type Currency = Balances;
852    type Sender = Messenger;
853    type AccountIdConverter = AccountIdConverter;
854    type WeightInfo = weights::pallet_transporter::WeightInfo<Runtime>;
855    type MinimumTransfer = MinimumTransfer;
856}
857
858pub struct BlockTreePruningDepth;
859impl Get<BlockNumber> for BlockTreePruningDepth {
860    fn get() -> BlockNumber {
861        pallet_runtime_configs::DomainBlockPruningDepth::<Runtime>::get()
862    }
863}
864
865pub struct StakeWithdrawalLockingPeriod;
866impl Get<BlockNumber> for StakeWithdrawalLockingPeriod {
867    fn get() -> BlockNumber {
868        pallet_runtime_configs::StakingWithdrawalPeriod::<Runtime>::get()
869    }
870}
871
872parameter_types! {
873    pub const MaximumReceiptDrift: BlockNumber = 128;
874    pub const InitialDomainTxRange: u64 = INITIAL_DOMAIN_TX_RANGE;
875    pub const DomainTxRangeAdjustmentInterval: u64 = TX_RANGE_ADJUSTMENT_INTERVAL_BLOCKS;
876    /// Minimum operator stake to become an operator.
877    // TODO: this value should be properly updated before permissionless operators are allowed
878    pub const MinOperatorStake: Balance = 100 * AI3;
879    /// Minimum nominator stake to nominate and operator.
880    // TODO: this value should be properly updated before permissionless operators are allowed
881    pub const MinNominatorStake: Balance = AI3;
882    /// Use the consensus chain's `Normal` extrinsics block size limit as the domain block size limit
883    pub MaxDomainBlockSize: u32 = NORMAL_DISPATCH_RATIO * MAX_BLOCK_LENGTH;
884    /// Use the consensus chain's `Normal` extrinsics block weight limit as the domain block weight limit
885    pub MaxDomainBlockWeight: Weight = maximum_domain_block_weight();
886    pub const DomainInstantiationDeposit: Balance = 100 * AI3;
887    pub const MaxDomainNameLength: u32 = 32;
888    // TODO: revisit these. For now epoch every 10 mins for a 6 second block and only 100 number of staking
889    // operations allowed within each epoch.
890    pub const StakeEpochDuration: DomainNumber = 100;
891    pub TreasuryAccount: AccountId = PalletId(*b"treasury").into_account_truncating();
892    pub const MaxPendingStakingOperation: u32 = 512;
893    pub const DomainsPalletId: PalletId = PalletId(*b"domains_");
894    pub const MaxInitialDomainAccounts: u32 = 10;
895    pub const MinInitialDomainAccountBalance: Balance = AI3;
896    pub const BundleLongevity: u32 = 5;
897    pub const WithdrawalLimit: u32 = 32;
898    pub const CurrentBundleAndExecutionReceiptVersion: BundleAndExecutionReceiptVersion = BundleAndExecutionReceiptVersion{
899        bundle_version: BundleVersion::V0,
900        execution_receipt_version: ExecutionReceiptVersion::V0,
901    };
902    /// Operator activation delay after deactivation in Epochs
903    pub const OperatorActivationDelayInEpochs: EpochIndex = 5;
904}
905
906// `BlockSlotCount` must at least keep the slot for the current and the parent block, it also need to
907// keep enough block slot for bundle validation
908const_assert!(BlockSlotCount::get() >= 2 && BlockSlotCount::get() > BundleLongevity::get());
909
910// `BlockHashCount` must greater than `BlockSlotCount` because we need to use the block number found
911// with `BlockSlotCount` to get the block hash.
912const_assert!(BlockHashCount::get() > BlockSlotCount::get());
913
914// Minimum operator stake must be >= minimum nominator stake since operator is also a nominator.
915const_assert!(MinOperatorStake::get() >= MinNominatorStake::get());
916
917pub struct BlockSlot;
918
919impl pallet_domains::BlockSlot<Runtime> for BlockSlot {
920    fn future_slot(block_number: BlockNumber) -> Option<sp_consensus_slots::Slot> {
921        let block_slots = Subspace::block_slots();
922        block_slots
923            .get(&block_number)
924            .map(|slot| *slot + Slot::from(BlockAuthoringDelay::get()))
925    }
926
927    fn slot_produced_after(to_check: sp_consensus_slots::Slot) -> Option<BlockNumber> {
928        let block_slots = Subspace::block_slots();
929        for (block_number, slot) in block_slots.into_iter().rev() {
930            if to_check > slot {
931                return Some(block_number);
932            }
933        }
934        None
935    }
936
937    fn current_slot() -> Slot {
938        Subspace::current_slot()
939    }
940}
941
942pub struct OnChainRewards;
943
944impl sp_domains::OnChainRewards<Balance> for OnChainRewards {
945    fn on_chain_rewards(chain_id: ChainId, reward: Balance) {
946        match chain_id {
947            ChainId::Consensus => {
948                if let Some(block_author) = Subspace::find_block_reward_address() {
949                    let _ = Balances::deposit_creating(&block_author, reward);
950                }
951            }
952            ChainId::Domain(domain_id) => Domains::reward_domain_operators(domain_id, reward),
953        }
954    }
955}
956
957impl pallet_domains::Config for Runtime {
958    type RuntimeEvent = RuntimeEvent;
959    type DomainOrigin = pallet_domains::EnsureDomainOrigin;
960    type DomainHash = DomainHash;
961    type Balance = Balance;
962    type DomainHeader = sp_runtime::generic::Header<DomainNumber, BlakeTwo256>;
963    type ConfirmationDepthK = ConfirmationDepthK;
964    type Currency = Balances;
965    type Share = Balance;
966    type HoldIdentifier = HoldIdentifierWrapper;
967    type BlockTreePruningDepth = BlockTreePruningDepth;
968    type ConsensusSlotProbability = SlotProbability;
969    type MaxDomainBlockSize = MaxDomainBlockSize;
970    type MaxDomainBlockWeight = MaxDomainBlockWeight;
971    type MaxDomainNameLength = MaxDomainNameLength;
972    type DomainInstantiationDeposit = DomainInstantiationDeposit;
973    type WeightInfo = weights::pallet_domains::WeightInfo<Runtime>;
974    type InitialDomainTxRange = InitialDomainTxRange;
975    type DomainTxRangeAdjustmentInterval = DomainTxRangeAdjustmentInterval;
976    type MinOperatorStake = MinOperatorStake;
977    type MinNominatorStake = MinNominatorStake;
978    type StakeWithdrawalLockingPeriod = StakeWithdrawalLockingPeriod;
979    type StakeEpochDuration = StakeEpochDuration;
980    type TreasuryAccount = TreasuryAccount;
981    type MaxPendingStakingOperation = MaxPendingStakingOperation;
982    type Randomness = Subspace;
983    type PalletId = DomainsPalletId;
984    type StorageFee = TransactionFees;
985    type BlockTimestamp = pallet_timestamp::Pallet<Runtime>;
986    type BlockSlot = BlockSlot;
987    type DomainsTransfersTracker = Transporter;
988    type MaxInitialDomainAccounts = MaxInitialDomainAccounts;
989    type MinInitialDomainAccountBalance = MinInitialDomainAccountBalance;
990    type BundleLongevity = BundleLongevity;
991    type DomainBundleSubmitted = Messenger;
992    type OnDomainInstantiated = Messenger;
993    type MmrHash = mmr::Hash;
994    type MmrProofVerifier = MmrProofVerifier;
995    type FraudProofStorageKeyProvider = StorageKeyProvider;
996    type OnChainRewards = OnChainRewards;
997    type WithdrawalLimit = WithdrawalLimit;
998    type CurrentBundleAndExecutionReceiptVersion = CurrentBundleAndExecutionReceiptVersion;
999    type OperatorActivationDelayInEpochs = OperatorActivationDelayInEpochs;
1000}
1001
1002parameter_types! {
1003    pub const AvgBlockspaceUsageNumBlocks: BlockNumber = 100;
1004    pub const ProposerTaxOnVotes: (u32, u32) = (1, 10);
1005}
1006
1007impl pallet_rewards::Config for Runtime {
1008    type RuntimeEvent = RuntimeEvent;
1009    type Currency = Balances;
1010    type AvgBlockspaceUsageNumBlocks = AvgBlockspaceUsageNumBlocks;
1011    type TransactionByteFee = TransactionByteFee;
1012    type MaxRewardPoints = ConstU32<20>;
1013    type ProposerTaxOnVotes = ProposerTaxOnVotes;
1014    type RewardsEnabled = Subspace;
1015    type FindBlockRewardAddress = Subspace;
1016    type FindVotingRewardAddresses = Subspace;
1017    type WeightInfo = weights::pallet_rewards::WeightInfo<Runtime>;
1018    type OnReward = ();
1019}
1020
1021impl pallet_runtime_configs::Config for Runtime {
1022    type WeightInfo = weights::pallet_runtime_configs::WeightInfo<Runtime>;
1023}
1024
1025impl pallet_domains::extensions::DomainsCheck for Runtime {
1026    fn is_domains_enabled() -> bool {
1027        RuntimeConfigs::enable_domains()
1028    }
1029}
1030
1031mod mmr {
1032    use super::Runtime;
1033    pub use pallet_mmr::primitives::*;
1034
1035    pub type Leaf = <<Runtime as pallet_mmr::Config>::LeafData as LeafDataProvider>::LeafData;
1036    pub type Hashing = <Runtime as pallet_mmr::Config>::Hashing;
1037    pub type Hash = <Hashing as sp_runtime::traits::Hash>::Output;
1038}
1039
1040pub struct BlockHashProvider;
1041
1042impl pallet_mmr::BlockHashProvider<BlockNumber, Hash> for BlockHashProvider {
1043    fn block_hash(block_number: BlockNumber) -> Hash {
1044        consensus_block_hash(block_number).expect("Hash must exist for a given block number.")
1045    }
1046}
1047
1048impl pallet_mmr::Config for Runtime {
1049    const INDEXING_PREFIX: &'static [u8] = mmr::INDEXING_PREFIX;
1050    type Hashing = Keccak256;
1051    type LeafData = SubspaceMmr;
1052    type OnNewRoot = SubspaceMmr;
1053    type BlockHashProvider = BlockHashProvider;
1054    type WeightInfo = weights::pallet_mmr::WeightInfo<Runtime>;
1055    #[cfg(feature = "runtime-benchmarks")]
1056    type BenchmarkHelper = ();
1057}
1058
1059parameter_types! {
1060    pub const MmrRootHashCount: u32 = 1024;
1061}
1062
1063impl pallet_subspace_mmr::Config for Runtime {
1064    type MmrRootHash = mmr::Hash;
1065    type MmrRootHashCount = MmrRootHashCount;
1066}
1067
1068parameter_types! {
1069    pub const MaxSignatories: u32 = 100;
1070}
1071
1072macro_rules! deposit {
1073    ($name:ident, $item_fee:expr, $items:expr, $bytes:expr) => {
1074        pub struct $name;
1075
1076        impl Get<Balance> for $name {
1077            fn get() -> Balance {
1078                $item_fee.saturating_mul($items.into()).saturating_add(
1079                    TransactionFees::transaction_byte_fee().saturating_mul($bytes.into()),
1080                )
1081            }
1082        }
1083    };
1084}
1085
1086// One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes.
1087// Each multisig costs 20 AI3 + bytes_of_storge * TransactionByteFee
1088deposit!(DepositBaseFee, 20 * AI3, 1u32, 88u32);
1089
1090// Additional storage item size of 32 bytes.
1091deposit!(DepositFactor, 0u128, 0u32, 32u32);
1092
1093impl pallet_multisig::Config for Runtime {
1094    type RuntimeEvent = RuntimeEvent;
1095    type RuntimeCall = RuntimeCall;
1096    type Currency = Balances;
1097    type DepositBase = DepositBaseFee;
1098    type DepositFactor = DepositFactor;
1099    type MaxSignatories = MaxSignatories;
1100    type WeightInfo = weights::pallet_multisig::WeightInfo<Runtime>;
1101    type BlockNumberProvider = System;
1102}
1103
1104construct_runtime!(
1105    pub struct Runtime {
1106        System: frame_system = 0,
1107        Timestamp: pallet_timestamp = 1,
1108
1109        Subspace: pallet_subspace = 2,
1110        Rewards: pallet_rewards = 4,
1111
1112        Balances: pallet_balances = 5,
1113        TransactionFees: pallet_transaction_fees = 6,
1114        TransactionPayment: pallet_transaction_payment = 7,
1115        Utility: pallet_utility = 8,
1116
1117        Domains: pallet_domains = 12,
1118        RuntimeConfigs: pallet_runtime_configs = 14,
1119
1120        Mmr: pallet_mmr = 30,
1121        SubspaceMmr: pallet_subspace_mmr = 31,
1122
1123        // messenger stuff
1124        // Note: Indexes should match with indexes on other chains and domains
1125        Messenger: pallet_messenger exclude_parts { Inherent } = 60,
1126        Transporter: pallet_transporter = 61,
1127
1128        // council and democracy
1129        Scheduler: pallet_scheduler = 81,
1130        Council: pallet_collective::<Instance1> = 82,
1131        Democracy: pallet_democracy = 83,
1132        Preimage: pallet_preimage = 84,
1133
1134        // Multisig
1135        Multisig: pallet_multisig = 90,
1136
1137        // Reserve some room for other pallets as we'll remove sudo pallet eventually.
1138        Sudo: pallet_sudo = 100,
1139    }
1140);
1141
1142/// The address format for describing accounts.
1143pub type Address = sp_runtime::MultiAddress<AccountId, ()>;
1144/// Block header type as expected by this runtime.
1145pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
1146/// Block type as expected by this runtime.
1147pub type Block = generic::Block<Header, UncheckedExtrinsic>;
1148
1149/// The SignedExtension to the basic transaction logic.
1150pub type SignedExtra = (
1151    frame_system::CheckNonZeroSender<Runtime>,
1152    frame_system::CheckSpecVersion<Runtime>,
1153    frame_system::CheckTxVersion<Runtime>,
1154    frame_system::CheckGenesis<Runtime>,
1155    frame_system::CheckMortality<Runtime>,
1156    frame_system::CheckNonce<Runtime>,
1157    frame_system::CheckWeight<Runtime>,
1158    pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
1159    BalanceTransferCheckExtension<Runtime>,
1160    pallet_subspace::extensions::SubspaceExtension<Runtime>,
1161    pallet_domains::extensions::DomainsExtension<Runtime>,
1162    pallet_messenger::extensions::MessengerExtension<Runtime>,
1163);
1164/// Unchecked extrinsic type as expected by this runtime.
1165pub type UncheckedExtrinsic =
1166    generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
1167
1168/// Executive: handles dispatch to the various modules.
1169pub type Executive = frame_executive::Executive<
1170    Runtime,
1171    Block,
1172    frame_system::ChainContext<Runtime>,
1173    Runtime,
1174    AllPalletsWithSystem,
1175    pallet_domains::migrations::VersionCheckedMigrateDomainsV5ToV6<Runtime>,
1176>;
1177
1178impl pallet_subspace::extensions::MaybeSubspaceCall<Runtime> for RuntimeCall {
1179    fn maybe_subspace_call(&self) -> Option<&pallet_subspace::Call<Runtime>> {
1180        match self {
1181            RuntimeCall::Subspace(call) => Some(call),
1182            _ => None,
1183        }
1184    }
1185}
1186
1187impl pallet_domains::extensions::MaybeDomainsCall<Runtime> for RuntimeCall {
1188    fn maybe_domains_call(&self) -> Option<&pallet_domains::Call<Runtime>> {
1189        match self {
1190            RuntimeCall::Domains(call) => Some(call),
1191            _ => None,
1192        }
1193    }
1194}
1195
1196impl pallet_messenger::extensions::MaybeMessengerCall<Runtime> for RuntimeCall {
1197    fn maybe_messenger_call(&self) -> Option<&pallet_messenger::Call<Runtime>> {
1198        match self {
1199            RuntimeCall::Messenger(call) => Some(call),
1200            _ => None,
1201        }
1202    }
1203}
1204
1205fn extract_segment_headers(ext: &UncheckedExtrinsic) -> Option<Vec<SegmentHeader>> {
1206    match &ext.function {
1207        RuntimeCall::Subspace(pallet_subspace::Call::store_segment_headers { segment_headers }) => {
1208            Some(segment_headers.clone())
1209        }
1210        _ => None,
1211    }
1212}
1213
1214fn is_xdm_mmr_proof_valid(ext: &ExtrinsicFor<Block>) -> Option<bool> {
1215    match &ext.function {
1216        RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })
1217        | RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1218            let ConsensusChainMmrLeafProof {
1219                consensus_block_number,
1220                opaque_mmr_leaf,
1221                proof,
1222                ..
1223            } = msg.proof.consensus_mmr_proof();
1224
1225            let mmr_root = SubspaceMmr::mmr_root_hash(consensus_block_number)?;
1226
1227            Some(
1228                pallet_mmr::verify_leaves_proof::<mmr::Hashing, _>(
1229                    mmr_root,
1230                    vec![mmr::DataOrHash::Data(
1231                        EncodableOpaqueLeaf(opaque_mmr_leaf.0.clone()).into_opaque_leaf(),
1232                    )],
1233                    proof,
1234                )
1235                .is_ok(),
1236            )
1237        }
1238        _ => None,
1239    }
1240}
1241
1242fn create_unsigned_general_extrinsic(call: RuntimeCall) -> UncheckedExtrinsic {
1243    let extra: SignedExtra = (
1244        frame_system::CheckNonZeroSender::<Runtime>::new(),
1245        frame_system::CheckSpecVersion::<Runtime>::new(),
1246        frame_system::CheckTxVersion::<Runtime>::new(),
1247        frame_system::CheckGenesis::<Runtime>::new(),
1248        frame_system::CheckMortality::<Runtime>::from(generic::Era::Immortal),
1249        // for unsigned extrinsic, nonce check will be skipped
1250        // so set a default value
1251        frame_system::CheckNonce::<Runtime>::from(0u32.into()),
1252        frame_system::CheckWeight::<Runtime>::new(),
1253        // for unsigned extrinsic, transaction fee check will be skipped
1254        // so set a default value
1255        pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(0u128),
1256        BalanceTransferCheckExtension::<Runtime>::default(),
1257        pallet_subspace::extensions::SubspaceExtension::<Runtime>::new(),
1258        pallet_domains::extensions::DomainsExtension::<Runtime>::new(),
1259        pallet_messenger::extensions::MessengerExtension::<Runtime>::new(),
1260    );
1261
1262    UncheckedExtrinsic::new_transaction(call, extra)
1263}
1264
1265struct RewardAddress([u8; 32]);
1266
1267impl From<PublicKey> for RewardAddress {
1268    #[inline]
1269    fn from(public_key: PublicKey) -> Self {
1270        Self(*public_key)
1271    }
1272}
1273
1274impl From<RewardAddress> for AccountId32 {
1275    #[inline]
1276    fn from(reward_address: RewardAddress) -> Self {
1277        reward_address.0.into()
1278    }
1279}
1280
1281pub struct StorageKeyProvider;
1282impl FraudProofStorageKeyProvider<NumberFor<Block>> for StorageKeyProvider {
1283    fn storage_key(req: FraudProofStorageKeyRequest<NumberFor<Block>>) -> Vec<u8> {
1284        match req {
1285            FraudProofStorageKeyRequest::InvalidInherentExtrinsicData => {
1286                pallet_domains::BlockInherentExtrinsicData::<Runtime>::hashed_key().to_vec()
1287            }
1288            FraudProofStorageKeyRequest::SuccessfulBundles(domain_id) => {
1289                pallet_domains::SuccessfulBundles::<Runtime>::hashed_key_for(domain_id)
1290            }
1291            FraudProofStorageKeyRequest::DomainAllowlistUpdates(domain_id) => {
1292                Messenger::domain_allow_list_update_storage_key(domain_id)
1293            }
1294            FraudProofStorageKeyRequest::DomainRuntimeUpgrades => {
1295                pallet_domains::DomainRuntimeUpgrades::<Runtime>::hashed_key().to_vec()
1296            }
1297            FraudProofStorageKeyRequest::RuntimeRegistry(runtime_id) => {
1298                pallet_domains::RuntimeRegistry::<Runtime>::hashed_key_for(runtime_id)
1299            }
1300            FraudProofStorageKeyRequest::DomainSudoCall(domain_id) => {
1301                pallet_domains::DomainSudoCalls::<Runtime>::hashed_key_for(domain_id)
1302            }
1303            FraudProofStorageKeyRequest::EvmDomainContractCreationAllowedByCall(domain_id) => {
1304                pallet_domains::EvmDomainContractCreationAllowedByCalls::<Runtime>::hashed_key_for(
1305                    domain_id,
1306                )
1307            }
1308            FraudProofStorageKeyRequest::MmrRoot(block_number) => {
1309                pallet_subspace_mmr::MmrRootHashes::<Runtime>::hashed_key_for(block_number)
1310            }
1311        }
1312    }
1313}
1314
1315#[cfg(feature = "runtime-benchmarks")]
1316mod benches {
1317    frame_benchmarking::define_benchmarks!(
1318        [frame_benchmarking, BaselineBench::<Runtime>]
1319        [frame_system, SystemBench::<Runtime>]
1320        [pallet_timestamp, Timestamp]
1321        [pallet_subspace, Subspace]
1322        [pallet_subspace_extension, SubspaceExtensionBench::<Runtime>]
1323        [pallet_rewards, Rewards]
1324        [pallet_balances, Balances]
1325        [balance_transfer_check_extension, BalanceTransferCheckBench::<Runtime>]
1326        // pallet_transaction_fees uses a default over-estimated weight
1327        [pallet_transaction_payment, TransactionPayment]
1328        [pallet_utility, Utility]
1329        [pallet_domains, Domains]
1330        [pallet_runtime_configs, RuntimeConfigs]
1331        [pallet_mmr, Mmr]
1332        // pallet_subspace_mmr has no calls to benchmark
1333        [pallet_messenger, Messenger]
1334        [pallet_messenger_from_domains_extension, MessengerFromDomainsExtensionBench::<Runtime>]
1335        [pallet_transporter, Transporter]
1336        [pallet_scheduler, Scheduler]
1337        [pallet_collective, Council]
1338        [pallet_democracy, Democracy]
1339        [pallet_preimage, Preimage]
1340        [pallet_multisig, Multisig]
1341        [pallet_sudo, Sudo]
1342    );
1343}
1344
1345#[cfg(feature = "runtime-benchmarks")]
1346impl frame_system_benchmarking::Config for Runtime {}
1347
1348#[cfg(feature = "runtime-benchmarks")]
1349impl frame_benchmarking::baseline::Config for Runtime {}
1350
1351impl_runtime_apis! {
1352    impl sp_api::Core<Block> for Runtime {
1353        fn version() -> RuntimeVersion {
1354            VERSION
1355        }
1356
1357        fn execute_block(block: Block) {
1358            Executive::execute_block(block);
1359        }
1360
1361        fn initialize_block(header: &HeaderFor<Block>) -> ExtrinsicInclusionMode {
1362            Executive::initialize_block(header)
1363        }
1364    }
1365
1366    impl sp_api::Metadata<Block> for Runtime {
1367        fn metadata() -> OpaqueMetadata {
1368            OpaqueMetadata::new(Runtime::metadata().into())
1369        }
1370
1371        fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
1372            Runtime::metadata_at_version(version)
1373        }
1374
1375        fn metadata_versions() -> Vec<u32> {
1376            Runtime::metadata_versions()
1377        }
1378    }
1379
1380    impl sp_block_builder::BlockBuilder<Block> for Runtime {
1381        fn apply_extrinsic(extrinsic: ExtrinsicFor<Block>) -> ApplyExtrinsicResult {
1382            Executive::apply_extrinsic(extrinsic)
1383        }
1384
1385        fn finalize_block() -> HeaderFor<Block> {
1386            Executive::finalize_block()
1387        }
1388
1389        fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<ExtrinsicFor<Block>> {
1390            data.create_extrinsics()
1391        }
1392
1393        fn check_inherents(
1394            block: Block,
1395            data: sp_inherents::InherentData,
1396        ) -> sp_inherents::CheckInherentsResult {
1397            data.check_extrinsics(&block)
1398        }
1399    }
1400
1401    impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
1402        fn validate_transaction(
1403            source: TransactionSource,
1404            tx: ExtrinsicFor<Block>,
1405            block_hash: BlockHashFor<Block>,
1406        ) -> TransactionValidity {
1407            Executive::validate_transaction(source, tx, block_hash)
1408        }
1409    }
1410
1411    impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
1412        fn offchain_worker(header: &HeaderFor<Block>) {
1413            Executive::offchain_worker(header)
1414        }
1415    }
1416
1417    impl sp_objects::ObjectsApi<Block> for Runtime {
1418        fn extract_block_object_mapping(block: Block) -> BlockObjectMapping {
1419            extract_block_object_mapping(block)
1420        }
1421    }
1422
1423    impl sp_consensus_subspace::SubspaceApi<Block, PublicKey> for Runtime {
1424        fn pot_parameters() -> PotParameters {
1425            Subspace::pot_parameters()
1426        }
1427
1428        fn solution_ranges() -> SolutionRanges {
1429            Subspace::solution_ranges()
1430        }
1431
1432        fn submit_vote_extrinsic(
1433            signed_vote: SignedVote<NumberFor<Block>, BlockHashFor<Block>, PublicKey>,
1434        ) {
1435            let SignedVote { vote, signature } = signed_vote;
1436            let Vote::V0 {
1437                height,
1438                parent_hash,
1439                slot,
1440                solution,
1441                proof_of_time,
1442                future_proof_of_time,
1443            } = vote;
1444
1445            Subspace::submit_vote(SignedVote {
1446                vote: Vote::V0 {
1447                    height,
1448                    parent_hash,
1449                    slot,
1450                    solution: solution.into_reward_address_format::<RewardAddress, AccountId32>(),
1451                    proof_of_time,
1452                    future_proof_of_time,
1453                },
1454                signature,
1455            })
1456        }
1457
1458        fn history_size() -> HistorySize {
1459            <pallet_subspace::Pallet<Runtime>>::history_size()
1460        }
1461
1462        fn max_pieces_in_sector() -> u16 {
1463            MAX_PIECES_IN_SECTOR
1464        }
1465
1466        fn segment_commitment(segment_index: SegmentIndex) -> Option<SegmentCommitment> {
1467            Subspace::segment_commitment(segment_index)
1468        }
1469
1470        fn extract_segment_headers(ext: &ExtrinsicFor<Block>) -> Option<Vec<SegmentHeader >> {
1471            extract_segment_headers(ext)
1472        }
1473
1474        fn is_inherent(ext: &ExtrinsicFor<Block>) -> bool {
1475            match &ext.function {
1476                RuntimeCall::Subspace(call) => Subspace::is_inherent(call),
1477                RuntimeCall::Timestamp(call) => Timestamp::is_inherent(call),
1478                _ => false,
1479            }
1480        }
1481
1482        fn root_plot_public_key() -> Option<PublicKey> {
1483            Subspace::root_plot_public_key()
1484        }
1485
1486        fn should_adjust_solution_range() -> bool {
1487            Subspace::should_adjust_solution_range()
1488        }
1489
1490        fn chain_constants() -> ChainConstants {
1491            ChainConstants::V0 {
1492                confirmation_depth_k: ConfirmationDepthK::get(),
1493                block_authoring_delay: Slot::from(BlockAuthoringDelay::get()),
1494                era_duration: EraDuration::get(),
1495                slot_probability: SlotProbability::get(),
1496                slot_duration: SlotDuration::from_millis(SLOT_DURATION),
1497                recent_segments: RecentSegments::get(),
1498                recent_history_fraction: RecentHistoryFraction::get(),
1499                min_sector_lifetime: MinSectorLifetime::get(),
1500            }
1501        }
1502
1503        fn block_weight() -> Weight {
1504            System::block_weight().total()
1505        }
1506    }
1507
1508    impl sp_domains::DomainsApi<Block, DomainHeader> for Runtime {
1509        fn submit_bundle_unsigned(
1510            opaque_bundle: sp_domains::bundle::OpaqueBundle<NumberFor<Block>, BlockHashFor<Block>, DomainHeader, Balance>,
1511        ) {
1512            Domains::submit_bundle_unsigned(opaque_bundle)
1513        }
1514
1515        fn submit_receipt_unsigned(
1516            singleton_receipt: SealedSingletonReceipt<NumberFor<Block>, BlockHashFor<Block>, DomainHeader, Balance>,
1517        ) {
1518            Domains::submit_receipt_unsigned(singleton_receipt)
1519        }
1520
1521        fn extract_successful_bundles(
1522            domain_id: DomainId,
1523            extrinsics: Vec<ExtrinsicFor<Block>>,
1524        ) -> sp_domains::bundle::OpaqueBundles<Block, DomainHeader, Balance> {
1525            crate::domains::extract_successful_bundles(domain_id, extrinsics)
1526        }
1527
1528        fn extrinsics_shuffling_seed() -> Randomness {
1529            Randomness::from(Domains::extrinsics_shuffling_seed().to_fixed_bytes())
1530        }
1531
1532        fn domain_runtime_code(domain_id: DomainId) -> Option<Vec<u8>> {
1533            Domains::domain_runtime_code(domain_id)
1534        }
1535
1536        fn runtime_id(domain_id: DomainId) -> Option<sp_domains::RuntimeId> {
1537            Domains::runtime_id(domain_id)
1538        }
1539
1540        fn runtime_upgrades() -> Vec<sp_domains::RuntimeId> {
1541            Domains::runtime_upgrades()
1542        }
1543
1544        fn domain_instance_data(domain_id: DomainId) -> Option<(DomainInstanceData, NumberFor<Block>)> {
1545            Domains::domain_instance_data(domain_id)
1546        }
1547
1548        fn domain_timestamp() -> Moment {
1549            Domains::timestamp()
1550        }
1551
1552        fn consensus_transaction_byte_fee() -> Balance {
1553            Domains::consensus_transaction_byte_fee()
1554        }
1555
1556        fn domain_tx_range(domain_id: DomainId) -> U256 {
1557            Domains::domain_tx_range(domain_id)
1558        }
1559
1560        fn genesis_state_root(domain_id: DomainId) -> Option<H256> {
1561            Domains::domain_genesis_block_execution_receipt(domain_id)
1562                .map(|er| *er.final_state_root())
1563        }
1564
1565        fn head_receipt_number(domain_id: DomainId) -> DomainNumber {
1566            Domains::head_receipt_number(domain_id)
1567        }
1568
1569        fn oldest_unconfirmed_receipt_number(domain_id: DomainId) -> Option<DomainNumber> {
1570            Domains::oldest_unconfirmed_receipt_number(domain_id)
1571        }
1572
1573        fn domain_bundle_limit(domain_id: DomainId) -> Option<sp_domains::DomainBundleLimit> {
1574            Domains::domain_bundle_limit(domain_id).ok().flatten()
1575        }
1576
1577        fn non_empty_er_exists(domain_id: DomainId) -> bool {
1578            Domains::non_empty_er_exists(domain_id)
1579        }
1580
1581        fn domain_best_number(domain_id: DomainId) -> Option<DomainNumber> {
1582            Domains::domain_best_number(domain_id).ok()
1583        }
1584
1585        fn execution_receipt(receipt_hash: DomainHash) -> Option<ExecutionReceiptFor<DomainHeader, Block, Balance>> {
1586            Domains::execution_receipt(receipt_hash)
1587        }
1588
1589        fn domain_operators(domain_id: DomainId) -> Option<(BTreeMap<OperatorId, Balance>, Vec<OperatorId>)> {
1590            Domains::domain_staking_summary(domain_id).map(|summary| {
1591                let next_operators = summary.next_operators.into_iter().collect();
1592                (summary.current_operators, next_operators)
1593            })
1594        }
1595
1596        fn receipt_hash(domain_id: DomainId, domain_number: DomainNumber) -> Option<DomainHash> {
1597            Domains::receipt_hash(domain_id, domain_number)
1598        }
1599
1600        fn latest_confirmed_domain_block(domain_id: DomainId) -> Option<(DomainNumber, DomainHash)>{
1601            Domains::latest_confirmed_domain_block(domain_id)
1602        }
1603
1604        fn is_bad_er_pending_to_prune(domain_id: DomainId, receipt_hash: DomainHash) -> bool {
1605            Domains::execution_receipt(receipt_hash).map(
1606                |er| Domains::is_bad_er_pending_to_prune(domain_id, *er.domain_block_number())
1607            )
1608            .unwrap_or(false)
1609        }
1610
1611        fn storage_fund_account_balance(operator_id: OperatorId) -> Balance {
1612            Domains::storage_fund_account_balance(operator_id)
1613        }
1614
1615        fn is_domain_runtime_upgraded_since(domain_id: DomainId, at: NumberFor<Block>) -> Option<bool> {
1616            Domains::is_domain_runtime_upgraded_since(domain_id, at)
1617        }
1618
1619        fn domain_sudo_call(domain_id: DomainId) -> Option<Vec<u8>> {
1620            Domains::domain_sudo_call(domain_id)
1621        }
1622
1623        fn evm_domain_contract_creation_allowed_by_call(domain_id: DomainId) -> Option<PermissionedActionAllowedBy<EthereumAccountId>> {
1624            Domains::evm_domain_contract_creation_allowed_by_call(domain_id)
1625        }
1626
1627        fn last_confirmed_domain_block_receipt(domain_id: DomainId) -> Option<ExecutionReceiptFor<DomainHeader, Block, Balance>>{
1628            Domains::latest_confirmed_domain_execution_receipt(domain_id)
1629        }
1630
1631        fn current_bundle_and_execution_receipt_version() -> BundleAndExecutionReceiptVersion {
1632            Domains::current_bundle_and_execution_receipt_version()
1633        }
1634
1635        fn genesis_execution_receipt(domain_id: DomainId) -> Option<ExecutionReceiptFor<DomainHeader, Block, Balance>> {
1636            Domains::domain_genesis_block_execution_receipt(domain_id)
1637        }
1638
1639        fn nominator_position(
1640            operator_id: OperatorId,
1641            nominator_account: sp_runtime::AccountId32,
1642        ) -> Option<sp_domains::NominatorPosition<Balance, DomainNumber, Balance>> {
1643            Domains::nominator_position(operator_id, nominator_account)
1644        }
1645
1646        fn block_pruning_depth() -> NumberFor<Block> {
1647            BlockTreePruningDepth::get()
1648        }
1649    }
1650
1651    impl sp_domains::BundleProducerElectionApi<Block, Balance> for Runtime {
1652        fn bundle_producer_election_params(domain_id: DomainId) -> Option<BundleProducerElectionParams<Balance>> {
1653            Domains::bundle_producer_election_params(domain_id)
1654        }
1655
1656        fn operator(operator_id: OperatorId) -> Option<(OperatorPublicKey, Balance)> {
1657            Domains::operator(operator_id)
1658        }
1659    }
1660
1661    impl sp_session::SessionKeys<Block> for Runtime {
1662        fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
1663            SessionKeys::generate(seed)
1664        }
1665
1666        fn decode_session_keys(
1667            encoded: Vec<u8>,
1668        ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
1669            SessionKeys::decode_into_raw_public_keys(&encoded)
1670        }
1671    }
1672
1673    impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
1674        fn account_nonce(account: AccountId) -> Nonce {
1675            *System::account_nonce(account)
1676        }
1677    }
1678
1679    impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
1680        fn query_info(
1681            uxt: ExtrinsicFor<Block>,
1682            len: u32,
1683        ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
1684            TransactionPayment::query_info(uxt, len)
1685        }
1686        fn query_fee_details(
1687            uxt: ExtrinsicFor<Block>,
1688            len: u32,
1689        ) -> pallet_transaction_payment::FeeDetails<Balance> {
1690            TransactionPayment::query_fee_details(uxt, len)
1691        }
1692        fn query_weight_to_fee(weight: Weight) -> Balance {
1693            TransactionPayment::weight_to_fee(weight)
1694        }
1695        fn query_length_to_fee(length: u32) -> Balance {
1696            TransactionPayment::length_to_fee(length)
1697        }
1698    }
1699
1700    impl sp_messenger::MessengerApi<Block, BlockNumber, BlockHashFor<Block>> for Runtime {
1701        fn is_xdm_mmr_proof_valid(
1702            ext: &ExtrinsicFor<Block>
1703        ) -> Option<bool> {
1704            is_xdm_mmr_proof_valid(ext)
1705        }
1706
1707        fn extract_xdm_mmr_proof(ext: &ExtrinsicFor<Block>) -> Option<ConsensusChainMmrLeafProof<BlockNumber, BlockHashFor<Block>, sp_core::H256>> {
1708            match &ext.function {
1709                RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })
1710                | RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1711                    Some(msg.proof.consensus_mmr_proof())
1712                }
1713                _ => None,
1714            }
1715        }
1716
1717        fn batch_extract_xdm_mmr_proof(extrinsics: &Vec<ExtrinsicFor<Block>>) -> BTreeMap<u32, ConsensusChainMmrLeafProof<BlockNumber, BlockHashFor<Block>, sp_core::H256>> {
1718            let mut mmr_proofs = BTreeMap::new();
1719            for (index, ext) in extrinsics.iter().enumerate() {
1720                match &ext.function {
1721                    RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })
1722                    | RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1723                        mmr_proofs.insert(index as u32, msg.proof.consensus_mmr_proof());
1724                    }
1725                    _ => {},
1726                }
1727            }
1728            mmr_proofs
1729        }
1730
1731        fn confirmed_domain_block_storage_key(domain_id: DomainId) -> Vec<u8> {
1732            Domains::confirmed_domain_block_storage_key(domain_id)
1733        }
1734
1735        fn outbox_storage_key(message_key: MessageKey) -> Vec<u8> {
1736            Messenger::outbox_storage_key(message_key)
1737        }
1738
1739        fn inbox_response_storage_key(message_key: MessageKey) -> Vec<u8> {
1740            Messenger::inbox_response_storage_key(message_key)
1741        }
1742
1743        fn domain_chains_allowlist_update(domain_id: DomainId) -> Option<DomainAllowlistUpdates>{
1744            Messenger::domain_chains_allowlist_update(domain_id)
1745        }
1746
1747        fn xdm_id(ext: &ExtrinsicFor<Block>) -> Option<XdmId> {
1748            match &ext.function {
1749                RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })=> {
1750                    Some(XdmId::RelayMessage((msg.src_chain_id, msg.channel_id, msg.nonce)))
1751                }
1752                RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1753                    Some(XdmId::RelayResponseMessage((msg.src_chain_id, msg.channel_id, msg.nonce)))
1754                }
1755                _ => None,
1756            }
1757        }
1758
1759        fn channel_nonce(chain_id: ChainId, channel_id: ChannelId) -> Option<ChannelNonce> {
1760            Messenger::channel_nonce(chain_id, channel_id)
1761        }
1762    }
1763
1764    impl sp_messenger::RelayerApi<Block, BlockNumber, BlockNumber, BlockHashFor<Block>> for Runtime {
1765        fn outbox_message_unsigned(msg: CrossDomainMessage<NumberFor<Block>, BlockHashFor<Block>, BlockHashFor<Block>>) -> Option<ExtrinsicFor<Block>> {
1766            Messenger::outbox_message_unsigned(msg)
1767        }
1768
1769        fn inbox_response_message_unsigned(msg: CrossDomainMessage<NumberFor<Block>, BlockHashFor<Block>, BlockHashFor<Block>>) -> Option<ExtrinsicFor<Block>> {
1770            Messenger::inbox_response_message_unsigned(msg)
1771        }
1772
1773        fn updated_channels() -> BTreeSet<(ChainId, ChannelId)> {
1774            Messenger::updated_channels()
1775        }
1776
1777        fn channel_storage_key(chain_id: ChainId, channel_id: ChannelId) -> Vec<u8> {
1778            Messenger::channel_storage_key(chain_id, channel_id)
1779        }
1780
1781        fn open_channels() -> BTreeSet<(ChainId, ChannelId)> {
1782            Messenger::open_channels()
1783        }
1784
1785        fn block_messages_with_query(query: BlockMessagesQuery) -> MessagesWithStorageKey {
1786            Messenger::get_block_messages(query)
1787        }
1788
1789        fn channels_and_state() -> Vec<(ChainId, ChannelId, ChannelStateWithNonce)> {
1790            Messenger::channels_and_states()
1791        }
1792
1793        fn first_outbox_message_nonce_to_relay(dst_chain_id: ChainId, channel_id: ChannelId, from_nonce: XdmNonce) -> Option<XdmNonce> {
1794            Messenger::first_outbox_message_nonce_to_relay(dst_chain_id, channel_id, from_nonce)
1795        }
1796
1797        fn first_inbox_message_response_nonce_to_relay(dst_chain_id: ChainId, channel_id: ChannelId, from_nonce: XdmNonce) -> Option<XdmNonce> {
1798            Messenger::first_inbox_message_response_nonce_to_relay(dst_chain_id, channel_id, from_nonce)
1799        }
1800    }
1801
1802    impl sp_domains_fraud_proof::FraudProofApi<Block, DomainHeader> for Runtime {
1803        fn submit_fraud_proof_unsigned(fraud_proof: FraudProof<NumberFor<Block>, BlockHashFor<Block>, DomainHeader, H256>) {
1804            Domains::submit_fraud_proof_unsigned(fraud_proof)
1805        }
1806
1807        fn fraud_proof_storage_key(req: FraudProofStorageKeyRequest<NumberFor<Block>>) -> Vec<u8> {
1808            <StorageKeyProvider as FraudProofStorageKeyProvider<NumberFor<Block>>>::storage_key(req)
1809        }
1810    }
1811
1812    impl mmr::MmrApi<Block, mmr::Hash, BlockNumber> for Runtime {
1813        fn mmr_root() -> Result<mmr::Hash, mmr::Error> {
1814            Ok(Mmr::mmr_root())
1815        }
1816
1817        fn mmr_leaf_count() -> Result<mmr::LeafIndex, mmr::Error> {
1818            Ok(Mmr::mmr_leaves())
1819        }
1820
1821        fn generate_proof(
1822            block_numbers: Vec<BlockNumber>,
1823            best_known_block_number: Option<BlockNumber>,
1824        ) -> Result<(Vec<mmr::EncodableOpaqueLeaf>, mmr::LeafProof<mmr::Hash>), mmr::Error> {
1825            Mmr::generate_proof(block_numbers, best_known_block_number).map(
1826                |(leaves, proof)| {
1827                    (
1828                        leaves
1829                            .into_iter()
1830                            .map(|leaf| mmr::EncodableOpaqueLeaf::from_leaf(&leaf))
1831                            .collect(),
1832                        proof,
1833                    )
1834                },
1835            )
1836        }
1837
1838        fn verify_proof(leaves: Vec<mmr::EncodableOpaqueLeaf>, proof: mmr::LeafProof<mmr::Hash>)
1839            -> Result<(), mmr::Error>
1840        {
1841            let leaves = leaves.into_iter().map(|leaf|
1842                leaf.into_opaque_leaf()
1843                .try_decode()
1844                .ok_or(mmr::Error::Verify)).collect::<Result<Vec<mmr::Leaf>, mmr::Error>>()?;
1845            Mmr::verify_leaves(leaves, proof)
1846        }
1847
1848        fn verify_proof_stateless(
1849            root: mmr::Hash,
1850            leaves: Vec<mmr::EncodableOpaqueLeaf>,
1851            proof: mmr::LeafProof<mmr::Hash>
1852        ) -> Result<(), mmr::Error> {
1853            let nodes = leaves.into_iter().map(|leaf|mmr::DataOrHash::Data(leaf.into_opaque_leaf())).collect();
1854            pallet_mmr::verify_leaves_proof::<mmr::Hashing, _>(root, nodes, proof)
1855        }
1856    }
1857
1858    impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
1859        fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
1860            build_state::<RuntimeGenesisConfig>(config)
1861        }
1862
1863        fn get_preset(_id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
1864            // By passing `None` the upstream `get_preset` will return the default value of `RuntimeGenesisConfig`
1865            get_preset::<RuntimeGenesisConfig>(&None, |_| None)
1866        }
1867
1868        fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
1869            vec![]
1870        }
1871    }
1872
1873    #[cfg(feature = "runtime-benchmarks")]
1874    impl frame_benchmarking::Benchmark<Block> for Runtime {
1875        fn benchmark_metadata(extra: bool) -> (
1876            Vec<frame_benchmarking::BenchmarkList>,
1877            Vec<frame_support::traits::StorageInfo>,
1878        ) {
1879            use frame_benchmarking::{baseline, BenchmarkList};
1880            use frame_support::traits::StorageInfoTrait;
1881            use frame_system_benchmarking::Pallet as SystemBench;
1882            use baseline::Pallet as BaselineBench;
1883            use pallet_subspace::extensions::benchmarking::Pallet as SubspaceExtensionBench;
1884            use pallet_messenger::extensions::benchmarking_from_domains::Pallet as MessengerFromDomainsExtensionBench;
1885            use subspace_runtime_primitives::extension::benchmarking::Pallet as BalanceTransferCheckBench;
1886
1887            let mut list = Vec::<BenchmarkList>::new();
1888            list_benchmarks!(list, extra);
1889
1890            let storage_info = AllPalletsWithSystem::storage_info();
1891
1892            (list, storage_info)
1893        }
1894
1895        fn dispatch_benchmark(
1896            config: frame_benchmarking::BenchmarkConfig
1897        ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
1898            use frame_benchmarking::{baseline, BenchmarkBatch};
1899            use sp_core::storage::TrackedStorageKey;
1900
1901            use frame_system_benchmarking::Pallet as SystemBench;
1902            use baseline::Pallet as BaselineBench;
1903            use pallet_subspace::extensions::benchmarking::Pallet as SubspaceExtensionBench;
1904            use pallet_messenger::extensions::benchmarking_from_domains::Pallet as MessengerFromDomainsExtensionBench;
1905            use subspace_runtime_primitives::extension::benchmarking::Pallet as BalanceTransferCheckBench;
1906
1907            use frame_support::traits::WhitelistedStorageKeys;
1908            let whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
1909
1910            let mut batches = Vec::<BenchmarkBatch>::new();
1911            let params = (&config, &whitelist);
1912            add_benchmarks!(params, batches);
1913
1914            Ok(batches)
1915        }
1916    }
1917}
1918
1919#[cfg(test)]
1920mod tests {
1921    use crate::{Runtime, SubspaceBlockWeights as BlockWeights};
1922    use pallet_domains::bundle_storage_fund::AccountType;
1923    use sp_domains::OperatorId;
1924    use sp_runtime::traits::AccountIdConversion;
1925    use subspace_runtime_primitives::tests_utils::FeeMultiplierUtils;
1926
1927    #[test]
1928    fn multiplier_can_grow_from_zero() {
1929        FeeMultiplierUtils::<Runtime, BlockWeights>::multiplier_can_grow_from_zero()
1930    }
1931
1932    #[test]
1933    fn test_bundle_storage_fund_account_uniqueness() {
1934        let _: <Runtime as frame_system::Config>::AccountId = <Runtime as pallet_domains::Config>::PalletId::get()
1935            .try_into_sub_account((AccountType::StorageFund, OperatorId::MAX))
1936            .expect(
1937                "The `AccountId` type must be large enough to fit the seed of the bundle storage fund account",
1938            );
1939    }
1940}