subspace_runtime_primitives/
lib.rs1#![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
34pub const MIN_REPLICATION_FACTOR: u16 = 25;
37
38pub const SHANNON: Balance = 1;
40pub const DECIMAL_PLACES: u8 = 18;
42pub const AI3: Balance = (10 * SHANNON).pow(DECIMAL_PLACES as u32);
44pub const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
46pub const SLOT_PROBABILITY: (u64, u64) = (1, 6);
49pub const BLOCK_WEIGHT_FOR_2_SEC: Weight =
51 Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2), u64::MAX);
52
53pub const MAX_BLOCK_LENGTH: u32 = 5 * 1024 * 1024;
55
56pub const DOMAINS_PRUNING_DEPTH_MULTIPLIER: u32 = 2;
58
59pub 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
69pub const MAX_CALL_RECURSION_DEPTH: u32 = 10;
75
76pub type Signature = MultiSignature;
78
79pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;
85
86pub type Balance = u128;
88
89pub type Nonce = u32;
91
92pub type Hash = sp_core::H256;
94
95pub type Moment = u64;
97
98pub type ExtrinsicFor<Block> = <Block as BlockT>::Extrinsic;
100
101pub type BlockHashFor<Block> = <Block as BlockT>::Hash;
103
104pub type HeaderFor<Block> = <Block as BlockT>::Header;
106
107pub type BlockHashingFor<Block> = <HeaderFor<Block> as HeaderT>::Hashing;
109
110parameter_types! {
111 pub const ConsensusEventSegmentSize: u32 = 0;
113 pub const DomainEventSegmentSize: u32 = 100;
115}
116
117pub 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 pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
131 pub type Block = generic::Block<Header, UncheckedExtrinsic>;
133}
134
135pub mod time {
136 pub const MILLISECS_PER_BLOCK: u64 = 6000;
153 pub const BLOCKS_IN_AN_MINUTE: u32 = (60 * 1000) / MILLISECS_PER_BLOCK as u32;
155 pub const BLOCKS_IN_AN_HOUR: u32 = 60 * BLOCKS_IN_AN_MINUTE;
157 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 pub council_motion_duration: BlockNumber,
165 pub democracy_cooloff_period: BlockNumber,
167 pub democracy_enactment_period: BlockNumber,
169 pub democracy_fast_track_voting_period: BlockNumber,
171 pub democracy_launch_period: BlockNumber,
173 pub democracy_vote_locking_period: BlockNumber,
175 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 pub fn production_params() -> Self {
196 Self::default()
197 }
198
199 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}
212pub struct GenesisConfigParams {
214 pub confirmation_depth_k: BlockNumber,
216 pub domain_block_pruning_depth: BlockNumber,
218 pub staking_withdrawal_period: BlockNumber,
220}
221
222impl GenesisConfigParams {
223 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 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
242pub trait RewardsEnabled {
244 fn rewards_enabled() -> bool;
246}
247
248pub trait FindBlockRewardAddress<RewardAddress> {
250 fn find_block_reward_address() -> Option<RewardAddress>;
252}
253
254pub trait FindVotingRewardAddresses<RewardAddress> {
256 fn find_voting_reward_addresses() -> Vec<RewardAddress>;
258}
259
260pub trait StorageFee<Balance> {
261 fn transaction_byte_fee() -> Balance;
263
264 fn note_storage_fees(fee: Balance);
266}
267
268parameter_types! {
269 pub const TargetBlockFullness: Perquintill = Perquintill::from_percent(50);
272 pub AdjustmentVariable: Multiplier = Multiplier::saturating_from_rational(75, 1_000_000);
275 pub MinimumMultiplier: Multiplier = Multiplier::saturating_from_rational(1, 10u128);
279 pub MaximumMultiplier: Multiplier = Bounded::max_value();
281}
282
283pub 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 pub current: Balance,
297 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
314pub type OnChargeTransactionBalance<T> = <<T as pallet_transaction_payment::Config>::OnChargeTransaction as OnChargeTransaction<
316 T,
317>>::Balance;
318
319pub 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 let unadjusted_weight_fee = pallet_transaction_payment::Pallet::<T>::weight_to_fee(*weight);
327 let multiplier = NextFeeMultiplier::<T>::get();
328 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
355pub trait CreateUnsigned<LocalCall>: CreateTransactionBase<LocalCall> {
357 fn create_unsigned(call: Self::RuntimeCall) -> Self::Extrinsic;
359}
360
361pub trait OnSetCode<Number> {
363 fn set_code(block_number: Number) -> DispatchResult;
365}
366
367pub 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 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 pub fn multiplier_can_grow_from_zero()
441 where
442 Runtime: pallet_transaction_payment::Config,
443 BlockWeightsGetter: Get<BlockWeights>,
444 {
445 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 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}