subspace_runtime_primitives/
lib.rs

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