subspace_runtime_primitives/
lib.rs

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