From 2f643816d79a76155aec790a35b9b72a5d8bb726 Mon Sep 17 00:00:00 2001 From: Kian Paimani <5588131+kianenigma@users.noreply.github.com> Date: Mon, 17 Jun 2024 11:31:15 +0800 Subject: [PATCH 1/9] add ref doc for logging practices in FRAME (#4768) --- Cargo.lock | 3 + docs/sdk/Cargo.toml | 2 + docs/sdk/src/reference_docs/frame_logging.rs | 116 ++++++++++++++++++ docs/sdk/src/reference_docs/mod.rs | 3 + docs/sdk/src/reference_docs/umbrella_crate.rs | 5 +- substrate/primitives/api/Cargo.toml | 1 + substrate/primitives/api/src/lib.rs | 1 + 7 files changed, 129 insertions(+), 2 deletions(-) create mode 100644 docs/sdk/src/reference_docs/frame_logging.rs diff --git a/Cargo.lock b/Cargo.lock index 71b98d2cd5c4c..4f4e0a988cecb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -14381,6 +14381,8 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-runtime-interface 24.0.0", + "sp-std 14.0.0", + "sp-tracing 16.0.0", "sp-version", "staging-chain-spec-builder", "staging-node-cli", @@ -19530,6 +19532,7 @@ dependencies = [ name = "sp-api" version = "26.0.0" dependencies = [ + "docify", "hash-db", "log", "parity-scale-codec", diff --git a/docs/sdk/Cargo.toml b/docs/sdk/Cargo.toml index 10c0912116711..ee603f8c49465 100644 --- a/docs/sdk/Cargo.toml +++ b/docs/sdk/Cargo.toml @@ -89,6 +89,8 @@ pallet-babe = { path = "../../substrate/frame/babe" } # Primitives sp-io = { path = "../../substrate/primitives/io" } +sp-std = { path = "../../substrate/primitives/std" } +sp-tracing = { path = "../../substrate/primitives/tracing" } sp-runtime-interface = { path = "../../substrate/primitives/runtime-interface" } sp-api = { path = "../../substrate/primitives/api" } sp-core = { path = "../../substrate/primitives/core" } diff --git a/docs/sdk/src/reference_docs/frame_logging.rs b/docs/sdk/src/reference_docs/frame_logging.rs new file mode 100644 index 0000000000000..301fa7ef83f82 --- /dev/null +++ b/docs/sdk/src/reference_docs/frame_logging.rs @@ -0,0 +1,116 @@ +//! # FRAME Logging +//! +//! This reference docs briefly explores how to do logging and printing runtimes, mainly +//! FRAME-based. +//! +//! ## Using `println!` +//! +//! To recap, as with standard Rust, you can use `println!` _in your tests_, but it will only print +//! out if executed with `--nocapture`, or if the test panics. +//! +//! ``` +//! fn it_print() { +//! println!("Hello, world!"); +//! } +//! ``` +//! +//! within the pallet, if you want to use the standard `println!`, it needs to be wrapped in +//! [`sp_std::if_std`]. Of course, this means that this print code is only available to you in the +//! `std` compiler flag, and never present in a wasm build. +//! +//! ``` +//! // somewhere in your pallet. This is not a real pallet code. +//! mod pallet { +//! struct Pallet; +//! impl Pallet { +//! fn print() { +//! sp_std::if_std! { +//! println!("Hello, world!"); +//! } +//! } +//! } +//! } +//! ``` +//! +//! ## Using `log` +//! +//! First, ensure you are familiar with the `log` crate. In short, each log statement has: +//! +//! 1. `log-level`, signifying how important it is +//! 2. `log-target`, signifying to which component it belongs. +//! +//! Add log statements to your pallet as such: +//! +//! You can add the log crate to the `Cargo.toml` of the pallet. +//! +//! ```text +//! #[dependencies] +//! log = { version = "x.y.z", default-features = false } +//! +//! #[features] +//! std = [ +//! // snip -- other pallets +//! "log/std" +//! ] +//! ``` +//! +//! More conveniently, the `frame` umbrella crate re-exports the log crate as [`frame::log`]. +//! +//! Then, the pallet can use this crate to emit log statements. In this statement, we use the info +//! level, and the target is `pallet-example`. +//! +//! ``` +//! mod pallet { +//! struct Pallet; +//! +//! impl Pallet { +//! fn logs() { +//! frame::log::info!(target: "pallet-example", "Hello, world!"); +//! } +//! } +//! } +//! ``` +//! +//! This will in itself just emit the log messages, **but unless if captured by a logger, they will +//! not go anywhere**. [`sp_api`] provides a handy function to enable the runtime logging: +//! +//! ``` +//! // in your test +//! fn it_also_prints() { +//! sp_api::init_runtime_logger(); +//! // call into your pallet, and now it will print `log` statements. +//! } +//! ``` +//! +//! Alternatively, you can use [`sp_tracing::try_init_simple`]. +//! +//! `info`, `error` and `warn` logs are printed by default, but if you want lower level logs to also +//! be printed, you must to add the following compiler flag: +//! +//! ```text +//! RUST_LOG=pallet-example=trace cargo test +//! ``` +//! +//! ## Enabling Logs in Production +//! +//! All logs from the runtime are emitted by default, but there is a feature flag in [`sp_api`], +//! called `disable-logging`, that can be used to disable all logs in the runtime. This is useful +//! for production chains to reduce the size and overhead of the wasm runtime. +#![doc = docify::embed!("../../substrate/primitives/api/src/lib.rs", init_runtime_logger)] +//! +//! Similar to the above, the proper `RUST_LOG` must also be passed to your compiler flag when +//! compiling the runtime. +//! +//! ## Log Target Prefixing +//! +//! Many [`crate::polkadot_sdk::frame_runtime`] pallets emit logs with log target `runtime::`, for example `runtime::system`. This then allows one to run a node with a wasm blob +//! compiled with `LOG_TARGET=runtime=debug`, which enables the log target of all pallets who's log +//! target starts with `runtime`. +//! +//! ## Low Level Primitives +//! +//! Under the hood, logging is another instance of host functions under the hood (as defined in +//! [`crate::reference_docs::wasm_meta_protocol`]). The runtime uses a set of host functions under +//! [`sp_io::logging`] and [`sp_io::misc`] to emit all logs and prints. You typically do not need to +//! use these APIs directly. diff --git a/docs/sdk/src/reference_docs/mod.rs b/docs/sdk/src/reference_docs/mod.rs index 51150a5583758..688339b7e3806 100644 --- a/docs/sdk/src/reference_docs/mod.rs +++ b/docs/sdk/src/reference_docs/mod.rs @@ -93,6 +93,9 @@ pub mod frame_offchain_workers; /// together. pub mod frame_pallet_coupling; +/// Learn about how to do logging in FRAME-based runtimes. +pub mod frame_logging; + /// Learn about the Polkadot Umbrella crate that re-exports all other crates. pub mod umbrella_crate; diff --git a/docs/sdk/src/reference_docs/umbrella_crate.rs b/docs/sdk/src/reference_docs/umbrella_crate.rs index 9751b0ad5ad6d..0b3445cfc4bc0 100644 --- a/docs/sdk/src/reference_docs/umbrella_crate.rs +++ b/docs/sdk/src/reference_docs/umbrella_crate.rs @@ -28,8 +28,9 @@ //! `node` feature. For docs.rs the manifest contains specific configuration to make it show up //! all re-exports. //! -//! There is a specific `zepter` check in place to ensure that the features of the umbrella are -//! correctly configured. This check is run in CI and locally when running `zepter`. +//! There is a specific [`zepter`](https://github.com/ggwpez/zepter) check in place to ensure that +//! the features of the umbrella are correctly configured. This check is run in CI and locally when +//! running `zepter`. //! //! ## Generation //! diff --git a/substrate/primitives/api/Cargo.toml b/substrate/primitives/api/Cargo.toml index f48480f398d00..b334880785f2f 100644 --- a/substrate/primitives/api/Cargo.toml +++ b/substrate/primitives/api/Cargo.toml @@ -33,6 +33,7 @@ scale-info = { version = "2.11.1", default-features = false, features = [ ] } sp-metadata-ir = { path = "../metadata-ir", default-features = false, optional = true } log = { workspace = true } +docify = { version = "0.2.1" } [dev-dependencies] sp-test-primitives = { path = "../test-primitives" } diff --git a/substrate/primitives/api/src/lib.rs b/substrate/primitives/api/src/lib.rs index 20f989c4882e3..cd8da8ba2374e 100644 --- a/substrate/primitives/api/src/lib.rs +++ b/substrate/primitives/api/src/lib.rs @@ -532,6 +532,7 @@ pub trait ConstructRuntimeApi> { fn construct_runtime_api(call: &C) -> ApiRef; } +#[docify::export] /// Init the [`RuntimeLogger`](sp_runtime::runtime_logger::RuntimeLogger). pub fn init_runtime_logger() { #[cfg(not(feature = "disable-logging"))] From 796890979e5d7d16a522c304376d78eec120f3cb Mon Sep 17 00:00:00 2001 From: Oliver Tale-Yazdi Date: Mon, 17 Jun 2024 13:46:04 +0200 Subject: [PATCH 2/9] CI: Add stable clobber (#4780) Clobbers the `stable` branch with the `audited` tag as described in the [RELEASE.md](https://github.com/paritytech/polkadot-sdk/blob/master/docs/RELEASE.md#clobbering). Example of the `staging_stable` branch now after force-pushing the `staging_audited` tag for a few times. The `staging_` prefix has now been removed and should be ready for normal use. The only trigger is currently manual, but can easily be set to three months. ![Screenshot 2024-06-13 at 00 47 43](https://github.com/paritytech/polkadot-sdk/assets/10380170/97e070ad-ce2d-4504-83a0-ad6717b6e73e) --------- Signed-off-by: Oliver Tale-Yazdi --- .github/workflows/release-clobber-stable.yml | 70 ++++++++++++++++++++ .github/workflows/release-srtool.yml | 2 - 2 files changed, 70 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/release-clobber-stable.yml diff --git a/.github/workflows/release-clobber-stable.yml b/.github/workflows/release-clobber-stable.yml new file mode 100644 index 0000000000000..643c14daa15b1 --- /dev/null +++ b/.github/workflows/release-clobber-stable.yml @@ -0,0 +1,70 @@ +name: Clobber Stable + +# This action implements the +# [Clobbering](https://github.com/paritytech/polkadot-sdk/blob/master/docs/RELEASE.md#clobbering) +# process from the release process. It pushes a new commit to the `stable` branch with all the +# current content of the `audited` tag. It does not use a merge commit, but rather 'clobbers' the +# branch with a single commit that contains all the changes. It has a naming scheme of `Clobber with +# audited ($COMMIT)`. +# Currently, the script is only triggered manually, but can be easily changed to a schedule. + +on: + workflow_dispatch: + +permissions: + contents: write + +jobs: + clobber-stable: + runs-on: ubuntu-latest + timeout-minutes: 5 + env: + STABLE: stable + UNSTABLE: master + AUDITED: audited + steps: + - name: Checkout + uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + + - name: Prechecks + run: | + # Properly fetch + git fetch --prune --unshallow origin tag $AUDITED + git fetch origin $STABLE + + # Sanity checks + git checkout -q tags/$AUDITED || (echo "Could not find the '$AUDITED' tag." && exit 1) + COMMIT=$(git rev-parse tags/$AUDITED) + #$(git branch --contains $COMMIT | grep -q $UNSTABLE) || (echo "The '$AUDITED' tag is not on the '$UNSTABLE' branch." && exit 1) + + git config --global user.email "admin@parity.io" + git config --global user.name "Parity Release Team" + + - name: Prepare commit + run: | + git checkout --quiet origin/$STABLE + + # Delete all tracked files in the working directory + git ls-files -z | xargs -0 rm -f + + # Find and delete any empty directories + find . -type d -empty -delete + + git add . 1>/dev/null 2>/dev/null + git commit -qm "Delete all files" + + # Grab the files from the commit + git checkout --quiet tags/$AUDITED -- . + + # Stage, commit, and push the working directory which now matches 'audited' 1:1 + git status + COMMIT=$(git rev-parse --short=10 tags/$AUDITED) + git add . 1>/dev/null 2>/dev/null + git commit --allow-empty --amend -qm "Clobber with $AUDITED ($COMMIT)" + + - name: Push stable branch + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + git log -3 + git push --verbose origin HEAD:$STABLE diff --git a/.github/workflows/release-srtool.yml b/.github/workflows/release-srtool.yml index 95b1846b98e0c..69a4bdbdda9ae 100644 --- a/.github/workflows/release-srtool.yml +++ b/.github/workflows/release-srtool.yml @@ -6,8 +6,6 @@ env: on: push: - tags: - - "*" branches: - release-v[0-9]+.[0-9]+.[0-9]+* - release-cumulus-v[0-9]+* From d91cbbd453c1d4553d7e3dc8753a2007fc4c5a67 Mon Sep 17 00:00:00 2001 From: Ankan <10196091+Ank4n@users.noreply.github.com> Date: Mon, 17 Jun 2024 14:35:15 +0200 Subject: [PATCH 3/9] Impl and use default config for pallet-staking in tests (#4797) --- substrate/frame/babe/src/mock.rs | 19 +----- substrate/frame/beefy/src/mock.rs | 18 +---- substrate/frame/delegated-staking/src/mock.rs | 21 +----- .../frame/delegated-staking/src/tests.rs | 26 +++---- .../test-staking-e2e/src/mock.rs | 11 +-- substrate/frame/fast-unstake/src/mock.rs | 20 +----- substrate/frame/grandpa/src/mock.rs | 15 +---- .../nomination-pools/benchmarking/src/mock.rs | 19 +----- .../test-delegate-stake/src/mock.rs | 18 +---- .../test-transfer-stake/src/mock.rs | 18 +---- .../frame/offences/benchmarking/src/mock.rs | 18 +---- substrate/frame/root-offences/src/mock.rs | 15 +---- .../frame/session/benchmarking/src/mock.rs | 18 +---- substrate/frame/staking/src/mock.rs | 8 +-- substrate/frame/staking/src/pallet/mod.rs | 67 ++++++++++++++++++- 15 files changed, 92 insertions(+), 219 deletions(-) diff --git a/substrate/frame/babe/src/mock.rs b/substrate/frame/babe/src/mock.rs index 16db40e3cb35c..be38e3e7e5db5 100644 --- a/substrate/frame/babe/src/mock.rs +++ b/substrate/frame/babe/src/mock.rs @@ -28,7 +28,6 @@ use frame_support::{ traits::{ConstU128, ConstU32, ConstU64, KeyOwnerProofSystem, OnInitialize}, }; use pallet_session::historical as pallet_session_historical; -use pallet_staking::FixedNominationsQuota; use sp_consensus_babe::{AuthorityId, AuthorityPair, Randomness, Slot, VrfSignature}; use sp_core::{ crypto::{KeyTypeId, Pair, VrfSecret}, @@ -133,7 +132,6 @@ pallet_staking_reward_curve::build! { parameter_types! { pub const SessionsPerEra: SessionIndex = 3; pub const BondingDuration: EraIndex = 3; - pub const SlashDeferDuration: EraIndex = 0; pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE; pub static ElectionsBounds: ElectionBounds = ElectionBoundsBuilder::default().build(); } @@ -148,35 +146,20 @@ impl onchain::Config for OnChainSeqPhragmen { type Bounds = ElectionsBounds; } +#[derive_impl(pallet_staking::config_preludes::TestDefaultConfig)] impl pallet_staking::Config for Test { - type RewardRemainder = (); - type CurrencyToVote = (); - type RuntimeEvent = RuntimeEvent; type Currency = Balances; - type CurrencyBalance = ::Balance; - type Slash = (); - type Reward = (); type SessionsPerEra = SessionsPerEra; type BondingDuration = BondingDuration; - type SlashDeferDuration = SlashDeferDuration; type AdminOrigin = frame_system::EnsureRoot; type SessionInterface = Self; type UnixTime = pallet_timestamp::Pallet; type EraPayout = pallet_staking::ConvertCurve; - type MaxExposurePageSize = ConstU32<64>; type NextNewSession = Session; type ElectionProvider = onchain::OnChainExecution; type GenesisElectionProvider = Self::ElectionProvider; type VoterList = pallet_staking::UseNominatorsAndValidatorsMap; type TargetList = pallet_staking::UseValidatorsMap; - type NominationsQuota = FixedNominationsQuota<16>; - type MaxUnlockingChunks = ConstU32<32>; - type MaxControllersInDeprecationBatch = ConstU32<100>; - type HistoryDepth = ConstU32<84>; - type EventListeners = (); - type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; - type WeightInfo = (); - type DisablingStrategy = pallet_staking::UpToLimitDisablingStrategy; } impl pallet_offences::Config for Test { diff --git a/substrate/frame/beefy/src/mock.rs b/substrate/frame/beefy/src/mock.rs index ceca0fd07b730..35bf172d60632 100644 --- a/substrate/frame/beefy/src/mock.rs +++ b/substrate/frame/beefy/src/mock.rs @@ -162,35 +162,19 @@ impl onchain::Config for OnChainSeqPhragmen { type Bounds = ElectionsBoundsOnChain; } +#[derive_impl(pallet_staking::config_preludes::TestDefaultConfig)] impl pallet_staking::Config for Test { - type RewardRemainder = (); - type CurrencyToVote = (); type RuntimeEvent = RuntimeEvent; type Currency = Balances; - type CurrencyBalance = ::Balance; - type Slash = (); - type Reward = (); - type SessionsPerEra = SessionsPerEra; - type BondingDuration = BondingDuration; - type SlashDeferDuration = (); type AdminOrigin = frame_system::EnsureRoot; type SessionInterface = Self; type UnixTime = pallet_timestamp::Pallet; type EraPayout = pallet_staking::ConvertCurve; - type MaxExposurePageSize = ConstU32<64>; type NextNewSession = Session; type ElectionProvider = onchain::OnChainExecution; type GenesisElectionProvider = Self::ElectionProvider; type VoterList = pallet_staking::UseNominatorsAndValidatorsMap; type TargetList = pallet_staking::UseValidatorsMap; - type NominationsQuota = pallet_staking::FixedNominationsQuota<16>; - type MaxUnlockingChunks = ConstU32<32>; - type MaxControllersInDeprecationBatch = ConstU32<100>; - type HistoryDepth = ConstU32<84>; - type EventListeners = (); - type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; - type WeightInfo = (); - type DisablingStrategy = pallet_staking::UpToLimitDisablingStrategy; } impl pallet_offences::Config for Test { diff --git a/substrate/frame/delegated-staking/src/mock.rs b/substrate/frame/delegated-staking/src/mock.rs index 0991833f86500..811d5739f4e98 100644 --- a/substrate/frame/delegated-staking/src/mock.rs +++ b/substrate/frame/delegated-staking/src/mock.rs @@ -88,7 +88,6 @@ pallet_staking_reward_curve::build! { parameter_types! { pub const RewardCurve: &'static sp_runtime::curve::PiecewiseLinear<'static> = &I_NPOS; - pub static BondingDuration: u32 = 3; pub static ElectionsBoundsOnChain: ElectionBounds = ElectionBoundsBuilder::default().build(); } pub struct OnChainSeqPhragmen; @@ -101,35 +100,17 @@ impl onchain::Config for OnChainSeqPhragmen { type Bounds = ElectionsBoundsOnChain; } +#[derive_impl(pallet_staking::config_preludes::TestDefaultConfig)] impl pallet_staking::Config for Runtime { type Currency = Balances; - type CurrencyBalance = Balance; type UnixTime = pallet_timestamp::Pallet; - type CurrencyToVote = (); - type RewardRemainder = (); - type RuntimeEvent = RuntimeEvent; - type Slash = (); - type Reward = (); - type SessionsPerEra = ConstU32<1>; - type SlashDeferDuration = (); type AdminOrigin = frame_system::EnsureRoot; - type BondingDuration = BondingDuration; - type SessionInterface = (); type EraPayout = pallet_staking::ConvertCurve; - type NextNewSession = (); - type HistoryDepth = ConstU32<84>; - type MaxExposurePageSize = ConstU32<64>; type ElectionProvider = onchain::OnChainExecution; type GenesisElectionProvider = Self::ElectionProvider; type VoterList = pallet_staking::UseNominatorsAndValidatorsMap; type TargetList = pallet_staking::UseValidatorsMap; - type NominationsQuota = pallet_staking::FixedNominationsQuota<16>; - type MaxUnlockingChunks = ConstU32<10>; - type MaxControllersInDeprecationBatch = ConstU32<100>; type EventListeners = (Pools, DelegatedStaking); - type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; - type WeightInfo = (); - type DisablingStrategy = pallet_staking::UpToLimitDisablingStrategy; } parameter_types! { diff --git a/substrate/frame/delegated-staking/src/tests.rs b/substrate/frame/delegated-staking/src/tests.rs index d40539d40ddda..2295f7d0c8719 100644 --- a/substrate/frame/delegated-staking/src/tests.rs +++ b/substrate/frame/delegated-staking/src/tests.rs @@ -501,17 +501,17 @@ mod staking_integration { ExtBuilder::default().build_and_execute(|| { start_era(1); let agent = 200; - setup_delegation_stake(agent, 201, (300..350).collect(), 100, 0); + setup_delegation_stake(agent, 201, (300..350).collect(), 320, 0); // verify withdraw not possible yet assert_noop!( - DelegatedStaking::release_delegation(RawOrigin::Signed(agent).into(), 300, 100, 0), + DelegatedStaking::release_delegation(RawOrigin::Signed(agent).into(), 300, 320, 0), Error::::NotEnoughFunds ); // fill up unlocking chunks in core staking. - // 10 is the max chunks - for i in 2..=11 { + // 32 is the max chunks + for i in 2..=33 { start_era(i); assert_ok!(Staking::unbond(RawOrigin::Signed(agent).into(), 10)); // no withdrawals from core staking yet. @@ -519,35 +519,35 @@ mod staking_integration { } // another unbond would trigger withdrawal - start_era(12); + start_era(34); assert_ok!(Staking::unbond(RawOrigin::Signed(agent).into(), 10)); - // 8 previous unbonds would be withdrawn as they were already unlocked. Unlocking period - // is 3 eras. - assert_eq!(get_agent_ledger(&agent).ledger.unclaimed_withdrawals, 8 * 10); + // 30 previous unbonds would be withdrawn as they were already unlocked. Unlocking + // period is 3 eras. + assert_eq!(get_agent_ledger(&agent).ledger.unclaimed_withdrawals, 30 * 10); // release some delegation now. assert_ok!(DelegatedStaking::release_delegation( RawOrigin::Signed(agent).into(), 300, - 40, + 160, 0 )); - assert_eq!(get_agent_ledger(&agent).ledger.unclaimed_withdrawals, 80 - 40); + assert_eq!(get_agent_ledger(&agent).ledger.unclaimed_withdrawals, 300 - 160); // cannot release more than available assert_noop!( - DelegatedStaking::release_delegation(RawOrigin::Signed(agent).into(), 300, 50, 0), + DelegatedStaking::release_delegation(RawOrigin::Signed(agent).into(), 300, 141, 0), Error::::NotEnoughFunds ); assert_ok!(DelegatedStaking::release_delegation( RawOrigin::Signed(agent).into(), 300, - 40, + 140, 0 )); - assert_eq!(DelegatedStaking::held_balance_of(Delegator::from(300)), 100 - 80); + assert_eq!(DelegatedStaking::held_balance_of(Delegator::from(300)), 320 - 300); }); } diff --git a/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs b/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs index 9c4991513633f..bb1bdb3142056 100644 --- a/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs +++ b/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs @@ -229,7 +229,6 @@ parameter_types! { pub const SessionsPerEra: sp_staking::SessionIndex = 2; pub static BondingDuration: sp_staking::EraIndex = 28; pub const SlashDeferDuration: sp_staking::EraIndex = 7; // 1/4 the bonding duration. - pub HistoryDepth: u32 = 84; } impl pallet_bags_list::Config for Runtime { @@ -285,15 +284,11 @@ const MAX_QUOTA_NOMINATIONS: u32 = 16; /// Disabling factor set explicitly to byzantine threshold pub(crate) const SLASHING_DISABLING_FACTOR: usize = 3; +#[derive_impl(pallet_staking::config_preludes::TestDefaultConfig)] impl pallet_staking::Config for Runtime { type Currency = Balances; type CurrencyBalance = Balance; type UnixTime = Timestamp; - type CurrencyToVote = (); - type RewardRemainder = (); - type RuntimeEvent = RuntimeEvent; - type Slash = (); // burn slashes - type Reward = (); // rewards are minted from the void type SessionsPerEra = SessionsPerEra; type BondingDuration = BondingDuration; type SlashDeferDuration = SlashDeferDuration; @@ -308,12 +303,10 @@ impl pallet_staking::Config for Runtime { type NominationsQuota = pallet_staking::FixedNominationsQuota; type TargetList = pallet_staking::UseValidatorsMap; type MaxUnlockingChunks = MaxUnlockingChunks; - type MaxControllersInDeprecationBatch = ConstU32<100>; - type HistoryDepth = HistoryDepth; type EventListeners = Pools; type WeightInfo = pallet_staking::weights::SubstrateWeight; - type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; type DisablingStrategy = pallet_staking::UpToLimitDisablingStrategy; + type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; } impl frame_system::offchain::SendTransactionTypes for Runtime diff --git a/substrate/frame/fast-unstake/src/mock.rs b/substrate/frame/fast-unstake/src/mock.rs index 63bf533d8ee45..7ce7fee141078 100644 --- a/substrate/frame/fast-unstake/src/mock.rs +++ b/substrate/frame/fast-unstake/src/mock.rs @@ -104,35 +104,17 @@ impl frame_election_provider_support::ElectionProvider for MockElection { } } +#[derive_impl(pallet_staking::config_preludes::TestDefaultConfig)] impl pallet_staking::Config for Runtime { type Currency = Balances; - type CurrencyBalance = Balance; type UnixTime = pallet_timestamp::Pallet; - type CurrencyToVote = (); - type RewardRemainder = (); - type RuntimeEvent = RuntimeEvent; - type Slash = (); - type Reward = (); - type SessionsPerEra = (); - type SlashDeferDuration = (); type AdminOrigin = frame_system::EnsureRoot; type BondingDuration = BondingDuration; - type SessionInterface = (); type EraPayout = pallet_staking::ConvertCurve; - type NextNewSession = (); - type HistoryDepth = ConstU32<84>; - type MaxExposurePageSize = ConstU32<64>; type ElectionProvider = MockElection; type GenesisElectionProvider = Self::ElectionProvider; type VoterList = pallet_staking::UseNominatorsAndValidatorsMap; type TargetList = pallet_staking::UseValidatorsMap; - type NominationsQuota = pallet_staking::FixedNominationsQuota<16>; - type MaxUnlockingChunks = ConstU32<32>; - type MaxControllersInDeprecationBatch = ConstU32<100>; - type EventListeners = (); - type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; - type WeightInfo = (); - type DisablingStrategy = pallet_staking::UpToLimitDisablingStrategy; } parameter_types! { diff --git a/substrate/frame/grandpa/src/mock.rs b/substrate/frame/grandpa/src/mock.rs index 5642ffe899808..5ba7da7f9fda2 100644 --- a/substrate/frame/grandpa/src/mock.rs +++ b/substrate/frame/grandpa/src/mock.rs @@ -150,35 +150,22 @@ impl onchain::Config for OnChainSeqPhragmen { type Bounds = ElectionsBoundsOnChain; } +#[derive_impl(pallet_staking::config_preludes::TestDefaultConfig)] impl pallet_staking::Config for Test { - type RewardRemainder = (); - type CurrencyToVote = (); - type RuntimeEvent = RuntimeEvent; type Currency = Balances; type CurrencyBalance = ::Balance; - type Slash = (); - type Reward = (); type SessionsPerEra = SessionsPerEra; type BondingDuration = BondingDuration; - type SlashDeferDuration = (); type AdminOrigin = frame_system::EnsureRoot; type SessionInterface = Self; type UnixTime = pallet_timestamp::Pallet; type EraPayout = pallet_staking::ConvertCurve; - type MaxExposurePageSize = ConstU32<64>; type NextNewSession = Session; type ElectionProvider = onchain::OnChainExecution; type GenesisElectionProvider = Self::ElectionProvider; type VoterList = pallet_staking::UseNominatorsAndValidatorsMap; type TargetList = pallet_staking::UseValidatorsMap; type NominationsQuota = pallet_staking::FixedNominationsQuota<16>; - type MaxUnlockingChunks = ConstU32<32>; - type MaxControllersInDeprecationBatch = ConstU32<100>; - type HistoryDepth = ConstU32<84>; - type EventListeners = (); - type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; - type WeightInfo = (); - type DisablingStrategy = pallet_staking::UpToLimitDisablingStrategy; } impl pallet_offences::Config for Test { diff --git a/substrate/frame/nomination-pools/benchmarking/src/mock.rs b/substrate/frame/nomination-pools/benchmarking/src/mock.rs index b9cff7960716e..15d9e2c56031f 100644 --- a/substrate/frame/nomination-pools/benchmarking/src/mock.rs +++ b/substrate/frame/nomination-pools/benchmarking/src/mock.rs @@ -76,36 +76,19 @@ pallet_staking_reward_curve::build! { parameter_types! { pub const RewardCurve: &'static sp_runtime::curve::PiecewiseLinear<'static> = &I_NPOS; } +#[derive_impl(pallet_staking::config_preludes::TestDefaultConfig)] impl pallet_staking::Config for Runtime { type Currency = Balances; type CurrencyBalance = Balance; type UnixTime = pallet_timestamp::Pallet; - type CurrencyToVote = (); - type RewardRemainder = (); - type RuntimeEvent = RuntimeEvent; - type Slash = (); - type Reward = (); - type SessionsPerEra = (); - type SlashDeferDuration = (); type AdminOrigin = frame_system::EnsureRoot; - type BondingDuration = ConstU32<3>; - type SessionInterface = (); type EraPayout = pallet_staking::ConvertCurve; - type NextNewSession = (); - type MaxExposurePageSize = ConstU32<64>; type ElectionProvider = frame_election_provider_support::NoElection<(AccountId, BlockNumber, Staking, ())>; type GenesisElectionProvider = Self::ElectionProvider; type VoterList = VoterList; type TargetList = pallet_staking::UseValidatorsMap; - type NominationsQuota = pallet_staking::FixedNominationsQuota<16>; - type MaxControllersInDeprecationBatch = ConstU32<100>; - type MaxUnlockingChunks = ConstU32<32>; - type HistoryDepth = ConstU32<84>; type EventListeners = (Pools, DelegatedStaking); - type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; - type WeightInfo = (); - type DisablingStrategy = pallet_staking::UpToLimitDisablingStrategy; } parameter_types! { diff --git a/substrate/frame/nomination-pools/test-delegate-stake/src/mock.rs b/substrate/frame/nomination-pools/test-delegate-stake/src/mock.rs index 0a456503ad81b..ed47932a323bf 100644 --- a/substrate/frame/nomination-pools/test-delegate-stake/src/mock.rs +++ b/substrate/frame/nomination-pools/test-delegate-stake/src/mock.rs @@ -90,36 +90,20 @@ parameter_types! { pub static BondingDuration: u32 = 3; } +#[derive_impl(pallet_staking::config_preludes::TestDefaultConfig)] impl pallet_staking::Config for Runtime { type Currency = Balances; - type CurrencyBalance = Balance; type UnixTime = pallet_timestamp::Pallet; - type CurrencyToVote = (); - type RewardRemainder = (); - type RuntimeEvent = RuntimeEvent; - type Slash = (); - type Reward = (); - type SessionsPerEra = (); - type SlashDeferDuration = (); type AdminOrigin = frame_system::EnsureRoot; type BondingDuration = BondingDuration; - type SessionInterface = (); type EraPayout = pallet_staking::ConvertCurve; - type NextNewSession = (); - type MaxExposurePageSize = ConstU32<64>; type ElectionProvider = frame_election_provider_support::NoElection<(AccountId, BlockNumber, Staking, ())>; type GenesisElectionProvider = Self::ElectionProvider; type VoterList = VoterList; type TargetList = pallet_staking::UseValidatorsMap; - type NominationsQuota = pallet_staking::FixedNominationsQuota<16>; - type MaxUnlockingChunks = ConstU32<32>; - type MaxControllersInDeprecationBatch = ConstU32<100>; - type HistoryDepth = ConstU32<84>; type EventListeners = (Pools, DelegatedStaking); type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; - type WeightInfo = (); - type DisablingStrategy = pallet_staking::UpToLimitDisablingStrategy; } parameter_types! { diff --git a/substrate/frame/nomination-pools/test-transfer-stake/src/mock.rs b/substrate/frame/nomination-pools/test-transfer-stake/src/mock.rs index 570cdea904609..d913c5fe6948c 100644 --- a/substrate/frame/nomination-pools/test-transfer-stake/src/mock.rs +++ b/substrate/frame/nomination-pools/test-transfer-stake/src/mock.rs @@ -82,36 +82,20 @@ parameter_types! { pub static BondingDuration: u32 = 3; } +#[derive_impl(pallet_staking::config_preludes::TestDefaultConfig)] impl pallet_staking::Config for Runtime { type Currency = Balances; - type CurrencyBalance = Balance; type UnixTime = pallet_timestamp::Pallet; - type CurrencyToVote = (); - type RewardRemainder = (); - type RuntimeEvent = RuntimeEvent; - type Slash = (); - type Reward = (); - type SessionsPerEra = (); - type SlashDeferDuration = (); type AdminOrigin = frame_system::EnsureRoot; type BondingDuration = BondingDuration; - type SessionInterface = (); type EraPayout = pallet_staking::ConvertCurve; - type NextNewSession = (); - type MaxExposurePageSize = ConstU32<64>; type ElectionProvider = frame_election_provider_support::NoElection<(AccountId, BlockNumber, Staking, ())>; type GenesisElectionProvider = Self::ElectionProvider; type VoterList = VoterList; type TargetList = pallet_staking::UseValidatorsMap; - type NominationsQuota = pallet_staking::FixedNominationsQuota<16>; - type MaxUnlockingChunks = ConstU32<32>; - type MaxControllersInDeprecationBatch = ConstU32<100>; - type HistoryDepth = ConstU32<84>; type EventListeners = Pools; type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; - type WeightInfo = (); - type DisablingStrategy = pallet_staking::UpToLimitDisablingStrategy; } parameter_types! { diff --git a/substrate/frame/offences/benchmarking/src/mock.rs b/substrate/frame/offences/benchmarking/src/mock.rs index e45d280ba52e2..e243ad0e718eb 100644 --- a/substrate/frame/offences/benchmarking/src/mock.rs +++ b/substrate/frame/offences/benchmarking/src/mock.rs @@ -124,35 +124,19 @@ impl onchain::Config for OnChainSeqPhragmen { type Bounds = ElectionsBounds; } +#[derive_impl(pallet_staking::config_preludes::TestDefaultConfig)] impl pallet_staking::Config for Test { type Currency = Balances; type CurrencyBalance = ::Balance; type UnixTime = pallet_timestamp::Pallet; - type CurrencyToVote = (); - type RewardRemainder = (); - type RuntimeEvent = RuntimeEvent; - type Slash = (); - type Reward = (); - type SessionsPerEra = (); - type SlashDeferDuration = (); type AdminOrigin = frame_system::EnsureRoot; - type BondingDuration = (); type SessionInterface = Self; type EraPayout = pallet_staking::ConvertCurve; type NextNewSession = Session; - type MaxExposurePageSize = ConstU32<64>; type ElectionProvider = onchain::OnChainExecution; type GenesisElectionProvider = Self::ElectionProvider; type VoterList = pallet_staking::UseNominatorsAndValidatorsMap; type TargetList = pallet_staking::UseValidatorsMap; - type NominationsQuota = pallet_staking::FixedNominationsQuota<16>; - type MaxUnlockingChunks = ConstU32<32>; - type MaxControllersInDeprecationBatch = ConstU32<100>; - type HistoryDepth = ConstU32<84>; - type EventListeners = (); - type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; - type WeightInfo = (); - type DisablingStrategy = pallet_staking::UpToLimitDisablingStrategy; } impl pallet_im_online::Config for Test { diff --git a/substrate/frame/root-offences/src/mock.rs b/substrate/frame/root-offences/src/mock.rs index ea7044fb6a347..3c758b91d52fe 100644 --- a/substrate/frame/root-offences/src/mock.rs +++ b/substrate/frame/root-offences/src/mock.rs @@ -124,15 +124,11 @@ parameter_types! { pub static LedgerSlashPerEra: (BalanceOf, BTreeMap>) = (Zero::zero(), BTreeMap::new()); } +#[derive_impl(pallet_staking::config_preludes::TestDefaultConfig)] impl pallet_staking::Config for Test { type Currency = Balances; type CurrencyBalance = ::Balance; type UnixTime = Timestamp; - type CurrencyToVote = (); - type RewardRemainder = (); - type RuntimeEvent = RuntimeEvent; - type Slash = (); - type Reward = (); type SessionsPerEra = SessionsPerEra; type SlashDeferDuration = SlashDeferDuration; type AdminOrigin = frame_system::EnsureRoot; @@ -140,19 +136,10 @@ impl pallet_staking::Config for Test { type SessionInterface = Self; type EraPayout = pallet_staking::ConvertCurve; type NextNewSession = Session; - type MaxExposurePageSize = ConstU32<64>; type ElectionProvider = onchain::OnChainExecution; type GenesisElectionProvider = Self::ElectionProvider; type TargetList = pallet_staking::UseValidatorsMap; - type NominationsQuota = pallet_staking::FixedNominationsQuota<16>; - type MaxUnlockingChunks = ConstU32<32>; - type HistoryDepth = ConstU32<84>; - type MaxControllersInDeprecationBatch = ConstU32<100>; type VoterList = pallet_staking::UseNominatorsAndValidatorsMap; - type EventListeners = (); - type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; - type WeightInfo = (); - type DisablingStrategy = pallet_staking::UpToLimitDisablingStrategy; } impl pallet_session::historical::Config for Test { diff --git a/substrate/frame/session/benchmarking/src/mock.rs b/substrate/frame/session/benchmarking/src/mock.rs index b79bae73270e4..2aec58cceded2 100644 --- a/substrate/frame/session/benchmarking/src/mock.rs +++ b/substrate/frame/session/benchmarking/src/mock.rs @@ -129,35 +129,19 @@ impl onchain::Config for OnChainSeqPhragmen { type Bounds = ElectionsBounds; } +#[derive_impl(pallet_staking::config_preludes::TestDefaultConfig)] impl pallet_staking::Config for Test { type Currency = Balances; type CurrencyBalance = ::Balance; type UnixTime = pallet_timestamp::Pallet; - type CurrencyToVote = (); - type RewardRemainder = (); - type RuntimeEvent = RuntimeEvent; - type Slash = (); - type Reward = (); - type SessionsPerEra = (); - type SlashDeferDuration = (); type AdminOrigin = frame_system::EnsureRoot; - type BondingDuration = (); type SessionInterface = Self; type EraPayout = pallet_staking::ConvertCurve; type NextNewSession = Session; - type MaxExposurePageSize = ConstU32<64>; type ElectionProvider = onchain::OnChainExecution; type GenesisElectionProvider = Self::ElectionProvider; - type MaxUnlockingChunks = ConstU32<32>; - type MaxControllersInDeprecationBatch = ConstU32<100>; - type HistoryDepth = ConstU32<84>; type VoterList = pallet_staking::UseNominatorsAndValidatorsMap; type TargetList = pallet_staking::UseValidatorsMap; - type NominationsQuota = pallet_staking::FixedNominationsQuota<16>; - type EventListeners = (); - type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; - type WeightInfo = (); - type DisablingStrategy = pallet_staking::UpToLimitDisablingStrategy; } impl crate::Config for Test {} diff --git a/substrate/frame/staking/src/mock.rs b/substrate/frame/staking/src/mock.rs index 6d65500ef9078..7e6a87955b083 100644 --- a/substrate/frame/staking/src/mock.rs +++ b/substrate/frame/staking/src/mock.rs @@ -261,19 +261,15 @@ impl OnStakingUpdate for EventListenerMock { // Disabling threshold for `UpToLimitDisablingStrategy` pub(crate) const DISABLING_LIMIT_FACTOR: usize = 3; +#[derive_impl(crate::config_preludes::TestDefaultConfig)] impl crate::pallet::pallet::Config for Test { type Currency = Balances; - type CurrencyBalance = ::Balance; type UnixTime = Timestamp; - type CurrencyToVote = (); type RewardRemainder = RewardRemainderMock; - type RuntimeEvent = RuntimeEvent; - type Slash = (); type Reward = MockReward; type SessionsPerEra = SessionsPerEra; type SlashDeferDuration = SlashDeferDuration; type AdminOrigin = EnsureOneOrRoot; - type BondingDuration = BondingDuration; type SessionInterface = Self; type EraPayout = ConvertCurve; type NextNewSession = Session; @@ -288,8 +284,6 @@ impl crate::pallet::pallet::Config for Test { type HistoryDepth = HistoryDepth; type MaxControllersInDeprecationBatch = MaxControllersInDeprecationBatch; type EventListeners = EventListenerMock; - type BenchmarkingConfig = TestBenchmarkingConfig; - type WeightInfo = (); type DisablingStrategy = pallet_staking::UpToLimitDisablingStrategy; } diff --git a/substrate/frame/staking/src/pallet/mod.rs b/substrate/frame/staking/src/pallet/mod.rs index 284a801a0f050..a76e47edf3803 100644 --- a/substrate/frame/staking/src/pallet/mod.rs +++ b/substrate/frame/staking/src/pallet/mod.rs @@ -86,9 +86,10 @@ pub mod pallet { Remove, } - #[pallet::config] + #[pallet::config(with_default)] pub trait Config: frame_system::Config { /// The staking balance. + #[pallet::no_default] type Currency: LockableCurrency< Self::AccountId, Moment = BlockNumberFor, @@ -109,6 +110,7 @@ pub mod pallet { /// /// It is guaranteed to start being called from the first `on_finalize`. Thus value at /// genesis is not used. + #[pallet::no_default] type UnixTime: UnixTime; /// Convert a balance into a number used for election calculation. This must fit into a @@ -117,9 +119,11 @@ pub mod pallet { /// in 128. /// Consequently, the backward convert is used convert the u128s from sp-elections back to a /// [`BalanceOf`]. + #[pallet::no_default_bounds] type CurrencyToVote: sp_staking::currency_to_vote::CurrencyToVote>; /// Something that provides the election functionality. + #[pallet::no_default] type ElectionProvider: ElectionProvider< AccountId = Self::AccountId, BlockNumber = BlockNumberFor, @@ -127,6 +131,7 @@ pub mod pallet { DataProvider = Pallet, >; /// Something that provides the election functionality at genesis. + #[pallet::no_default] type GenesisElectionProvider: ElectionProvider< AccountId = Self::AccountId, BlockNumber = BlockNumberFor, @@ -134,6 +139,7 @@ pub mod pallet { >; /// Something that defines the maximum number of nominations per nominator. + #[pallet::no_default_bounds] type NominationsQuota: NominationsQuota>; /// Number of eras to keep in history. @@ -161,17 +167,21 @@ pub mod pallet { /// Tokens have been minted and are unused for validator-reward. /// See [Era payout](./index.html#era-payout). + #[pallet::no_default_bounds] type RewardRemainder: OnUnbalanced>; /// The overarching event type. + #[pallet::no_default_bounds] type RuntimeEvent: From> + IsType<::RuntimeEvent>; /// Handler for the unbalanced reduction when slashing a staker. + #[pallet::no_default_bounds] type Slash: OnUnbalanced>; /// Handler for the unbalanced increment when rewarding a staker. /// NOTE: in most cases, the implementation of `OnUnbalanced` should modify the total /// issuance. + #[pallet::no_default_bounds] type Reward: OnUnbalanced>; /// Number of sessions per era. @@ -192,6 +202,7 @@ pub mod pallet { /// The origin which can manage less critical staking parameters that does not require root. /// /// Supported actions: (1) cancel deferred slash, (2) set minimum commission. + #[pallet::no_default] type AdminOrigin: EnsureOrigin; /// Interface for interacting with a session pallet. @@ -199,10 +210,12 @@ pub mod pallet { /// The payout for validators and the system for the current era. /// See [Era payout](./index.html#era-payout). + #[pallet::no_default] type EraPayout: EraPayout>; /// Something that can estimate the next session change, accurately or as a best effort /// guess. + #[pallet::no_default_bounds] type NextNewSession: EstimateNextNewSession>; /// The maximum size of each `T::ExposurePage`. @@ -230,6 +243,7 @@ pub mod pallet { /// staker. In case of `bags-list`, this always means using `rebag` and `putInFrontOf`. /// /// Invariant: what comes out of this list will always be a nominator. + #[pallet::no_default] type VoterList: SortedListProvider; /// WIP: This is a noop as of now, the actual business logic that's described below is going @@ -252,6 +266,7 @@ pub mod pallet { /// validators, they can chill at any point, and their approval stakes will still be /// recorded. This implies that what comes out of iterating this list MIGHT NOT BE AN ACTIVE /// VALIDATOR. + #[pallet::no_default] type TargetList: SortedListProvider>; /// The maximum number of `unlocking` chunks a [`StakingLedger`] can @@ -274,18 +289,66 @@ pub mod pallet { /// receives. /// /// WARNING: this only reports slashing and withdraw events for the time being. + #[pallet::no_default_bounds] type EventListeners: sp_staking::OnStakingUpdate>; - // `DisablingStragegy` controls how validators are disabled + /// `DisablingStragegy` controls how validators are disabled + #[pallet::no_default_bounds] type DisablingStrategy: DisablingStrategy; /// Some parameters of the benchmarking. + #[cfg(feature = "std")] + type BenchmarkingConfig: BenchmarkingConfig; + + #[cfg(not(feature = "std"))] + #[pallet::no_default] type BenchmarkingConfig: BenchmarkingConfig; /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; } + /// Default implementations of [`DefaultConfig`], which can be used to implement [`Config`]. + pub mod config_preludes { + use super::*; + use frame_support::{derive_impl, parameter_types, traits::ConstU32}; + pub struct TestDefaultConfig; + + #[derive_impl(frame_system::config_preludes::TestDefaultConfig, no_aggregated_types)] + impl frame_system::DefaultConfig for TestDefaultConfig {} + + parameter_types! { + pub const SessionsPerEra: SessionIndex = 3; + pub const BondingDuration: EraIndex = 3; + } + + #[frame_support::register_default_impl(TestDefaultConfig)] + impl DefaultConfig for TestDefaultConfig { + #[inject_runtime_type] + type RuntimeEvent = (); + type CurrencyBalance = u128; + type CurrencyToVote = (); + type NominationsQuota = crate::FixedNominationsQuota<16>; + type HistoryDepth = ConstU32<84>; + type RewardRemainder = (); + type Slash = (); + type Reward = (); + type SessionsPerEra = SessionsPerEra; + type BondingDuration = BondingDuration; + type SlashDeferDuration = (); + type SessionInterface = (); + type NextNewSession = (); + type MaxExposurePageSize = ConstU32<64>; + type MaxUnlockingChunks = ConstU32<32>; + type MaxControllersInDeprecationBatch = ConstU32<100>; + type EventListeners = (); + type DisablingStrategy = crate::UpToLimitDisablingStrategy; + #[cfg(feature = "std")] + type BenchmarkingConfig = crate::TestBenchmarkingConfig; + type WeightInfo = (); + } + } + /// The ideal number of active validators. #[pallet::storage] #[pallet::getter(fn validator_count)] From 2e39e052adfe951a3f2b70833111a8026ce3f992 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Mon, 17 Jun 2024 15:56:00 +0200 Subject: [PATCH 4/9] Improve pruning CLI documentation (#4810) Closes: https://github.com/paritytech/polkadot-sdk/issues/4801 @andreclaro I hope this makes it more clear from the docs directly. --- .../client/cli/src/params/pruning_params.rs | 41 +++++++++++++------ 1 file changed, 28 insertions(+), 13 deletions(-) diff --git a/substrate/client/cli/src/params/pruning_params.rs b/substrate/client/cli/src/params/pruning_params.rs index 25b17b5328981..88ae006c638e5 100644 --- a/substrate/client/cli/src/params/pruning_params.rs +++ b/substrate/client/cli/src/params/pruning_params.rs @@ -17,7 +17,7 @@ // along with this program. If not, see . use crate::error; -use clap::Args; +use clap::{builder::PossibleValue, Args, ValueEnum}; use sc_service::{BlocksPruning, PruningMode}; /// Parameters to define the pruning mode @@ -29,29 +29,24 @@ pub struct PruningParams { /// should be pruned (ie, removed) from the database. /// This setting can only be set on the first creation of the database. Every subsequent run /// will load the pruning mode from the database and will error if the stored mode doesn't - /// match this CLI value. It is fine to drop this CLI flag for subsequent runs. - /// Possible values: - /// - archive: Keep the state of all blocks. - /// - 'archive-canonical' Keep only the state of finalized blocks. - /// - number Keep the state of the last number of finalized blocks. + /// match this CLI value. It is fine to drop this CLI flag for subsequent runs. The only + /// exception is that `` can change between subsequent runs (increasing it will not + /// lead to restoring pruned state). + /// /// [default: 256] - #[arg(alias = "pruning", long, value_name = "PRUNING_MODE")] + #[arg(alias = "pruning", long, value_name = "PRUNING_MODE", value_enum)] pub state_pruning: Option, /// Specify the blocks pruning mode. /// /// This mode specifies when the block's body (including justifications) /// should be pruned (ie, removed) from the database. - /// Possible values: - /// - 'archive' Keep all blocks. - /// - 'archive-canonical' Keep only finalized blocks. - /// - number - /// Keep the last `number` of finalized blocks. #[arg( alias = "keep-blocks", long, value_name = "PRUNING_MODE", - default_value = "archive-canonical" + default_value_t = DatabasePruningMode::ArchiveCanonical, + value_enum )] pub blocks_pruning: DatabasePruningMode, } @@ -83,6 +78,26 @@ pub enum DatabasePruningMode { Custom(u32), } +impl ValueEnum for DatabasePruningMode { + fn value_variants<'a>() -> &'a [Self] { + &[Self::Archive, Self::ArchiveCanonical, Self::Custom(0)] + } + + fn to_possible_value(&self) -> Option { + Some(match self { + Self::Archive => PossibleValue::new("archive").help("Keep the data of all blocks."), + Self::ArchiveCanonical => PossibleValue::new("archive-canonical") + .help("Keep only the data of finalized blocks."), + Self::Custom(_) => PossibleValue::new("") + .help("Keep the data of the last of finalized blocks."), + }) + } + + fn from_str(input: &str, _: bool) -> Result { + ::from_str(input) + } +} + impl std::str::FromStr for DatabasePruningMode { type Err = String; From fed508f962f283600b2cc15335a3659efb0ceae9 Mon Sep 17 00:00:00 2001 From: hattizai Date: Mon, 17 Jun 2024 22:13:48 +0800 Subject: [PATCH 5/9] chore: remove unnecessary words (#4796) remove unnecessary words in comments. --- docs/sdk/src/guides/your_first_pallet/mod.rs | 6 +++--- substrate/primitives/trie/src/lib.rs | 10 +++++----- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/sdk/src/guides/your_first_pallet/mod.rs b/docs/sdk/src/guides/your_first_pallet/mod.rs index 0a22b13df814d..da4624f5ac2b8 100644 --- a/docs/sdk/src/guides/your_first_pallet/mod.rs +++ b/docs/sdk/src/guides/your_first_pallet/mod.rs @@ -626,7 +626,7 @@ pub mod pallet { #[test] fn transfer_works() { StateBuilder::default().build_and_execute(|| { - // given the the initial state, when: + // given the initial state, when: assert_ok!(Pallet::::transfer(RuntimeOrigin::signed(ALICE), BOB, 50)); // then: @@ -648,7 +648,7 @@ pub mod pallet { #[test] fn transfer_from_non_existent_fails() { StateBuilder::default().build_and_execute(|| { - // given the the initial state, when: + // given the initial state, when: assert_err!( Pallet::::transfer(RuntimeOrigin::signed(CHARLIE), ALICE, 10), "NonExistentAccount" @@ -769,7 +769,7 @@ pub mod pallet_v2 { // the final assertion. System::set_block_number(ALICE); - // given the the initial state, when: + // given the initial state, when: assert_ok!(Pallet::::transfer(RuntimeOrigin::signed(ALICE), BOB, 50)); // then: diff --git a/substrate/primitives/trie/src/lib.rs b/substrate/primitives/trie/src/lib.rs index 54f202eda0c9a..0c14e3af196d0 100644 --- a/substrate/primitives/trie/src/lib.rs +++ b/substrate/primitives/trie/src/lib.rs @@ -195,11 +195,11 @@ pub type MemoryDB = memory_db::MemoryDB, trie_db::DB /// Reexport from `hash_db`, with genericity set for `Hasher` trait. pub type GenericMemoryDB = memory_db::MemoryDB; -/// Persistent trie database read-access interface for the a given hasher. +/// Persistent trie database read-access interface for a given hasher. pub type TrieDB<'a, 'cache, L> = trie_db::TrieDB<'a, 'cache, L>; /// Builder for creating a [`TrieDB`]. pub type TrieDBBuilder<'a, 'cache, L> = trie_db::TrieDBBuilder<'a, 'cache, L>; -/// Persistent trie database write-access interface for the a given hasher. +/// Persistent trie database write-access interface for a given hasher. pub type TrieDBMut<'a, L> = trie_db::TrieDBMut<'a, L>; /// Builder for creating a [`TrieDBMut`]. pub type TrieDBMutBuilder<'a, L> = trie_db::TrieDBMutBuilder<'a, L>; @@ -212,17 +212,17 @@ pub type TrieHash = <::Hash as Hasher>::Out; pub mod trie_types { use super::*; - /// Persistent trie database read-access interface for the a given hasher. + /// Persistent trie database read-access interface for a given hasher. /// /// Read only V1 and V0 are compatible, thus we always use V1. pub type TrieDB<'a, 'cache, H> = super::TrieDB<'a, 'cache, LayoutV1>; /// Builder for creating a [`TrieDB`]. pub type TrieDBBuilder<'a, 'cache, H> = super::TrieDBBuilder<'a, 'cache, LayoutV1>; - /// Persistent trie database write-access interface for the a given hasher. + /// Persistent trie database write-access interface for a given hasher. pub type TrieDBMutV0<'a, H> = super::TrieDBMut<'a, LayoutV0>; /// Builder for creating a [`TrieDBMutV0`]. pub type TrieDBMutBuilderV0<'a, H> = super::TrieDBMutBuilder<'a, LayoutV0>; - /// Persistent trie database write-access interface for the a given hasher. + /// Persistent trie database write-access interface for a given hasher. pub type TrieDBMutV1<'a, H> = super::TrieDBMut<'a, LayoutV1>; /// Builder for creating a [`TrieDBMutV1`]. pub type TrieDBMutBuilderV1<'a, H> = super::TrieDBMutBuilder<'a, LayoutV1>; From 6cb3bd23910ec48ab37a3c95a6b03286ff2979bf Mon Sep 17 00:00:00 2001 From: Tom Mi Date: Mon, 17 Jun 2024 18:11:21 +0300 Subject: [PATCH 6/9] Ibp bootnodes for Kusama People (#6) (#4741) * fix rotko's pcollectives bootnode * Update people-kusama.json * Add Dwellir People Kusama bootnode * add Gatotech bootnodes to `people-kusama` * Add Dwellir People Kusama bootnode * Update Amforc bootnodes for Kusama and Polkadot (#4668) --------- Co-authored-by: RadiumBlock Co-authored-by: Jonathan Udd Co-authored-by: Milos Kriz Co-authored-by: tugy <33746108+tugytur@users.noreply.github.com> Co-authored-by: Kutsal Kaan Bilgin Co-authored-by: Petr Mensik Co-authored-by: Tommi --- .../chain-specs/collectives-polkadot.json | 5 ++--- .../parachains/chain-specs/people-kusama.json | 20 ++++++++++++++++++- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/cumulus/parachains/chain-specs/collectives-polkadot.json b/cumulus/parachains/chain-specs/collectives-polkadot.json index a0d5ddff6ebb1..a6ba01ffa394d 100644 --- a/cumulus/parachains/chain-specs/collectives-polkadot.json +++ b/cumulus/parachains/chain-specs/collectives-polkadot.json @@ -23,9 +23,8 @@ "/dns/polkadot-collectives-boot-ng.dwellir.com/tcp/443/wss/p2p/12D3KooWDMFYCNRAQcSRNV7xu2xv8319goSEbSHW4TnXRz6EpPKc", "/dns/collectives-polkadot-bootnode.radiumblock.com/tcp/30333/p2p/12D3KooWDumvnNwPbBg5inBEapgjKU7ECdMHHgwfYeGWUkzYUE1c", "/dns/collectives-polkadot-bootnode.radiumblock.com/tcp/30336/wss/p2p/12D3KooWDumvnNwPbBg5inBEapgjKU7ECdMHHgwfYeGWUkzYUE1c", - "/dns/pch13.rotko.net/tcp/33573/p2p/12D3KooWRXudHoazPZ9osMfdY38e8CBxQLD4RhrVeHpRSNNpcDtH", - "/dns/pch13.rotko.net/tcp/34573/ws/p2p/12D3KooWRXudHoazPZ9osMfdY38e8CBxQLD4RhrVeHpRSNNpcDtH", - "/dns/pch13.rotko.net/tcp/35573/wss/p2p/12D3KooWRXudHoazPZ9osMfdY38e8CBxQLD4RhrVeHpRSNNpcDtH", + "/dns/pch16.rotko.net/tcp/33576/p2p/12D3KooWKrm3XmuGzJH17Wcn4HRDGsEjLZGDgN77q3ZhwnnQP7y1", + "/dns/pch16.rotko.net/tcp/35576/wss/p2p/12D3KooWKrm3XmuGzJH17Wcn4HRDGsEjLZGDgN77q3ZhwnnQP7y1", "/dns/collectives-polkadot.bootnodes.polkadotters.com/tcp/30526/p2p/12D3KooWNohUjvJtGKUa8Vhy8C1ZBB5N8JATB6e7rdLVCioeb3ff", "/dns/collectives-polkadot.bootnodes.polkadotters.com/tcp/30528/wss/p2p/12D3KooWNohUjvJtGKUa8Vhy8C1ZBB5N8JATB6e7rdLVCioeb3ff", "/dns/boot-polkadot-collectives.luckyfriday.io/tcp/443/wss/p2p/12D3KooWCzifnPooTt4kvTnXT7FTKTymVL7xn7DURQLsS2AKpf6w" diff --git a/cumulus/parachains/chain-specs/people-kusama.json b/cumulus/parachains/chain-specs/people-kusama.json index 00a38b675def7..3352cb25a2898 100644 --- a/cumulus/parachains/chain-specs/people-kusama.json +++ b/cumulus/parachains/chain-specs/people-kusama.json @@ -8,7 +8,25 @@ "/dns/kusama-people-connect-0.polkadot.io/tcp/443/wss/p2p/12D3KooWQaqG5TNmDfRWrtH7tMsN7YeqwVkSfoZT4GkemSzezNi1", "/dns/kusama-people-connect-1.polkadot.io/tcp/443/wss/p2p/12D3KooWKhYoQH9LdSyvY3SVZY9gFf6ZV1bFh6317TRehUP3r5fm", "/dns/people-kusama.bootnode.amforc.com/tcp/29999/wss/p2p/12D3KooWPjzgKZe5jdG6TY4gwcFq8QxyyhqsYbQo6N29pwGePWLA", - "/dns/people-kusama.bootnode.amforc.com/tcp/30004/p2p/12D3KooWPjzgKZe5jdG6TY4gwcFq8QxyyhqsYbQo6N29pwGePWLA" + "/dns/people-kusama.bootnode.amforc.com/tcp/30004/p2p/12D3KooWPjzgKZe5jdG6TY4gwcFq8QxyyhqsYbQo6N29pwGePWLA", + "/dns/boot.gatotech.network/tcp/33240/p2p/12D3KooWLi9TzaKX4zniJpiM521PnYG4EocpdqjPpJUhXq9QGkRX", + "/dns/boot.gatotech.network/tcp/35240/wss/p2p/12D3KooWLi9TzaKX4zniJpiM521PnYG4EocpdqjPpJUhXq9QGkRX", + "/dns/people-kusama-bootnode.radiumblock.com/tcp/30333/p2p/12D3KooWGP1C9iWTHnZyeaSjYZ7LdK8douXWc1n1dBv25XEASHaj", + "/dns/people-kusama-bootnode.radiumblock.com/tcp/30336/wss/p2p/12D3KooWGP1C9iWTHnZyeaSjYZ7LdK8douXWc1n1dBv25XEASHaj", + "/dns/kppl16.rotko.net/tcp/33756/p2p/12D3KooWSKQwgoydfbN6mNN2aNwdqfkR2ExAnTRs8mmdrPQTtDLo", + "/dns/kppl16.rotko.net/tcp/35756/wss/p2p/12D3KooWSKQwgoydfbN6mNN2aNwdqfkR2ExAnTRs8mmdrPQTtDLo", + "/dns/people-kusama-boot-ng.dwellir.com/tcp/30359/p2p/12D3KooWM6T8MMibxLZhhpq6F612CZ4FgnfDSJSkWDMiVUDe1aGb", + "/dns/people-kusama-boot-ng.dwellir.com/tcp/443/wss/p2p/12D3KooWM6T8MMibxLZhhpq6F612CZ4FgnfDSJSkWDMiVUDe1aGb", + "/dns/people-kusama-bootnode.turboflakes.io/tcp/30645/p2p/12D3KooWCR2Q8J2NFFfuofDak4zSgWkuBq7orP96HFaxLgAoDUBV", + "/dns/people-kusama-bootnode.turboflakes.io/tcp/30745/wss/p2p/12D3KooWCR2Q8J2NFFfuofDak4zSgWkuBq7orP96HFaxLgAoDUBV", + "/dns/boot-node.helikon.io/tcp/7510/p2p/12D3KooWM1X4setrMWjwnV8iDkAtYhqFHNkGozdWdq6sawWh5Yhv", + "/dns/boot-node.helikon.io/tcp/7512/wss/p2p/12D3KooWM1X4setrMWjwnV8iDkAtYhqFHNkGozdWdq6sawWh5Yhv", + "/dns/people-kusama.bootnodes.polkadotters.com/tcp/30377/p2p/12D3KooWHy7TAuK6EoVij2tfaeh3KkaEJxhTmumbEom3HfRnSEsp", + "/dns/people-kusama.bootnodes.polkadotters.com/tcp/30379/wss/p2p/12D3KooWHy7TAuK6EoVij2tfaeh3KkaEJxhTmumbEom3HfRnSEsp", + "/dns/boot.metaspan.io/tcp/25068/p2p/12D3KooWDoDLtLvQi8hhFVyubPZhaYuAwSAJrPFtyGWJ2NSfBiyP", + "/dns/boot.metaspan.io/tcp/25069/wss/p2p/12D3KooWDoDLtLvQi8hhFVyubPZhaYuAwSAJrPFtyGWJ2NSfBiyP", + "/dns/ibp-boot-kusama-people.luckyfriday.io/tcp/30342/p2p/12D3KooWM4bRafMH2StfBEQtyj5cMWfGLYbuikCZmvKv9m1MQVPn", + "/dns/ibp-boot-kusama-people.luckyfriday.io/tcp/443/wss/p2p/12D3KooWM4bRafMH2StfBEQtyj5cMWfGLYbuikCZmvKv9m1MQVPn" ], "telemetryEndpoints": null, "protocolId": null, From 5055294521021c0ffa1c449d6793ec9d264e5bd5 Mon Sep 17 00:00:00 2001 From: Florian Franzen Date: Mon, 17 Jun 2024 20:47:36 +0200 Subject: [PATCH 7/9] node-inspect: do not depend on rocksdb (#4783) The crate `sc-cli` otherwise enables the `rocksdb` feature. --- substrate/bin/node/inspect/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/substrate/bin/node/inspect/Cargo.toml b/substrate/bin/node/inspect/Cargo.toml index 5e4488903bf45..e23a4c4f37e59 100644 --- a/substrate/bin/node/inspect/Cargo.toml +++ b/substrate/bin/node/inspect/Cargo.toml @@ -18,7 +18,7 @@ targets = ["x86_64-unknown-linux-gnu"] clap = { version = "4.5.3", features = ["derive"] } codec = { package = "parity-scale-codec", version = "3.6.12" } thiserror = { workspace = true } -sc-cli = { path = "../../../client/cli" } +sc-cli = { path = "../../../client/cli", default-features = false } sc-client-api = { path = "../../../client/api" } sc-service = { path = "../../../client/service", default-features = false } sp-blockchain = { path = "../../../primitives/blockchain" } From 55a13abcd2f67e7fdfc8843f5c4a54798e26a9df Mon Sep 17 00:00:00 2001 From: Kantapat chankasem Date: Tue, 18 Jun 2024 05:30:13 +0700 Subject: [PATCH 8/9] remove pallet::getter usage from pallet-timestamp (#3374) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit this pr is a part of #3326 --------- Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> Co-authored-by: Bastian Köcher --- cumulus/test/runtime/src/lib.rs | 4 ++-- polkadot/runtime/test-runtime/src/lib.rs | 3 ++- prdoc/pr_3374.prdoc | 13 +++++++++++++ .../test-staking-e2e/src/lib.rs | 5 +++-- substrate/frame/timestamp/src/benchmarking.rs | 4 ++-- substrate/frame/timestamp/src/lib.rs | 13 ++++++------- substrate/frame/timestamp/src/tests.rs | 2 +- 7 files changed, 29 insertions(+), 15 deletions(-) create mode 100644 prdoc/pr_3374.prdoc diff --git a/cumulus/test/runtime/src/lib.rs b/cumulus/test/runtime/src/lib.rs index 452b3241d0bfa..26c6635e1ad32 100644 --- a/cumulus/test/runtime/src/lib.rs +++ b/cumulus/test/runtime/src/lib.rs @@ -66,7 +66,7 @@ use frame_system::{ pub use pallet_balances::Call as BalancesCall; pub use pallet_glutton::Call as GluttonCall; pub use pallet_sudo::Call as SudoCall; -pub use pallet_timestamp::Call as TimestampCall; +pub use pallet_timestamp::{Call as TimestampCall, Now}; #[cfg(any(feature = "std", test))] pub use sp_runtime::BuildStorage; pub use sp_runtime::{Perbill, Permill}; @@ -499,7 +499,7 @@ impl_runtime_apis! { impl crate::GetLastTimestamp for Runtime { fn get_last_timestamp() -> u64 { - Timestamp::now() + Now::::get() } } diff --git a/polkadot/runtime/test-runtime/src/lib.rs b/polkadot/runtime/test-runtime/src/lib.rs index 8178639946f8d..334c6eb733a1d 100644 --- a/polkadot/runtime/test-runtime/src/lib.rs +++ b/polkadot/runtime/test-runtime/src/lib.rs @@ -53,6 +53,7 @@ use frame_support::{ }; use pallet_grandpa::{fg_primitives, AuthorityId as GrandpaId}; use pallet_session::historical as session_historical; +use pallet_timestamp::Now; use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo}; use polkadot_primitives::{ slashing, AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CandidateHash, @@ -1186,7 +1187,7 @@ sp_api::impl_runtime_apis! { impl crate::GetLastTimestamp for Runtime { fn get_last_timestamp() -> u64 { - Timestamp::now() + Now::::get() } } diff --git a/prdoc/pr_3374.prdoc b/prdoc/pr_3374.prdoc new file mode 100644 index 0000000000000..76744f778db0a --- /dev/null +++ b/prdoc/pr_3374.prdoc @@ -0,0 +1,13 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: removed `pallet::getter` from `pallet-timestamp` + +doc: + - audience: Runtime Dev + description: | + This PR removes all the `pallet::getter` usages from `pallet-timestamp`, and updates depdendant runtimes accordingly. + The syntax `StorageItem::::get()` should be used instead. + +crates: + - name: pallet-timestamp \ No newline at end of file diff --git a/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/lib.rs b/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/lib.rs index 2b1f1335c6fe8..aaffbb6681cd2 100644 --- a/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/lib.rs +++ b/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/lib.rs @@ -22,6 +22,7 @@ pub(crate) const LOG_TARGET: &str = "tests::e2e-epm"; use frame_support::{assert_err, assert_noop, assert_ok}; use mock::*; +use pallet_timestamp::Now; use sp_core::Get; use sp_runtime::Perbill; @@ -46,7 +47,7 @@ fn log_current_time() { Session::current_index(), Staking::current_era(), ElectionProviderMultiPhase::current_phase(), - Timestamp::now() + Now::::get() ); } @@ -209,7 +210,7 @@ fn continuous_slashes_below_offending_threshold() { // failed due to election minimum score. if start_next_active_era(pool_state.clone()).is_err() { assert!(ElectionProviderMultiPhase::current_phase().is_emergency()); - break + break; } active_validator_set = Session::validators(); diff --git a/substrate/frame/timestamp/src/benchmarking.rs b/substrate/frame/timestamp/src/benchmarking.rs index 82dfdfa8b3120..d8c27b4967af9 100644 --- a/substrate/frame/timestamp/src/benchmarking.rs +++ b/substrate/frame/timestamp/src/benchmarking.rs @@ -25,7 +25,7 @@ use frame_support::{ensure, traits::OnFinalize}; use frame_system::RawOrigin; use sp_storage::TrackedStorageKey; -use crate::Pallet as Timestamp; +use crate::{Now, Pallet as Timestamp}; const MAX_TIME: u32 = 100; @@ -42,7 +42,7 @@ benchmarks! { }); }: _(RawOrigin::None, t.into()) verify { - ensure!(Timestamp::::now() == t.into(), "Time was not set."); + ensure!(Now::::get() == t.into(), "Time was not set."); } on_finalize { diff --git a/substrate/frame/timestamp/src/lib.rs b/substrate/frame/timestamp/src/lib.rs index 5269f17eca6b2..6a22ab1cd5ef8 100644 --- a/substrate/frame/timestamp/src/lib.rs +++ b/substrate/frame/timestamp/src/lib.rs @@ -202,7 +202,6 @@ pub mod pallet { /// The current time for the current block. #[pallet::storage] - #[pallet::getter(fn now)] pub type Now = StorageValue<_, T::Moment, ValueQuery>; /// Whether the timestamp has been updated in this block. @@ -261,7 +260,7 @@ pub mod pallet { pub fn set(origin: OriginFor, #[pallet::compact] now: T::Moment) -> DispatchResult { ensure_none(origin)?; assert!(!DidUpdate::::exists(), "Timestamp must be updated only once in the block"); - let prev = Self::now(); + let prev = Now::::get(); assert!( prev.is_zero() || now >= prev + T::MinimumPeriod::get(), "Timestamp must increment by at least between sequential blocks" @@ -296,7 +295,7 @@ pub mod pallet { .expect("Timestamp inherent data must be provided"); let data = (*inherent_data).saturated_into::(); - let next_time = cmp::max(data, Self::now() + T::MinimumPeriod::get()); + let next_time = cmp::max(data, Now::::get() + T::MinimumPeriod::get()); Some(Call::set { now: next_time }) } @@ -317,7 +316,7 @@ pub mod pallet { .expect("Timestamp inherent data not correctly encoded") .expect("Timestamp inherent data must be provided"); - let minimum = (Self::now() + T::MinimumPeriod::get()).saturated_into::(); + let minimum = (Now::::get() + T::MinimumPeriod::get()).saturated_into::(); if t > *(data + MAX_TIMESTAMP_DRIFT_MILLIS) { Err(InherentError::TooFarInFuture) } else if t < minimum { @@ -339,7 +338,7 @@ impl Pallet { /// NOTE: if this function is called prior to setting the timestamp, /// it will return the timestamp of the previous block. pub fn get() -> T::Moment { - Self::now() + Now::::get() } /// Set the timestamp to something in particular. Only used for tests. @@ -356,7 +355,7 @@ impl Time for Pallet { type Moment = T::Moment; fn now() -> Self::Moment { - Self::now() + Now::::get() } } @@ -367,7 +366,7 @@ impl UnixTime for Pallet { fn now() -> core::time::Duration { // now is duration since unix epoch in millisecond as documented in // `sp_timestamp::InherentDataProvider`. - let now = Self::now(); + let now = Now::::get(); sp_std::if_std! { if now == T::Moment::zero() { log::error!( diff --git a/substrate/frame/timestamp/src/tests.rs b/substrate/frame/timestamp/src/tests.rs index cc49d8a3296e8..a83855561889f 100644 --- a/substrate/frame/timestamp/src/tests.rs +++ b/substrate/frame/timestamp/src/tests.rs @@ -25,7 +25,7 @@ fn timestamp_works() { new_test_ext().execute_with(|| { crate::Now::::put(46); assert_ok!(Timestamp::set(RuntimeOrigin::none(), 69)); - assert_eq!(Timestamp::now(), 69); + assert_eq!(crate::Now::::get(), 69); assert_eq!(Some(69), get_captured_moment()); }); } From 7c847f8db6ab9ca9ef990c4cf61275415c78d106 Mon Sep 17 00:00:00 2001 From: Daan van der Plas <93204684+Daanvdplas@users.noreply.github.com> Date: Tue, 18 Jun 2024 09:51:47 +0200 Subject: [PATCH 9/9] refactor: parachain template (#4684) Update parachain template pallet based on polkadot sdk docs @kianenigma --------- Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- prdoc/pr_4684.prdoc | 13 +++ .../parachain/pallets/template/src/lib.rs | 42 ++++--- .../parachain/pallets/template/src/mock.rs | 45 +++++--- .../parachain/pallets/template/src/weights.rs | 2 +- templates/parachain/runtime/Cargo.toml | 2 +- templates/parachain/runtime/src/lib.rs | 107 +++++++++++------- 6 files changed, 133 insertions(+), 78 deletions(-) create mode 100644 prdoc/pr_4684.prdoc diff --git a/prdoc/pr_4684.prdoc b/prdoc/pr_4684.prdoc new file mode 100644 index 0000000000000..b1c429c578224 --- /dev/null +++ b/prdoc/pr_4684.prdoc @@ -0,0 +1,13 @@ +title: "Refactor of the parachain template" + +doc: + - audience: Runtime Dev + description: | + Introduce the construct runtime V2 to the parachain template runtime. In addition, url links in the parachain pallet + template now direct to the polkadot sdk docs. + +crates: + - name: pallet-parachain-template + bump: none + - name: parachain-template-runtime + bump: none diff --git a/templates/parachain/pallets/template/src/lib.rs b/templates/parachain/pallets/template/src/lib.rs index 11587d1df426f..0420e2b908215 100644 --- a/templates/parachain/pallets/template/src/lib.rs +++ b/templates/parachain/pallets/template/src/lib.rs @@ -1,8 +1,5 @@ #![cfg_attr(not(feature = "std"), no_std)] -/// Edit this file to define custom logic or remove it if it is not needed. -/// Learn more about FRAME and the core library of Substrate FRAME pallets: -/// pub use pallet::*; #[cfg(test)] @@ -16,6 +13,12 @@ pub mod weights; #[cfg(feature = "runtime-benchmarks")] mod benchmarking; +// +// +// +// To see a full list of `pallet` macros and their use cases, see: +// +// #[frame_support::pallet] pub mod pallet { use frame_support::{dispatch::DispatchResultWithPostInfo, pallet_prelude::*}; @@ -25,7 +28,9 @@ pub mod pallet { #[pallet::config] pub trait Config: frame_system::Config { /// Because this pallet emits events, it depends on the runtime's definition of an event. + /// type RuntimeEvent: From> + IsType<::RuntimeEvent>; + /// A type representing the weights required by the dispatchables of this pallet. type WeightInfo: crate::weights::WeightInfo; } @@ -33,24 +38,23 @@ pub mod pallet { #[pallet::pallet] pub struct Pallet(_); - // The pallet's runtime storage items. - // https://docs.substrate.io/v3/runtime/storage + /// The pallet's storage items. + /// + /// #[pallet::storage] - // Learn more about declaring storage items: - // https://docs.substrate.io/v3/runtime/storage#declaring-storage-items pub type Something = StorageValue<_, u32>; - // Pallets use events to inform users when important changes are made. - // https://docs.substrate.io/v3/runtime/events-and-errors + /// Pallets use events to inform users when important changes are made. + /// #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { - /// Event documentation should end with an array that provides descriptive names for event - /// parameters. [something, who] - SomethingStored(u32, T::AccountId), + /// We usually use passive tense for events. + SomethingStored { something: u32, who: T::AccountId }, } - // Errors inform users that something went wrong. + /// Errors inform users that something went wrong. + /// #[pallet::error] pub enum Error { /// Error names should be descriptive. @@ -62,9 +66,10 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet {} - // Dispatchable functions allows users to interact with the pallet and invoke state changes. - // These functions materialize as "extrinsics", which are often compared to transactions. - // Dispatchable functions must be annotated with a weight and must return a DispatchResult. + /// Dispatchable functions allows users to interact with the pallet and invoke state changes. + /// These functions materialize as "extrinsics", which are often compared to transactions. + /// Dispatchable functions must be annotated with a weight and must return a DispatchResult. + /// #[pallet::call] impl Pallet { /// An example dispatchable that takes a singles value as a parameter, writes the value to @@ -74,14 +79,15 @@ pub mod pallet { pub fn do_something(origin: OriginFor, something: u32) -> DispatchResultWithPostInfo { // Check that the extrinsic was signed and get the signer. // This function will return an error if the extrinsic is not signed. - // https://docs.substrate.io/v3/runtime/origins + // let who = ensure_signed(origin)?; // Update storage. >::put(something); // Emit an event. - Self::deposit_event(Event::SomethingStored(something, who)); + Self::deposit_event(Event::SomethingStored { something, who }); + // Return a successful DispatchResultWithPostInfo Ok(().into()) } diff --git a/templates/parachain/pallets/template/src/mock.rs b/templates/parachain/pallets/template/src/mock.rs index ebb0598df97bf..46e3117596f59 100644 --- a/templates/parachain/pallets/template/src/mock.rs +++ b/templates/parachain/pallets/template/src/mock.rs @@ -1,25 +1,36 @@ -use frame_support::{derive_impl, parameter_types}; -use frame_system as system; -use sp_runtime::BuildStorage; - -type Block = frame_system::mocking::MockBlock; +use frame_support::{derive_impl, weights::constants::RocksDbWeight}; +use frame_system::{mocking::MockBlock, GenesisConfig}; +use sp_runtime::{traits::ConstU64, BuildStorage}; // Configure a mock runtime to test the pallet. -frame_support::construct_runtime!( - pub enum Test - { - System: frame_system::{Pallet, Call, Config, Storage, Event}, - TemplateModule: crate::{Pallet, Call, Storage, Event}, - } -); +#[frame_support::runtime] +mod test_runtime { + #[runtime::runtime] + #[runtime::derive( + RuntimeCall, + RuntimeEvent, + RuntimeError, + RuntimeOrigin, + RuntimeFreezeReason, + RuntimeHoldReason, + RuntimeSlashReason, + RuntimeLockId, + RuntimeTask + )] + pub struct Test; -parameter_types! { - pub const SS58Prefix: u8 = 42; + #[runtime::pallet_index(0)] + pub type System = frame_system; + #[runtime::pallet_index(1)] + pub type TemplateModule = crate; } #[derive_impl(frame_system::config_preludes::TestDefaultConfig)] -impl system::Config for Test { - type Block = Block; +impl frame_system::Config for Test { + type Nonce = u64; + type Block = MockBlock; + type BlockHashCount = ConstU64<250>; + type DbWeight = RocksDbWeight; } impl crate::Config for Test { @@ -29,5 +40,5 @@ impl crate::Config for Test { // Build genesis storage according to the mock runtime. pub fn new_test_ext() -> sp_io::TestExternalities { - system::GenesisConfig::::default().build_storage().unwrap().into() + GenesisConfig::::default().build_storage().unwrap().into() } diff --git a/templates/parachain/pallets/template/src/weights.rs b/templates/parachain/pallets/template/src/weights.rs index 7c42936e09f29..5bfe28e8b71e3 100644 --- a/templates/parachain/pallets/template/src/weights.rs +++ b/templates/parachain/pallets/template/src/weights.rs @@ -4,7 +4,7 @@ //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev //! DATE: 2023-04-06, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `Alexs-MacBook-Pro-2.local`, CPU: `` +//! HOSTNAME: `_`, CPU: `` //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: diff --git a/templates/parachain/runtime/Cargo.toml b/templates/parachain/runtime/Cargo.toml index 059c793679694..48d9f69128949 100644 --- a/templates/parachain/runtime/Cargo.toml +++ b/templates/parachain/runtime/Cargo.toml @@ -35,7 +35,7 @@ pallet-parachain-template = { path = "../pallets/template", default-features = f frame-benchmarking = { path = "../../../substrate/frame/benchmarking", default-features = false, optional = true } frame-executive = { path = "../../../substrate/frame/executive", default-features = false } frame-metadata-hash-extension = { path = "../../../substrate/frame/metadata-hash-extension", default-features = false } -frame-support = { path = "../../../substrate/frame/support", default-features = false } +frame-support = { path = "../../../substrate/frame/support", default-features = false, features = ["experimental"] } frame-system = { path = "../../../substrate/frame/system", default-features = false } frame-system-benchmarking = { path = "../../../substrate/frame/system/benchmarking", default-features = false, optional = true } frame-system-rpc-runtime-api = { path = "../../../substrate/frame/system/rpc/runtime-api", default-features = false } diff --git a/templates/parachain/runtime/src/lib.rs b/templates/parachain/runtime/src/lib.rs index 987b88af8444d..6e6491a19adf6 100644 --- a/templates/parachain/runtime/src/lib.rs +++ b/templates/parachain/runtime/src/lib.rs @@ -7,6 +7,8 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); pub mod apis; +#[cfg(feature = "runtime-benchmarks")] +mod benchmarks; mod configs; mod weights; @@ -22,12 +24,9 @@ use sp_std::prelude::*; use sp_version::NativeVersion; use sp_version::RuntimeVersion; -use frame_support::{ - construct_runtime, - weights::{ - constants::WEIGHT_REF_TIME_PER_SECOND, Weight, WeightToFeeCoefficient, - WeightToFeeCoefficients, WeightToFeePolynomial, - }, +use frame_support::weights::{ + constants::WEIGHT_REF_TIME_PER_SECOND, Weight, WeightToFeeCoefficient, WeightToFeeCoefficients, + WeightToFeePolynomial, }; pub use sp_consensus_aura::sr25519::AuthorityId as AuraId; pub use sp_runtime::{MultiAddress, Perbill, Permill}; @@ -232,43 +231,69 @@ pub fn native_version() -> NativeVersion { } // Create the runtime by composing the FRAME pallets that were previously configured. -construct_runtime!( - pub enum Runtime { - // System support stuff. - System: frame_system = 0, - ParachainSystem: cumulus_pallet_parachain_system = 1, - Timestamp: pallet_timestamp = 2, - ParachainInfo: parachain_info = 3, - - // Monetary stuff. - Balances: pallet_balances = 10, - TransactionPayment: pallet_transaction_payment = 11, - - // Governance - Sudo: pallet_sudo = 15, - - // Collator support. The order of these 4 are important and shall not change. - Authorship: pallet_authorship = 20, - CollatorSelection: pallet_collator_selection = 21, - Session: pallet_session = 22, - Aura: pallet_aura = 23, - AuraExt: cumulus_pallet_aura_ext = 24, - - // XCM helpers. - XcmpQueue: cumulus_pallet_xcmp_queue = 30, - PolkadotXcm: pallet_xcm = 31, - CumulusXcm: cumulus_pallet_xcm = 32, - MessageQueue: pallet_message_queue = 33, - - // Template - TemplatePallet: pallet_parachain_template = 50, - } -); +#[frame_support::runtime] +mod runtime { + #[runtime::runtime] + #[runtime::derive( + RuntimeCall, + RuntimeEvent, + RuntimeError, + RuntimeOrigin, + RuntimeFreezeReason, + RuntimeHoldReason, + RuntimeSlashReason, + RuntimeLockId, + RuntimeTask + )] + pub struct Runtime; + + #[runtime::pallet_index(0)] + pub type System = frame_system; + #[runtime::pallet_index(1)] + pub type ParachainSystem = cumulus_pallet_parachain_system; + #[runtime::pallet_index(2)] + pub type Timestamp = pallet_timestamp; + #[runtime::pallet_index(3)] + pub type ParachainInfo = parachain_info; + + // Monetary stuff. + #[runtime::pallet_index(10)] + pub type Balances = pallet_balances; + #[runtime::pallet_index(11)] + pub type TransactionPayment = pallet_transaction_payment; + + // Governance + #[runtime::pallet_index(15)] + pub type Sudo = pallet_sudo; + + // Collator support. The order of these 4 are important and shall not change. + #[runtime::pallet_index(20)] + pub type Authorship = pallet_authorship; + #[runtime::pallet_index(21)] + pub type CollatorSelection = pallet_collator_selection; + #[runtime::pallet_index(22)] + pub type Session = pallet_session; + #[runtime::pallet_index(23)] + pub type Aura = pallet_aura; + #[runtime::pallet_index(24)] + pub type AuraExt = cumulus_pallet_aura_ext; + + // XCM helpers. + #[runtime::pallet_index(30)] + pub type XcmpQueue = cumulus_pallet_xcmp_queue; + #[runtime::pallet_index(31)] + pub type PolkadotXcm = pallet_xcm; + #[runtime::pallet_index(32)] + pub type CumulusXcm = cumulus_pallet_xcm; + #[runtime::pallet_index(33)] + pub type MessageQueue = pallet_message_queue; + + // Template + #[runtime::pallet_index(50)] + pub type TemplatePallet = pallet_parachain_template; +} cumulus_pallet_parachain_system::register_validate_block! { Runtime = Runtime, BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::, } - -#[cfg(feature = "runtime-benchmarks")] -mod benchmarks;