Skip to main content

subspace_runtime_primitives/
lib.rs

1//! Runtime primitives for Subspace Network.
2#![cfg_attr(not(feature = "std"), no_std)]
3
4pub mod extension;
5pub mod utility;
6pub mod weights;
7
8#[cfg(not(feature = "std"))]
9extern crate alloc;
10
11use crate::time::{BLOCKS_IN_A_DAY, BLOCKS_IN_AN_MINUTE};
12#[cfg(not(feature = "std"))]
13use alloc::vec::Vec;
14use core::marker::PhantomData;
15use frame_support::dispatch::{DispatchClass, DispatchResult};
16use frame_support::pallet_prelude::Weight;
17use frame_support::traits::tokens;
18use frame_support::weights::WeightToFee;
19use frame_support::weights::constants::WEIGHT_REF_TIME_PER_SECOND;
20use frame_support::{Deserialize, Serialize};
21use frame_system::limits::BlockLength;
22use frame_system::offchain::CreateTransactionBase;
23use frame_system::pallet_prelude::BlockNumberFor;
24use pallet_transaction_payment::{
25    Multiplier, NextFeeMultiplier, OnChargeTransaction, TargetedFeeAdjustment,
26};
27use parity_scale_codec::{Codec, Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
28use scale_info::TypeInfo;
29use sp_core::parameter_types;
30use sp_runtime::traits::{Block as BlockT, Bounded, Header as HeaderT, IdentifyAccount, Verify};
31use sp_runtime::{FixedPointNumber, MultiSignature, Perbill, Perquintill};
32pub use subspace_core_primitives::BlockNumber;
33
34/// Minimum desired number of replicas of the blockchain to be stored by the network,
35/// impacts storage fees.
36pub const MIN_REPLICATION_FACTOR: u16 = 25;
37
38/// The smallest unit of the token is called Shannon.
39pub const SHANNON: Balance = 1;
40/// Subspace Credits have 18 decimal places.
41pub const DECIMAL_PLACES: u8 = 18;
42/// One Subspace Credit.
43pub const AI3: Balance = (10 * SHANNON).pow(DECIMAL_PLACES as u32);
44/// A ratio of `Normal` dispatch class within block, for `BlockWeight` and `BlockLength`.
45pub const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
46/// 1 in 6 slots (on average, not counting collisions) will have a block.
47/// Must match ratio between block and slot duration in constants above.
48pub const SLOT_PROBABILITY: (u64, u64) = (1, 6);
49/// The block weight for 2 seconds of compute
50pub const BLOCK_WEIGHT_FOR_2_SEC: Weight =
51    Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2), u64::MAX);
52
53/// Maximum block length for non-`Normal` extrinsic is 5 MiB.
54pub const MAX_BLOCK_LENGTH: u32 = 5 * 1024 * 1024;
55
56/// Pruning depth multiplier for state and blocks pruning.
57pub const DOMAINS_PRUNING_DEPTH_MULTIPLIER: u32 = 2;
58
59/// We allow for 3.75 MiB for `Normal` extrinsic with 5 MiB maximum block length.
60pub fn maximum_normal_block_length() -> BlockLength {
61    BlockLength::builder()
62        .max_length(MAX_BLOCK_LENGTH)
63        .modify_max_length_for_class(DispatchClass::Normal, |max| {
64            *max = NORMAL_DISPATCH_RATIO * MAX_BLOCK_LENGTH
65        })
66        .build()
67}
68
69/// The maximum recursion depth we allow when parsing calls.
70/// This is a safety measure to avoid stack overflows.
71///
72/// Deeper nested calls can result in an error, or, if it is secure, the call is skipped.
73/// (Some code does unlimited heap-based recursion via `nested_utility_call_iter()`.)
74pub const MAX_CALL_RECURSION_DEPTH: u32 = 10;
75
76/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.
77pub type Signature = MultiSignature;
78
79/// Some way of identifying an account on the chain. We intentionally make it equivalent
80/// to the public key of our transaction signing scheme.
81//
82// Note: sometimes this type alias causes complex trait ambiguity / conflicting implementation errors.
83// As a workaround, `use sp_runtime::AccountId32 as AccountId` instead.
84pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;
85
86/// Balance of an account.
87pub type Balance = u128;
88
89/// Index of a transaction in the chain.
90pub type Nonce = u32;
91
92/// A hash of some data used by the chain.
93pub type Hash = sp_core::H256;
94
95/// Type used for expressing timestamp.
96pub type Moment = u64;
97
98/// Type alias for extrinsics.
99pub type ExtrinsicFor<Block> = <Block as BlockT>::Extrinsic;
100
101/// Type alias for block hash.
102pub type BlockHashFor<Block> = <Block as BlockT>::Hash;
103
104/// Type alias for block header.
105pub type HeaderFor<Block> = <Block as BlockT>::Header;
106
107/// Type alias for block hashing.
108pub type BlockHashingFor<Block> = <HeaderFor<Block> as HeaderT>::Hashing;
109
110parameter_types! {
111    /// Event segments are disabled on the consensus chain.
112    pub const ConsensusEventSegmentSize: u32 = 0;
113    /// Event segments are enabled on domain chains, this value was derived from benchmarking.
114    pub const DomainEventSegmentSize: u32 = 100;
115}
116
117/// Opaque types.
118///
119/// These are used by the CLI to instantiate machinery that don't need to know the specifics of the
120/// runtime. They can then be made to be agnostic over specific formats of data like extrinsics,
121/// allowing for them to continue syncing the network through upgrades to even the core data
122/// structures.
123pub mod opaque {
124    use super::BlockNumber;
125    pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
126    use sp_runtime::generic;
127    use sp_runtime::traits::BlakeTwo256;
128
129    /// Opaque block header type.
130    pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
131    /// Opaque block type.
132    pub type Block = generic::Block<Header, UncheckedExtrinsic>;
133}
134
135pub mod time {
136    /// Expected block time in milliseconds.
137    ///
138    /// Since Subspace is probabilistic this is the average expected block time that
139    /// we are targeting. Blocks will be produced at a minimum duration defined
140    /// by `SLOT_DURATION`, but some slots will not be allocated to any
141    /// farmer and hence no block will be produced. We expect to have this
142    /// block time on average following the defined slot duration and the value
143    /// of `c` configured for Subspace (where `1 - c` represents the probability of
144    /// a slot being empty).
145    /// This value is only used indirectly to define the unit constants below
146    /// that are expressed in blocks. The rest of the code should use
147    /// `SLOT_DURATION` instead (like the Timestamp pallet for calculating the
148    /// minimum period).
149    ///
150    /// Based on:
151    /// <https://research.web3.foundation/en/latest/polkadot/block-production/Babe.html#-6.-practical-results>
152    pub const MILLISECS_PER_BLOCK: u64 = 6000;
153    /// Approximate number of block in a minute.
154    pub const BLOCKS_IN_AN_MINUTE: u32 = (60 * 1000) / MILLISECS_PER_BLOCK as u32;
155    /// Approximate number of blocks in an hour.
156    pub const BLOCKS_IN_AN_HOUR: u32 = 60 * BLOCKS_IN_AN_MINUTE;
157    /// Approximate number of blocks in a day.
158    pub const BLOCKS_IN_A_DAY: u32 = 24 * BLOCKS_IN_AN_HOUR;
159}
160
161#[derive(Copy, Clone, Encode, Decode, TypeInfo, Serialize, Deserialize, MaxEncodedLen, Debug)]
162pub struct CouncilDemocracyConfigParams<BlockNumber> {
163    /// Council motion duration.
164    pub council_motion_duration: BlockNumber,
165    /// Democracy cooloff period.
166    pub democracy_cooloff_period: BlockNumber,
167    /// Democracy enactment period.
168    pub democracy_enactment_period: BlockNumber,
169    /// Fast track voting period.
170    pub democracy_fast_track_voting_period: BlockNumber,
171    /// Launch period.
172    pub democracy_launch_period: BlockNumber,
173    /// Vote locking period.
174    pub democracy_vote_locking_period: BlockNumber,
175    /// Voting period.
176    pub democracy_voting_period: BlockNumber,
177}
178
179impl<BlockNumber: From<u32>> Default for CouncilDemocracyConfigParams<BlockNumber> {
180    fn default() -> Self {
181        Self {
182            council_motion_duration: BLOCKS_IN_A_DAY.into(),
183            democracy_cooloff_period: BLOCKS_IN_A_DAY.into(),
184            democracy_enactment_period: BLOCKS_IN_A_DAY.into(),
185            democracy_fast_track_voting_period: (2 * BLOCKS_IN_A_DAY).into(),
186            democracy_launch_period: (2 * BLOCKS_IN_A_DAY).into(),
187            democracy_vote_locking_period: BLOCKS_IN_A_DAY.into(),
188            democracy_voting_period: BLOCKS_IN_A_DAY.into(),
189        }
190    }
191}
192
193impl<BlockNumber: From<u32>> CouncilDemocracyConfigParams<BlockNumber> {
194    /// Production params for Council democracy config.
195    pub fn production_params() -> Self {
196        Self::default()
197    }
198
199    /// Fast period params for Council democracy config.
200    pub fn fast_params() -> Self {
201        Self {
202            council_motion_duration: (15 * BLOCKS_IN_AN_MINUTE).into(),
203            democracy_cooloff_period: (5 * BLOCKS_IN_AN_MINUTE).into(),
204            democracy_enactment_period: (15 * BLOCKS_IN_AN_MINUTE).into(),
205            democracy_fast_track_voting_period: (5 * BLOCKS_IN_AN_MINUTE).into(),
206            democracy_launch_period: (15 * BLOCKS_IN_AN_MINUTE).into(),
207            democracy_vote_locking_period: BLOCKS_IN_AN_MINUTE.into(),
208            democracy_voting_period: (15 * BLOCKS_IN_AN_MINUTE).into(),
209        }
210    }
211}
212/// Config parameters for genesis.
213pub struct GenesisConfigParams {
214    /// Confirmation depth K
215    pub confirmation_depth_k: BlockNumber,
216    /// Domain pruning depth.
217    pub domain_block_pruning_depth: BlockNumber,
218    /// Staking withdrawal period.
219    pub staking_withdrawal_period: BlockNumber,
220}
221
222impl GenesisConfigParams {
223    /// Production specific domain parameters.
224    pub const fn production_params() -> Self {
225        Self {
226            confirmation_depth_k: 100u32,
227            domain_block_pruning_depth: 14_400u32,
228            staking_withdrawal_period: 14_400u32,
229        }
230    }
231
232    /// Development specific domain parameters.
233    pub const fn dev_params() -> Self {
234        Self {
235            confirmation_depth_k: 5u32,
236            domain_block_pruning_depth: 5u32,
237            staking_withdrawal_period: 5u32,
238        }
239    }
240}
241
242/// A trait for determining whether rewards are enabled or not
243pub trait RewardsEnabled {
244    /// Determine whether rewards are enabled or not
245    fn rewards_enabled() -> bool;
246}
247
248/// A trait for finding the address for a block reward based on the `PreRuntime` digests contained within it.
249pub trait FindBlockRewardAddress<RewardAddress> {
250    /// Find the address for a block rewards based on the pre-runtime digests.
251    fn find_block_reward_address() -> Option<RewardAddress>;
252}
253
254/// A trait for finding the addresses for voting reward based on transactions found in the block.
255pub trait FindVotingRewardAddresses<RewardAddress> {
256    /// Find the addresses for voting rewards based on transactions found in the block.
257    fn find_voting_reward_addresses() -> Vec<RewardAddress>;
258}
259
260pub trait StorageFee<Balance> {
261    /// Return the consensus transaction byte fee.
262    fn transaction_byte_fee() -> Balance;
263
264    /// Note the charged storage fee.
265    fn note_storage_fees(fee: Balance);
266}
267
268parameter_types! {
269    /// The portion of the `NORMAL_DISPATCH_RATIO` that we adjust the fees with. Blocks filled less
270    /// than this will decrease the weight and more will increase.
271    pub const TargetBlockFullness: Perquintill = Perquintill::from_percent(50);
272    /// The adjustment variable of the runtime. Higher values will cause `TargetBlockFullness` to
273    /// change the fees more rapidly.
274    pub AdjustmentVariable: Multiplier = Multiplier::saturating_from_rational(75, 1_000_000);
275    /// Minimum amount of the multiplier. This value cannot be too low. A test case should ensure
276    /// that combined with `AdjustmentVariable`, we can recover from the minimum.
277    /// See `multiplier_can_grow_from_zero`.
278    pub MinimumMultiplier: Multiplier = Multiplier::saturating_from_rational(1, 10u128);
279    /// The maximum amount of the multiplier.
280    pub MaximumMultiplier: Multiplier = Bounded::max_value();
281}
282
283/// Parameterized slow adjusting fee updated based on
284/// <https://research.web3.foundation/Polkadot/overview/token-economics#2-slow-adjusting-mechanism>
285pub type SlowAdjustingFeeUpdate<R, TargetBlockFullness> = TargetedFeeAdjustment<
286    R,
287    TargetBlockFullness,
288    AdjustmentVariable,
289    MinimumMultiplier,
290    MaximumMultiplier,
291>;
292
293#[derive(Encode, Decode, TypeInfo)]
294pub struct BlockTransactionByteFee<Balance: Codec> {
295    // The value of `transaction_byte_fee` for the current block
296    pub current: Balance,
297    // The value of `transaction_byte_fee` for the next block
298    pub next: Balance,
299}
300
301impl<Balance: Codec + tokens::Balance> Default for BlockTransactionByteFee<Balance> {
302    fn default() -> Self {
303        BlockTransactionByteFee {
304            current: Balance::max_value(),
305            next: Balance::max_value(),
306        }
307    }
308}
309
310parameter_types! {
311    pub const XdmFeeMultipler: u32 = 5;
312}
313
314/// Balance type pointing to the OnChargeTransaction trait.
315pub type OnChargeTransactionBalance<T> = <<T as pallet_transaction_payment::Config>::OnChargeTransaction as OnChargeTransaction<
316    T,
317>>::Balance;
318
319/// Adjusted XDM Weight to fee Conversion.
320pub struct XdmAdjustedWeightToFee<T>(PhantomData<T>);
321impl<T: pallet_transaction_payment::Config> WeightToFee for XdmAdjustedWeightToFee<T> {
322    type Balance = OnChargeTransactionBalance<T>;
323
324    fn weight_to_fee(weight: &Weight) -> Self::Balance {
325        // the adjustable part of the fee.
326        let unadjusted_weight_fee = pallet_transaction_payment::Pallet::<T>::weight_to_fee(*weight);
327        let multiplier = NextFeeMultiplier::<T>::get();
328        // final adjusted weight fee.
329        multiplier.saturating_mul_int(unadjusted_weight_fee)
330    }
331}
332
333#[derive(
334    PartialEq,
335    Eq,
336    Clone,
337    Encode,
338    Decode,
339    TypeInfo,
340    MaxEncodedLen,
341    Ord,
342    PartialOrd,
343    Copy,
344    Debug,
345    DecodeWithMemTracking,
346)]
347pub enum HoldIdentifier {
348    DomainStaking,
349    DomainInstantiation,
350    DomainStorageFund,
351    MessengerChannel,
352    Preimage,
353}
354
355/// Interface for creating an unsigned general extrinsic
356pub trait CreateUnsigned<LocalCall>: CreateTransactionBase<LocalCall> {
357    /// Create an unsigned extrinsic.
358    fn create_unsigned(call: Self::RuntimeCall) -> Self::Extrinsic;
359}
360
361/// Callback to do something before setting code.
362pub trait OnSetCode<Number> {
363    /// Do something before setting code at the block number.
364    fn set_code(block_number: Number) -> DispatchResult;
365}
366
367/// Implements [frame_system::SetCode]
368pub struct SetCode<Runtime, OSC>(PhantomData<(Runtime, OSC)>);
369impl<Runtime, OSC> frame_system::SetCode<Runtime> for SetCode<Runtime, OSC>
370where
371    Runtime: frame_system::Config,
372    OSC: OnSetCode<BlockNumberFor<Runtime>>,
373{
374    fn set_code(code: Vec<u8>) -> DispatchResult {
375        let current_block_number = frame_system::Pallet::<Runtime>::block_number();
376        OSC::set_code(current_block_number)?;
377        frame_system::Pallet::<Runtime>::update_code_in_storage(&code);
378        Ok(())
379    }
380}
381
382#[cfg(feature = "testing")]
383pub mod tests_utils {
384    use frame_support::dispatch::DispatchClass;
385    use frame_support::weights::Weight;
386    use frame_system::limits::BlockWeights;
387    use pallet_transaction_payment::{Multiplier, MultiplierUpdate};
388    use sp_runtime::BuildStorage;
389    use sp_runtime::traits::{Convert, Get};
390    use std::marker::PhantomData;
391
392    pub struct FeeMultiplierUtils<Runtime, BlockWeightsGetter>(
393        PhantomData<(Runtime, BlockWeightsGetter)>,
394    );
395
396    impl<Runtime, BlockWeightsGetter> FeeMultiplierUtils<Runtime, BlockWeightsGetter>
397    where
398        Runtime: frame_system::Config + pallet_transaction_payment::Config,
399        BlockWeightsGetter: Get<BlockWeights>,
400    {
401        fn max_normal() -> Weight {
402            let block_weights = BlockWeightsGetter::get();
403            block_weights
404                .get(DispatchClass::Normal)
405                .max_total
406                .unwrap_or(block_weights.max_block)
407        }
408
409        fn min_multiplier() -> Multiplier {
410            <Runtime as pallet_transaction_payment::Config>::FeeMultiplierUpdate::min()
411        }
412
413        fn target() -> Weight {
414            <Runtime as pallet_transaction_payment::Config>::FeeMultiplierUpdate::target()
415                * Self::max_normal()
416        }
417
418        // update based on runtime impl.
419        fn runtime_multiplier_update(fm: Multiplier) -> Multiplier {
420            <Runtime as pallet_transaction_payment::Config>::FeeMultiplierUpdate::convert(fm)
421        }
422
423        fn run_with_system_weight<F>(w: Weight, assertions: F)
424        where
425            F: Fn(),
426        {
427            let mut t: sp_io::TestExternalities = frame_system::GenesisConfig::<Runtime>::default()
428                .build_storage()
429                .unwrap()
430                .into();
431            t.execute_with(|| {
432                frame_system::Pallet::<Runtime>::set_block_consumed_resources(w, 0);
433                assertions()
434            });
435        }
436
437        // The following function is taken from test with same name from
438        // https://github.com/paritytech/polkadot-sdk/blob/91851951856b8effe627fb1d151fe336a51eef2d/substrate/bin/node/runtime/src/impls.rs#L234
439        // with some small surface changes.
440        pub fn multiplier_can_grow_from_zero()
441        where
442            Runtime: pallet_transaction_payment::Config,
443            BlockWeightsGetter: Get<BlockWeights>,
444        {
445            // if the min is too small, then this will not change, and we are doomed forever.
446            // the block ref time is 1/100th bigger than target.
447            Self::run_with_system_weight(
448                Self::target().set_ref_time((Self::target().ref_time() / 100) * 101),
449                || {
450                    let next = Self::runtime_multiplier_update(Self::min_multiplier());
451                    assert!(
452                        next > Self::min_multiplier(),
453                        "{:?} !> {:?}",
454                        next,
455                        Self::min_multiplier()
456                    );
457                },
458            );
459
460            // the block proof size is 1/100th bigger than target.
461            Self::run_with_system_weight(
462                Self::target().set_proof_size((Self::target().proof_size() / 100) * 101),
463                || {
464                    let next = Self::runtime_multiplier_update(Self::min_multiplier());
465                    assert!(
466                        next > Self::min_multiplier(),
467                        "{:?} !> {:?}",
468                        next,
469                        Self::min_multiplier()
470                    );
471                },
472            )
473        }
474    }
475}