diff --git a/Cargo.lock b/Cargo.lock index f548d2d8d..56299ecb5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4953,6 +4953,7 @@ name = "integration-tests" version = "1.0.0" dependencies = [ "assets-common", + "cumulus-pallet-parachain-system", "cumulus-pallet-xcm", "cumulus-primitives-core", "frame-metadata-hash-extension", @@ -8090,6 +8091,8 @@ dependencies = [ name = "pallet-funding" version = "1.0.0" dependencies = [ + "cumulus-pallet-parachain-system", + "cumulus-primitives-core", "frame-benchmarking", "frame-support", "frame-system", @@ -13993,6 +13996,7 @@ dependencies = [ name = "shared-configuration" version = "1.0.0" dependencies = [ + "cumulus-primitives-core", "frame-support", "frame-system", "orml-traits", diff --git a/integration-tests/Cargo.toml b/integration-tests/Cargo.toml index e1d7c9e96..64e54120a 100644 --- a/integration-tests/Cargo.toml +++ b/integration-tests/Cargo.toml @@ -51,6 +51,7 @@ pallet-elections-phragmen.workspace = true pallet-message-queue.workspace = true cumulus-primitives-core.workspace = true cumulus-pallet-xcm.workspace = true +cumulus-pallet-parachain-system.workspace = true parachain-info.workspace = true parachains-common.workspace = true @@ -151,6 +152,7 @@ std = [ "xcm-executor/std", "xcm-runtime-apis/std", "xcm/std", + "cumulus-pallet-parachain-system/std" ] development-settings = [ "polimec-runtime/development-settings" ] runtime-benchmarks = [ @@ -193,5 +195,6 @@ runtime-benchmarks = [ "xcm-executor/runtime-benchmarks", "xcm-runtime-apis/runtime-benchmarks", "assets-common/runtime-benchmarks", - "pallet-transaction-payment/runtime-benchmarks" + "pallet-transaction-payment/runtime-benchmarks", + "cumulus-pallet-parachain-system/runtime-benchmarks" ] diff --git a/integration-tests/src/tests/e2e.rs b/integration-tests/src/tests/e2e.rs index 1481154b8..d0dddc336 100644 --- a/integration-tests/src/tests/e2e.rs +++ b/integration-tests/src/tests/e2e.rs @@ -583,7 +583,7 @@ fn e2e_test() { assert_close_enough!(sub_account_held_plmc, plmc_balance, Perquintill::from_float(0.999)); let otm_duration = Multiplier::force_new(5).calculate_vesting_duration::(); - let now = PolimecSystem::block_number(); + let now = PolkadotSystem::block_number(); inst.jump_to_block(now + otm_duration); let treasury_account = ::Treasury::get(); diff --git a/pallets/democracy/src/lib.rs b/pallets/democracy/src/lib.rs index 1e9e01dd0..efddb9fa6 100644 --- a/pallets/democracy/src/lib.rs +++ b/pallets/democracy/src/lib.rs @@ -163,10 +163,10 @@ use frame_support::{ }, weights::Weight, }; -use frame_system::pallet_prelude::{BlockNumberFor, OriginFor}; +use frame_system::pallet_prelude::OriginFor; use parity_scale_codec::{Decode, Encode}; use sp_runtime::{ - traits::{Bounded as ArithBounded, One, Saturating, StaticLookup, Zero}, + traits::{BlockNumberProvider, Bounded as ArithBounded, One, Saturating, StaticLookup, Zero}, ArithmeticError, DispatchError, DispatchResult, }; @@ -199,11 +199,12 @@ pub type CreditOf = Credit<::AccountId, = ::RuntimeCall; pub type BoundedCallOf = Bounded, ::Hashing>; +pub type BlockNumberFor = <::BlockNumberProvider as BlockNumberProvider>::BlockNumber; type AccountIdLookupOf = <::Lookup as StaticLookup>::Source; #[frame_support::pallet] pub mod pallet { - use super::{DispatchResult, *}; + use super::{BlockNumberFor, DispatchResult, *}; use frame_support::{ pallet_prelude::*, traits::{ @@ -212,6 +213,7 @@ pub mod pallet { }, }; use frame_system::pallet_prelude::*; + use sp_runtime::traits::BlockNumberProvider; /// The current storage version. const STORAGE_VERSION: StorageVersion = StorageVersion::new(1); @@ -350,6 +352,9 @@ pub mod pallet { /// Type returning the total electorate. type Electorate: GetElectorate>; + + /// Block number provider. + type BlockNumberProvider: BlockNumberProvider>; } /// The number of (public) proposals that have been made so far. @@ -610,7 +615,7 @@ pub mod pallet { let proposal_hash = proposal.hash(); if let Some((until, _)) = >::get(proposal_hash) { - ensure!(>::block_number() >= until, Error::::ProposalBlacklisted,); + ensure!(T::BlockNumberProvider::current_block_number() >= until, Error::::ProposalBlacklisted,); } T::Fungible::hold(&HoldReason::Proposal.into(), &who, value)?; @@ -700,7 +705,7 @@ pub mod pallet { T::ExternalOrigin::ensure_origin(origin)?; ensure!(!>::exists(), Error::::DuplicateProposal); if let Some((until, _)) = >::get(proposal.hash()) { - ensure!(>::block_number() >= until, Error::::ProposalBlacklisted,); + ensure!(T::BlockNumberProvider::current_block_number() >= until, Error::::ProposalBlacklisted,); } >::put((proposal, VoteThreshold::SuperMajorityApprove)); Ok(()) @@ -790,7 +795,7 @@ pub mod pallet { ensure!(proposal_hash == ext_proposal.hash(), Error::::InvalidHash); >::kill(); - let now = >::block_number(); + let now = T::BlockNumberProvider::current_block_number(); let ref_index = Self::inject_referendum(now.saturating_add(voting_period), ext_proposal, threshold, delay); Self::transfer_metadata(MetadataOwner::External, MetadataOwner::Referendum(ref_index)); Ok(()) @@ -820,7 +825,7 @@ pub mod pallet { let insert_position = existing_vetoers.binary_search(&who).err().ok_or(Error::::AlreadyVetoed)?; existing_vetoers.try_insert(insert_position, who.clone()).map_err(|_| Error::::TooMany)?; - let until = >::block_number().saturating_add(T::CooloffPeriod::get()); + let until = T::BlockNumberProvider::current_block_number().saturating_add(T::CooloffPeriod::get()); >::insert(&proposal_hash, (until, existing_vetoers)); Self::deposit_event(Event::::Vetoed { who, proposal_hash, until }); @@ -1196,7 +1201,7 @@ impl Pallet { delay: BlockNumberFor, ) -> ReferendumIndex { >::inject_referendum( - >::block_number().saturating_add(T::VotingPeriod::get()), + T::BlockNumberProvider::current_block_number().saturating_add(T::VotingPeriod::get()), proposal, threshold, delay, @@ -1291,7 +1296,7 @@ impl Pallet { if let Some((lock_periods, balance)) = votes[i].1.locked_if(approved) { let unlock_at = end.saturating_add(T::VoteLockingPeriod::get().saturating_mul(lock_periods.into())); - let now = frame_system::Pallet::::block_number(); + let now = T::BlockNumberProvider::current_block_number(); if now < unlock_at { ensure!(matches!(scope, UnvoteScope::Any), Error::::NoPermission); prior.accumulate(unlock_at, balance) @@ -1380,7 +1385,7 @@ impl Pallet { Voting::Delegating { balance, target, conviction, delegations, mut prior, .. } => { // remove any delegation votes to our current target. Self::reduce_upstream_delegation(&target, conviction.votes(balance)); - let now = frame_system::Pallet::::block_number(); + let now = T::BlockNumberProvider::current_block_number(); let lock_periods = conviction.lock_periods().into(); let unlock_block = now.saturating_add(T::VoteLockingPeriod::get().saturating_mul(lock_periods)); prior.accumulate(unlock_block, balance); @@ -1413,7 +1418,7 @@ impl Pallet { Voting::Delegating { balance, target, conviction, delegations, mut prior } => { // remove any delegation votes to our current target. let votes = Self::reduce_upstream_delegation(&target, conviction.votes(balance)); - let now = frame_system::Pallet::::block_number(); + let now = T::BlockNumberProvider::current_block_number(); let lock_periods = conviction.lock_periods().into(); let unlock_block = now.saturating_add(T::VoteLockingPeriod::get().saturating_mul(lock_periods)); prior.accumulate(unlock_block, balance); @@ -1432,7 +1437,7 @@ impl Pallet { /// a security hole) but may be reduced from what they are currently. fn update_lock(who: &T::AccountId) -> DispatchResult { let lock_needed = VotingOf::::mutate(who, |voting| { - voting.rejig(frame_system::Pallet::::block_number()); + voting.rejig(T::BlockNumberProvider::current_block_number()); voting.locked_balance() }); if lock_needed.is_zero() { diff --git a/pallets/democracy/src/tests.rs b/pallets/democracy/src/tests.rs index 7d3bae8d7..90fdbb4b4 100644 --- a/pallets/democracy/src/tests.rs +++ b/pallets/democracy/src/tests.rs @@ -149,6 +149,7 @@ impl GetElectorate> for Electorate { impl Config for Test { type BlacklistOrigin = EnsureRoot; + type BlockNumberProvider = System; type CancelProposalOrigin = EnsureRoot; type CancellationOrigin = EnsureSignedBy; type CooloffPeriod = ConstU64<2>; diff --git a/pallets/dispenser/src/lib.rs b/pallets/dispenser/src/lib.rs index edb4fac43..d3f1805db 100644 --- a/pallets/dispenser/src/lib.rs +++ b/pallets/dispenser/src/lib.rs @@ -55,7 +55,7 @@ pub mod pallet { pallet_prelude::{ValueQuery, *}, PalletId, }; - use frame_system::pallet_prelude::*; + use frame_system::pallet_prelude::{BlockNumberFor, *}; use sp_runtime::{ traits::{AccountIdConversion, CheckedDiv}, Saturating, diff --git a/pallets/funding/Cargo.toml b/pallets/funding/Cargo.toml index 3f70b757f..4d4373100 100644 --- a/pallets/funding/Cargo.toml +++ b/pallets/funding/Cargo.toml @@ -50,6 +50,8 @@ hex.workspace = true # Used in the instantiator. itertools.workspace = true sp-io.workspace = true +cumulus-pallet-parachain-system.workspace = true +cumulus-primitives-core.workspace = true [dev-dependencies] pallet-timestamp.workspace = true @@ -92,6 +94,8 @@ std = [ "xcm-builder/std", "xcm-executor/std", "xcm/std", + "cumulus-pallet-parachain-system/std", + "cumulus-primitives-core/std" ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", @@ -112,6 +116,8 @@ runtime-benchmarks = [ "sp-runtime/runtime-benchmarks", "xcm-builder/runtime-benchmarks", "xcm-executor/runtime-benchmarks", + "cumulus-pallet-parachain-system/runtime-benchmarks", + "cumulus-primitives-core/runtime-benchmarks" ] try-runtime = [ "frame-support/try-runtime", @@ -124,5 +130,6 @@ try-runtime = [ "polimec-common-test-utils?/try-runtime", "polimec-common/try-runtime", "sp-runtime/try-runtime", + "cumulus-pallet-parachain-system/try-runtime" ] on-chain-release-build = [] diff --git a/pallets/funding/src/benchmarking.rs b/pallets/funding/src/benchmarking.rs index 16b774552..b67fcc3c4 100644 --- a/pallets/funding/src/benchmarking.rs +++ b/pallets/funding/src/benchmarking.rs @@ -97,7 +97,7 @@ pub fn string_account( #[benchmarks( where - T: Config + frame_system::Config::RuntimeEvent> + pallet_balances::Config + core::fmt::Debug, + T: Config + frame_system::Config::RuntimeEvent> + pallet_balances::Config + cumulus_pallet_parachain_system::Config + sp_std::fmt::Debug, ::RuntimeEvent: TryInto> + Parameter + Member, ::Price: From, T::Hash: From, diff --git a/pallets/funding/src/functions/2_evaluation.rs b/pallets/funding/src/functions/2_evaluation.rs index 386b5177f..e2d17fc5d 100644 --- a/pallets/funding/src/functions/2_evaluation.rs +++ b/pallets/funding/src/functions/2_evaluation.rs @@ -84,7 +84,7 @@ impl Pallet { // * Get variables * let project_metadata = ProjectsMetadata::::get(project_id).ok_or(Error::::ProjectMetadataNotFound)?; let mut project_details = ProjectsDetails::::get(project_id).ok_or(Error::::ProjectDetailsNotFound)?; - let now = >::block_number(); + let now = ::BlockNumberProvider::current_block_number(); let evaluation_id = NextEvaluationId::::get(); let plmc_usd_price = >::get_decimals_aware_price(Location::here(), USD_DECIMALS, PLMC_DECIMALS) diff --git a/pallets/funding/src/functions/3_auction.rs b/pallets/funding/src/functions/3_auction.rs index e4799165b..2c6770536 100644 --- a/pallets/funding/src/functions/3_auction.rs +++ b/pallets/funding/src/functions/3_auction.rs @@ -22,7 +22,7 @@ impl Pallet { // Fetch current bucket details and other required info let mut current_bucket = Buckets::::get(project_id).ok_or(Error::::BucketNotFound)?; - let now = >::block_number(); + let now = ::BlockNumberProvider::current_block_number(); let mut amount_to_bid = ct_amount; let project_policy = project_metadata.policy_ipfs_cid.ok_or(Error::::ImpossibleState)?; diff --git a/pallets/funding/src/functions/4_funding_end.rs b/pallets/funding/src/functions/4_funding_end.rs index 29fad9e70..21327ebfe 100644 --- a/pallets/funding/src/functions/4_funding_end.rs +++ b/pallets/funding/src/functions/4_funding_end.rs @@ -9,7 +9,7 @@ impl Pallet { let project_metadata = ProjectsMetadata::::get(project_id).ok_or(Error::::ProjectMetadataNotFound)?; let mut project_details = ProjectsDetails::::get(project_id).ok_or(Error::::ProjectDetailsNotFound)?; let bucket = Buckets::::get(project_id).ok_or(Error::::BucketNotFound)?; - let now = >::block_number(); + let now = ::BlockNumberProvider::current_block_number(); let issuer_did = project_details.issuer_did.clone(); let ct_amount_oversubscribed = CTAmountOversubscribed::::get(project_id); diff --git a/pallets/funding/src/functions/5_settlement.rs b/pallets/funding/src/functions/5_settlement.rs index 20f8d149c..428c931f1 100644 --- a/pallets/funding/src/functions/5_settlement.rs +++ b/pallets/funding/src/functions/5_settlement.rs @@ -28,7 +28,7 @@ impl Pallet { let mut project_details = ProjectsDetails::::get(project_id).ok_or(Error::::ProjectDetailsNotFound)?; let token_information = ProjectsMetadata::::get(project_id).ok_or(Error::::ProjectMetadataNotFound)?.token_information; - let now = >::block_number(); + let now = ::BlockNumberProvider::current_block_number(); project_details.funding_end_block = Some(now); @@ -38,7 +38,7 @@ impl Pallet { let multiplier: MultiplierOf = ParticipationMode::OTM.multiplier().try_into().map_err(|_| Error::::ImpossibleState)?; let duration = multiplier.calculate_vesting_duration::(); - let now = >::block_number(); + let now = ::BlockNumberProvider::current_block_number(); ReleaseType::Locked(duration.saturating_add(now)) }; >::set_release_type( diff --git a/pallets/funding/src/functions/misc.rs b/pallets/funding/src/functions/misc.rs index cb6742091..26ea5e68f 100644 --- a/pallets/funding/src/functions/misc.rs +++ b/pallets/funding/src/functions/misc.rs @@ -263,7 +263,7 @@ impl Pallet { skip_end_check: bool, ) -> DispatchResult { /* Verify */ - let now = >::block_number(); + let now = ::BlockNumberProvider::current_block_number(); ensure!(project_details.status == current_round, Error::::IncorrectRound); ensure!(project_details.round_duration.ended(now) || skip_end_check, Error::::TooEarlyForRound); diff --git a/pallets/funding/src/functions/mod.rs b/pallets/funding/src/functions/mod.rs index 4c51df02e..2d9f9b31c 100644 --- a/pallets/funding/src/functions/mod.rs +++ b/pallets/funding/src/functions/mod.rs @@ -17,7 +17,6 @@ use frame_support::{ }, transactional, }; -use frame_system::pallet_prelude::BlockNumberFor; use polimec_common::{ credentials::{Did, InvestorType}, USD_DECIMALS, diff --git a/pallets/funding/src/functions/runtime_api.rs b/pallets/funding/src/functions/runtime_api.rs index e40067794..2396297d3 100644 --- a/pallets/funding/src/functions/runtime_api.rs +++ b/pallets/funding/src/functions/runtime_api.rs @@ -237,7 +237,7 @@ impl Pallet { .enumerate() // Filter out schedules with future starting blocks before collecting them into a vector. .filter_map(|(i, schedule)| { - if schedule.starting_block > >::block_number() { + if schedule.starting_block > ::BlockNumberProvider::current_block_number() { None } else { Some((i, schedule.ending_block_as_balance::>())) diff --git a/pallets/funding/src/instantiator/calculations.rs b/pallets/funding/src/instantiator/calculations.rs index a28dffd29..3f49505cd 100644 --- a/pallets/funding/src/instantiator/calculations.rs +++ b/pallets/funding/src/instantiator/calculations.rs @@ -13,7 +13,7 @@ use sp_runtime::traits::TrailingZeroInput; use InvestorType::{self, *}; impl< - T: Config, + T: Config + cumulus_pallet_parachain_system::Config, AllPalletsWithoutSystem: OnFinalize> + OnIdle> + OnInitialize>, RuntimeEvent: From> + TryInto> + Parameter + Member + IsType<::RuntimeEvent>, > Instantiator diff --git a/pallets/funding/src/instantiator/chain_interactions.rs b/pallets/funding/src/instantiator/chain_interactions.rs index 5f6b81fbe..af562e83e 100644 --- a/pallets/funding/src/instantiator/chain_interactions.rs +++ b/pallets/funding/src/instantiator/chain_interactions.rs @@ -7,7 +7,7 @@ use polimec_common::assets::AcceptedFundingAsset; // general chain interactions impl< - T: Config + pallet_balances::Config, + T: Config + pallet_balances::Config + cumulus_pallet_parachain_system::Config, AllPalletsWithoutSystem: OnFinalize> + OnIdle> + OnInitialize>, RuntimeEvent: From> + TryInto> + Parameter + Member + IsType<::RuntimeEvent>, > Instantiator @@ -145,13 +145,13 @@ impl< } pub fn current_block(&mut self) -> BlockNumberFor { - self.execute(|| frame_system::Pallet::::block_number()) + self.execute(|| ::BlockNumberProvider::current_block_number()) } pub fn advance_time(&mut self, amount: BlockNumberFor) { self.execute(|| { for _block in 0u32..amount.saturated_into() { - let mut current_block = frame_system::Pallet::::block_number(); + let mut current_block = ::BlockNumberProvider::current_block_number(); >>::on_finalize(current_block); as OnFinalize>>::on_finalize(current_block); @@ -165,13 +165,21 @@ impl< as OnInitialize>>::on_initialize(current_block); >>::on_initialize(current_block); } - }) + }); + + let current_block = self.current_block(); + // in case we are relying on parachain system + self.set_relay_chain_block_number(current_block + amount); } pub fn jump_to_block(&mut self, block: BlockNumberFor) { let current_block = self.current_block(); if block > current_block { - self.execute(|| frame_system::Pallet::::set_block_number(block - One::one())); + self.execute(|| { + frame_system::Pallet::::set_block_number(block - One::one()); + }); + self.set_relay_chain_block_number(block - One::one()); + self.advance_time(One::one()); } else { // panic!("Cannot jump to a block in the present or past") @@ -217,11 +225,35 @@ impl< }); } } + + /// NOTE: this is a workaround function to advance relaychain's block number, since + /// `::BlockNumberProvider::set_block_number` is not working in tests + /// + /// It is cloned version of the above trait function implementation in [`cumulus_pallet_parachain_system::RelaychainDataProvider`] + /// + /// TODO: remove this function once the issue is fixed + pub fn set_relay_chain_block_number(&mut self, to: BlockNumberFor) { + use cumulus_pallet_parachain_system::ValidationData; + use cumulus_primitives_core::PersistedValidationData; + + self.execute(|| { + let mut validation_data = ValidationData::::get().unwrap_or_else(|| + // PersistedValidationData does not impl default in non-std + PersistedValidationData { + parent_head: vec![].into(), + relay_parent_number: Default::default(), + max_pov_size: Default::default(), + relay_parent_storage_root: Default::default(), + }); + validation_data.relay_parent_number = to.saturated_into(); + ValidationData::::put(validation_data) + }); + } } // assertions impl< - T: Config + pallet_balances::Config, + T: Config + pallet_balances::Config + cumulus_pallet_parachain_system::Config, AllPalletsWithoutSystem: OnFinalize> + OnIdle> + OnInitialize>, RuntimeEvent: From> + TryInto> + Parameter + Member + IsType<::RuntimeEvent>, > Instantiator @@ -328,7 +360,7 @@ impl< // project chain interactions impl< - T: Config + pallet_balances::Config, + T: Config + pallet_balances::Config + cumulus_pallet_parachain_system::Config, AllPalletsWithoutSystem: OnFinalize> + OnIdle> + OnInitialize>, RuntimeEvent: From> + TryInto> + Parameter + Member + IsType<::RuntimeEvent>, > Instantiator diff --git a/pallets/funding/src/instantiator/mod.rs b/pallets/funding/src/instantiator/mod.rs index 19d02ae0c..c985cb411 100644 --- a/pallets/funding/src/instantiator/mod.rs +++ b/pallets/funding/src/instantiator/mod.rs @@ -32,7 +32,6 @@ use frame_support::{ weights::Weight, Parameter, }; -use frame_system::pallet_prelude::BlockNumberFor; use itertools::Itertools; use parity_scale_codec::Decode; use polimec_common::{credentials::InvestorType, migration_types::MigrationOrigin}; diff --git a/pallets/funding/src/instantiator/types.rs b/pallets/funding/src/instantiator/types.rs index b3a4e3c8c..3040ca126 100644 --- a/pallets/funding/src/instantiator/types.rs +++ b/pallets/funding/src/instantiator/types.rs @@ -20,7 +20,7 @@ pub type OptionalExternalities = Option>; pub type OptionalExternalities = Option<()>; pub struct Instantiator< - T: Config + pallet_balances::Config, + T: Config + pallet_balances::Config + cumulus_pallet_parachain_system::Config, AllPalletsWithoutSystem: OnFinalize> + OnIdle> + OnInitialize>, RuntimeEvent: From> + TryInto> + Parameter + Member + IsType<::RuntimeEvent>, > { diff --git a/pallets/funding/src/lib.rs b/pallets/funding/src/lib.rs index 261c3ccf3..50e87ca26 100644 --- a/pallets/funding/src/lib.rs +++ b/pallets/funding/src/lib.rs @@ -79,7 +79,6 @@ use frame_support::{ }, BoundedVec, PalletId, WeakBoundedVec, }; -use frame_system::pallet_prelude::BlockNumberFor; pub use pallet::*; use polimec_common::{ credentials::{Cid, Did, EnsureOriginWithCredentials, InvestorType, UntrustedToken}, @@ -88,7 +87,10 @@ use polimec_common::{ }; use polkadot_parachain_primitives::primitives::Id as ParaId; use sp_arithmetic::traits::{One, Saturating}; -use sp_runtime::{traits::AccountIdConversion, FixedPointNumber, FixedU128}; +use sp_runtime::{ + traits::{AccountIdConversion, BlockNumberProvider}, + FixedPointNumber, FixedU128, +}; pub use types::*; use xcm::v4::prelude::*; @@ -134,9 +136,11 @@ pub type VestingOf = pallet_linear_release::Pallet; pub type BlockNumberToBalanceOf = ::BlockNumberToBalance; pub type RuntimeHoldReasonOf = ::RuntimeHoldReason; pub type PriceProviderOf = ::PriceProvider; +pub type BlockNumberFor = <::BlockNumberProvider as BlockNumberProvider>::BlockNumber; #[frame_support::pallet] pub mod pallet { + use super::BlockNumberFor; #[allow(clippy::wildcard_imports)] use super::*; use crate::traits::{BondingRequirementCalculation, VestingDurationCalculation}; @@ -316,6 +320,9 @@ pub mod pallet { /// Callbacks for dealing with an evaluator slash on other pallets type OnSlash: OnSlash, Balance>; + + /// Provider for block number + type BlockNumberProvider: BlockNumberProvider>; } #[pallet::storage] diff --git a/pallets/funding/src/mock.rs b/pallets/funding/src/mock.rs index c4c887b2e..dea167a74 100644 --- a/pallets/funding/src/mock.rs +++ b/pallets/funding/src/mock.rs @@ -26,7 +26,7 @@ use frame_support::{ construct_runtime, derive_impl, pallet_prelude::Weight, parameter_types, - traits::{AsEnsureOriginWithArg, ConstU16, ConstU32, ConstU64, OriginTrait, WithdrawReasons}, + traits::{AsEnsureOriginWithArg, ConstU16, ConstU32, ConstU64, EnqueueWithOrigin, OriginTrait, WithdrawReasons}, PalletId, }; use frame_system as system; @@ -227,10 +227,28 @@ impl system::Config for TestRuntime { type Hashing = BlakeTwo256; type Lookup = IdentityLookup; type MaxConsumers = frame_support::traits::ConstU32<16>; + type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode; type PalletInfo = PalletInfo; type SS58Prefix = ConstU16<41>; } +// NOTE: this is not used in the mock runtime at all, but it is required to satisfy type bound of [`crate::instantiator::Instantiator`] +// TODO: should be removed and `::BlockNumberProvider::set_block_number` should be used instead +impl cumulus_pallet_parachain_system::Config for TestRuntime { + type CheckAssociatedRelayNumber = cumulus_pallet_parachain_system::AnyRelayNumber; + type ConsensusHook = cumulus_pallet_parachain_system::ExpectParentIncluded; + type DmpQueue = EnqueueWithOrigin<(), sp_core::ConstU8<0>>; + type OnSystemEvent = (); + type OutboundXcmpMessageSource = (); + type ReservedDmpWeight = (); + type ReservedXcmpWeight = (); + type RuntimeEvent = RuntimeEvent; + type SelectCore = cumulus_pallet_parachain_system::DefaultCoreSelector; + type SelfParaId = (); + type WeightInfo = (); + type XcmpMessageHandler = (); +} + parameter_types! { pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT; } @@ -295,6 +313,7 @@ impl pallet_linear_release::Config for TestRuntime { type Balance = Balance; #[cfg(feature = "runtime-benchmarks")] type BenchmarkReason = BenchmarkReason; + type BlockNumberProvider = System; type BlockNumberToBalance = ConvertInto; type Currency = Balances; type MinVestedTransfer = MinVestedTransfer; @@ -372,6 +391,7 @@ impl Config for TestRuntime { type AllPalletsWithoutSystem = (Balances, ContributionTokens, ForeignAssets, PolimecFunding, LinearRelease); type AuctionRoundDuration = AuctionRoundDuration; type BlockNumber = BlockNumber; + type BlockNumberProvider = System; type BlockchainOperationTreasury = BlockchainOperationTreasuryAccount; type ContributionTokenCurrency = ContributionTokens; type ContributionTreasury = ContributionTreasury; @@ -436,6 +456,9 @@ construct_runtime!( ForeignAssets: pallet_assets::::{Pallet, Call, Storage, Event, Config}, PolimecFunding: pallet_funding::{Pallet, Call, Storage, Event, HoldReason} = 52, ProxyBonding: pallet_proxy_bonding, + + // NOTE: this pallet is only necessary to satisfy type bound of [`crate::instantiator::Instantiator`] + ParachainSystem: cumulus_pallet_parachain_system, } ); diff --git a/pallets/funding/src/tests/mod.rs b/pallets/funding/src/tests/mod.rs index 42fc21e2a..ad0a4ce43 100644 --- a/pallets/funding/src/tests/mod.rs +++ b/pallets/funding/src/tests/mod.rs @@ -13,6 +13,7 @@ use defaults::*; use frame_support::{ assert_err, assert_noop, assert_ok, dispatch::DispatchResult, + pallet_prelude::DispatchResultWithPostInfo, traits::{ fungible::{InspectFreeze, MutateFreeze, MutateHold}, fungibles::{metadata::Inspect as MetadataInspect, Inspect, Mutate}, diff --git a/pallets/funding/src/traits.rs b/pallets/funding/src/traits.rs index 9ecc77e60..9e585a087 100644 --- a/pallets/funding/src/traits.rs +++ b/pallets/funding/src/traits.rs @@ -14,9 +14,8 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use crate::{Balance, Config, ProjectId}; +use crate::{Balance, BlockNumberFor, Config, ProjectId}; use frame_support::weights::Weight; -use frame_system::pallet_prelude::BlockNumberFor; use sp_runtime::DispatchError; pub trait BondingRequirementCalculation { diff --git a/pallets/funding/src/types.rs b/pallets/funding/src/types.rs index f0b1a8760..f61d65100 100644 --- a/pallets/funding/src/types.rs +++ b/pallets/funding/src/types.rs @@ -23,7 +23,6 @@ pub use config::*; use core::cmp::Eq; pub use extrinsic::*; use frame_support::pallet_prelude::*; -use frame_system::pallet_prelude::BlockNumberFor; pub use inner::*; use parachains_common::DAYS; use polimec_common::USD_DECIMALS; @@ -40,7 +39,7 @@ use sp_runtime::traits::Zero; pub mod config { #[allow(clippy::wildcard_imports)] use super::*; - use crate::Balance; + use crate::{Balance, BlockNumberFor}; use sp_core::parameter_types; use xcm::v4::Location; @@ -706,8 +705,7 @@ pub mod inner { pub mod extrinsic { use super::*; - use crate::{AccountIdOf, Balance, Config, ParticipationMode, PriceOf, ProjectId, TicketSize}; - use frame_system::pallet_prelude::BlockNumberFor; + use crate::{AccountIdOf, Balance, BlockNumberFor, Config, ParticipationMode, PriceOf, ProjectId, TicketSize}; use polimec_common::credentials::{Cid, Did, InvestorType}; use xcm::v4::Junction; diff --git a/pallets/linear-release/src/impls.rs b/pallets/linear-release/src/impls.rs index bb89b643a..8457a14b8 100644 --- a/pallets/linear-release/src/impls.rs +++ b/pallets/linear-release/src/impls.rs @@ -124,7 +124,7 @@ impl Pallet { schedules: Vec>, action: VestingAction, ) -> (Vec>, BalanceOf) { - let now = >::block_number(); + let now = T::BlockNumberProvider::current_block_number(); let mut total_releasable: BalanceOf = Zero::zero(); let filtered_schedules = action @@ -208,7 +208,7 @@ impl Pallet { // (assuming initial state was valid). let (mut schedules, mut locked_now) = Self::report_schedule_updates(schedules.to_vec(), action); - let now = >::block_number(); + let now = T::BlockNumberProvider::current_block_number(); if let Some(new_schedule) = Self::merge_vesting_info(now, schedule1, schedule2) { // Merging created a new schedule so we: // 1) need to add it to the accounts vesting schedule collection, @@ -239,7 +239,7 @@ impl ReleaseSchedule, ReasonOf> for Pallet { /// Get the amount that is possible to vest (i.e release) at this block. fn vesting_balance(who: &T::AccountId, reason: ReasonOf) -> Option> { Self::vesting(who, reason).map(|v| { - let now = >::block_number(); + let now = T::BlockNumberProvider::current_block_number(); let total_releasable = v.iter().fold(Zero::zero(), |total, schedule| { schedule.releaseble_at::(now).saturating_add(total) }); diff --git a/pallets/linear-release/src/lib.rs b/pallets/linear-release/src/lib.rs index de0c802a6..952fff80b 100644 --- a/pallets/linear-release/src/lib.rs +++ b/pallets/linear-release/src/lib.rs @@ -39,7 +39,7 @@ use frame_support::{ use frame_system::pallet_prelude::*; use parity_scale_codec::MaxEncodedLen; use polimec_common::ReleaseSchedule; -use sp_runtime::traits::{Convert, One, Saturating, Zero}; +use sp_runtime::traits::{BlockNumberProvider, Convert, One, Saturating, Zero}; // Re-export pallet items so that they can be accessed from the crate namespace. pub use pallet::*; @@ -62,6 +62,7 @@ pub type BalanceOf = ::Balance; pub type ReasonOf = ::RuntimeHoldReason; pub type AccountIdOf = ::AccountId; pub type VestingInfoOf = VestingInfo, BlockNumberFor>; +pub type BlockNumberFor = <::BlockNumberProvider as BlockNumberProvider>::BlockNumber; /// Actions to take against a user's `Vesting` storage entry. #[derive(Clone, Copy)] @@ -145,6 +146,9 @@ pub mod pallet { /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; + /// Block number provider for this pallet + type BlockNumberProvider: BlockNumberProvider>; + /// Reason used when running benchmarks #[cfg(feature = "runtime-benchmarks")] type BenchmarkReason: Get; diff --git a/pallets/linear-release/src/mock.rs b/pallets/linear-release/src/mock.rs index 2e17d4aca..1f5952478 100644 --- a/pallets/linear-release/src/mock.rs +++ b/pallets/linear-release/src/mock.rs @@ -67,6 +67,7 @@ impl Config for Test { type Balance = u64; #[cfg(feature = "runtime-benchmarks")] type BenchmarkReason = BenchmarkReason; + type BlockNumberProvider = System; type BlockNumberToBalance = Identity; type Currency = Balances; // TODO: Use the type from Balances. diff --git a/pallets/proxy-bonding/src/mock.rs b/pallets/proxy-bonding/src/mock.rs index ba95b1359..7d1043835 100644 --- a/pallets/proxy-bonding/src/mock.rs +++ b/pallets/proxy-bonding/src/mock.rs @@ -106,6 +106,7 @@ impl pallet_linear_release::Config for TestRuntime { type Balance = ::Balance; #[cfg(feature = "runtime-benchmarks")] type BenchmarkReason = BenchmarkReason; + type BlockNumberProvider = System; type BlockNumberToBalance = Identity; type Currency = Balances; type MinVestedTransfer = MinVestedTransfer; diff --git a/runtimes/polimec/Cargo.toml b/runtimes/polimec/Cargo.toml index 97f9c9560..ee690e472 100644 --- a/runtimes/polimec/Cargo.toml +++ b/runtimes/polimec/Cargo.toml @@ -175,7 +175,6 @@ std = [ "sp-block-builder/std", "sp-consensus-aura/std", "sp-core/std", - # "sp-debug-derive/std", "sp-genesis-builder/std", "sp-inherents/std", "sp-offchain/std", diff --git a/runtimes/polimec/src/lib.rs b/runtimes/polimec/src/lib.rs index 0f1b3623f..25c6cace0 100644 --- a/runtimes/polimec/src/lib.rs +++ b/runtimes/polimec/src/lib.rs @@ -23,7 +23,7 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); extern crate alloc; use assets_common::fungible_conversion::{convert, convert_balance}; use core::cmp::Ordering; -use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases; +use cumulus_pallet_parachain_system::{RelayNumberMonotonicallyIncreases, RelaychainDataProvider}; use cumulus_primitives_core::{AggregateMessageOrigin, ParaId}; use frame_support::{ construct_runtime, @@ -366,7 +366,7 @@ impl frame_system::Config for Runtime { } impl pallet_timestamp::Config for Runtime { - type MinimumPeriod = MinimumPeriod; + type MinimumPeriod = ConstU64<0>; /// A timestamp: milliseconds since the unix epoch. type Moment = u64; type OnTimestampSet = Aura; @@ -559,11 +559,11 @@ impl pallet_session::Config for Runtime { } impl pallet_aura::Config for Runtime { - type AllowMultipleBlocksPerSlot = frame_support::traits::ConstBool; + type AllowMultipleBlocksPerSlot = frame_support::traits::ConstBool; type AuthorityId = AuraId; type DisabledValidators = (); type MaxAuthorities = MaxAuthorities; - type SlotDuration = ConstU64<12_000>; + type SlotDuration = ConstU64; } pub struct ToTreasury; @@ -690,6 +690,7 @@ impl GetElectorate for Electorate { impl pallet_democracy::Config for Runtime { type BlacklistOrigin = EnsureRoot; + type BlockNumberProvider = System; // To cancel a proposal before it has been passed, the technical committee must be unanimous or // Root must agree. type CancelProposalOrigin = EitherOfDiverse< @@ -1029,6 +1030,7 @@ impl pallet_funding::Config for Runtime { type AllPalletsWithoutSystem = (Balances, ContributionTokens, ForeignAssets, Oracle, Funding, LinearRelease); type AuctionRoundDuration = AuctionRoundDuration; type BlockNumber = BlockNumber; + type BlockNumberProvider = RelaychainDataProvider; type BlockchainOperationTreasury = BlockchainOperationTreasury; type ContributionTokenCurrency = ContributionTokens; type ContributionTreasury = ContributionTreasuryAccount; @@ -1093,6 +1095,7 @@ impl pallet_linear_release::Config for Runtime { type Balance = Balance; #[cfg(feature = "runtime-benchmarks")] type BenchmarkReason = BenchmarkReason; + type BlockNumberProvider = RelaychainDataProvider; type BlockNumberToBalance = ConvertInto; type Currency = Balances; type MinVestedTransfer = shared_configuration::vesting::MinVestedTransfer; @@ -1320,7 +1323,7 @@ impl_runtime_apis! { impl sp_consensus_aura::AuraApi for Runtime { fn slot_duration() -> sp_consensus_aura::SlotDuration { - sp_consensus_aura::SlotDuration::from_millis(parachains_common::SLOT_DURATION) + sp_consensus_aura::SlotDuration::from_millis(SLOT_DURATION) } fn authorities() -> Vec { diff --git a/runtimes/shared-configuration/Cargo.toml b/runtimes/shared-configuration/Cargo.toml index c88a434f1..13ef0618d 100644 --- a/runtimes/shared-configuration/Cargo.toml +++ b/runtimes/shared-configuration/Cargo.toml @@ -41,6 +41,8 @@ pallet-oracle-ocw.workspace = true pallet-treasury = {workspace = true, optional = true} pallet-asset-tx-payment.workspace = true xcm.workspace = true +cumulus-primitives-core.workspace = true + [features] default = [ "std" ] fast-mode = [] @@ -64,6 +66,7 @@ std = [ "sp-arithmetic/std", "sp-runtime/std", "xcm/std", + "cumulus-primitives-core/std", ] runtime-benchmarks = [ "frame-support/runtime-benchmarks", @@ -77,7 +80,8 @@ runtime-benchmarks = [ "parachains-common/runtime-benchmarks", "polimec-common/runtime-benchmarks", "sp-runtime/runtime-benchmarks", - "pallet-transaction-payment/runtime-benchmarks" + "pallet-transaction-payment/runtime-benchmarks", + "cumulus-primitives-core/runtime-benchmarks" ] try-runtime = [ "frame-support/try-runtime", diff --git a/runtimes/shared-configuration/src/fee.rs b/runtimes/shared-configuration/src/fee.rs index 175ae9337..01f8bb87e 100644 --- a/runtimes/shared-configuration/src/fee.rs +++ b/runtimes/shared-configuration/src/fee.rs @@ -37,7 +37,7 @@ use frame_support::{ }; use pallet_asset_tx_payment::{HandleCredit, OnChargeAssetTransaction}; use pallet_transaction_payment::OnChargeTransaction; -use parachains_common::{impls::AccountIdOf, AccountId, SLOT_DURATION}; +use parachains_common::{impls::AccountIdOf, AccountId}; use scale_info::prelude::vec; use smallvec::smallvec; use sp_arithmetic::Perbill; @@ -102,7 +102,6 @@ impl WeightToFeePolynomial for ProofSizeToFee { } parameter_types! { - pub const MinimumPeriod: u64 = SLOT_DURATION / 2; pub const MaxAuthorities: u32 = 75; } diff --git a/runtimes/shared-configuration/src/time.rs b/runtimes/shared-configuration/src/time.rs index a6fb15907..a2e43f8fe 100644 --- a/runtimes/shared-configuration/src/time.rs +++ b/runtimes/shared-configuration/src/time.rs @@ -16,9 +16,18 @@ /// Maximum number of blocks simultaneously accepted by the Runtime, not yet included /// into the relay chain. -pub const UNINCLUDED_SEGMENT_CAPACITY: u32 = 1; +pub const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3; /// How many parachain blocks are processed by the relay chain per parent. Limits the /// number of blocks authored per slot. pub const BLOCK_PROCESSING_VELOCITY: u32 = 1; /// Relay chain slot duration, in milliseconds. pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000; + +/// This determines the average expected block time that we are targeting. +/// Blocks will be produced at a minimum duration defined by `SLOT_DURATION`. +/// `SLOT_DURATION` is picked up by `pallet_timestamp` which is in turn picked +/// up by `pallet_aura` to implement `fn slot_duration()`. +/// +/// Change this to adjust the block time. +pub const MILLISECS_PER_BLOCK: u64 = 6000; +pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK; diff --git a/runtimes/shared-configuration/src/weights/mod.rs b/runtimes/shared-configuration/src/weights/mod.rs index 9070e6515..a0ee0e687 100644 --- a/runtimes/shared-configuration/src/weights/mod.rs +++ b/runtimes/shared-configuration/src/weights/mod.rs @@ -23,14 +23,24 @@ pub mod rocksdb_weights; pub use block_weights::constants::BlockExecutionWeight; pub use extrinsic_weights::constants::ExtrinsicBaseWeight; -use frame_support::{dispatch::DispatchClass, parameter_types, weights::Weight}; -use parachains_common::{AVERAGE_ON_INITIALIZE_RATIO, MAXIMUM_BLOCK_WEIGHT}; +use frame_support::{ + dispatch::DispatchClass, + parameter_types, + weights::{constants::WEIGHT_REF_TIME_PER_SECOND, Weight}, +}; +use parachains_common::AVERAGE_ON_INITIALIZE_RATIO; pub use paritydb_weights::constants::ParityDbWeight; pub use rocksdb_weights::constants::RocksDbWeight; use frame_system::limits::{BlockLength, BlockWeights}; use sp_arithmetic::Perbill; +/// We allow for 2 seconds of compute with a 6 second average block. +pub const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts( + WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2), + cumulus_primitives_core::relay_chain::MAX_POV_SIZE as u64, +); + /// We allow `Normal` extrinsics to fill up the block up to 85%, the rest can be used by operational extrinsics. pub const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(85);