Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added a storage migration for global params #30

Merged
merged 5 commits into from
Mar 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 0 additions & 21 deletions node/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,27 +194,6 @@ pub fn run() -> sc_cli::Result<()> {
}
})
}
#[cfg(feature = "try-runtime")]
Some(Subcommand::TryRuntime(cmd)) => {
use crate::service::ExecutorDispatch;
use sc_executor::{sp_wasm_interface::ExtendedHostFunctions, NativeExecutionDispatch};
let runner = cli.create_runner(cmd)?;
runner.async_run(|config| {
// we don't need any of the components of new_partial, just a runtime, or a task
// manager to do `async_run`.
let registry = config.prometheus_config.as_ref().map(|cfg| &cfg.registry);
let task_manager =
sc_service::TaskManager::new(config.tokio_handle.clone(), registry)
.map_err(|e| sc_cli::Error::Service(sc_service::Error::Prometheus(e)))?;
Ok((
cmd.run::<Block, ExtendedHostFunctions<
sp_io::SubstrateHostFunctions,
<ExecutorDispatch as NativeExecutionDispatch>::ExtendHostFunctions,
>>(),
task_manager,
))
})
}
Some(Subcommand::TryRuntime) => {
Err("TryRuntime is available through its own CLI now: <https://github.com/paritytech/try-runtime-cli>".into())
}
Expand Down
5 changes: 4 additions & 1 deletion pallets/subspace/src/global.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,10 @@ impl<T: Config> Pallet<T> {
// check if the name already exists
ensure!(params.max_name_length > 0, Error::<T>::InvalidMaxNameLength);

ensure!(params.min_delegation_fee.deconstruct() <= 100, Error::<T>::InvalidMinDelegationFee);
ensure!(
params.min_delegation_fee.deconstruct() <= 100,
Error::<T>::InvalidMinDelegationFee
);

ensure!(
params.max_allowed_subnets > 0,
Expand Down
26 changes: 19 additions & 7 deletions pallets/subspace/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
use frame_system::{self as system, ensure_signed};
pub use pallet::*;

// export the migrations here
pub mod migrations;

use frame_support::{
dispatch,
dispatch::{DispatchInfo, PostDispatchInfo},
Expand Down Expand Up @@ -63,8 +66,11 @@ pub mod pallet {
use sp_arithmetic::per_things::Percent;
pub use sp_std::{vec, vec::Vec};

const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);

#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
#[pallet::storage_version(STORAGE_VERSION)]
#[pallet::without_storage_info]
pub struct Pallet<T>(_);

Expand Down Expand Up @@ -242,8 +248,9 @@ pub mod pallet {
Percent::from_percent(5u8)
}

#[pallet::storage]
pub type MinDelegationFeeGlobal<T> = StorageValue<_, Percent, ValueQuery, DefaultMinDelegationFeeGlobal<T>>;
#[pallet::storage]
pub type MinDelegationFeeGlobal<T> =
StorageValue<_, Percent, ValueQuery, DefaultMinDelegationFeeGlobal<T>>;

#[pallet::type_value]
pub fn DefaultMinWeightStake<T: Config>() -> u64 {
Expand Down Expand Up @@ -282,11 +289,11 @@ pub mod pallet {
pub max_proposals: u64, // max number of proposals per block

// mins
pub min_burn: u64, // min burn required
pub max_burn: u64, // max burn allowed
pub min_stake: u64, // min stake required
pub min_burn: u64, // min burn required
pub max_burn: u64, // max burn allowed
pub min_stake: u64, // min stake required
pub min_delegation_fee: Percent, // min delegation fee
pub min_weight_stake: u64, // min weight stake required
pub min_weight_stake: u64, // min weight stake required

// other
pub target_registrations_per_interval: u16, // desired number of registrations per interval
Expand Down Expand Up @@ -1073,6 +1080,10 @@ pub mod pallet {
// # Args:
// * 'n': (T::BlockNumber):
// - The number of the block we are initializing.
// fn on_runtime_upgrade() -> frame_support::weights::Weight {
// migration::on_runtime_upgrade::<T>()
// }

fn on_initialize(_block_number: BlockNumberFor<T>) -> Weight {
Self::block_step();

Expand Down Expand Up @@ -1170,7 +1181,8 @@ pub mod pallet {
params.name = name;
params.address = address;
if let Some(delegation_fee) = delegation_fee {
ensure!(delegation_fee >= Self::get_min_deleg_fee_global(),
ensure!(
delegation_fee >= Self::get_min_deleg_fee_global(),
Error::<T>::InvalidMinDelegationFee
);
params.delegation_fee = delegation_fee;
Expand Down
88 changes: 88 additions & 0 deletions pallets/subspace/src/migrations.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
use super::*;

use frame_support::{
codec::{Decode, Encode},
pallet_prelude::StorageValue,
traits::{Get, OnRuntimeUpgrade, StorageInstance, StorageVersion},
weights::Weight,
};
use scale_info::TypeInfo;

#[derive(Decode, Encode, TypeInfo, Default)]
pub struct OldGlobalParams {
pub burn_rate: u16,
pub max_name_length: u16,
pub max_allowed_subnets: u16,
pub max_allowed_modules: u16,
pub max_registrations_per_block: u16,
pub max_allowed_weights: u16,
pub max_proposals: u64,
pub min_burn: u64,
pub min_stake: u64,
pub min_weight_stake: u64,
pub unit_emission: u64,
pub tx_rate_limit: u64,
pub vote_threshold: u16,
pub vote_mode: Vec<u8>,
}

impl<T: Config> StorageInstance for Pallet<T> {
fn pallet_prefix() -> &'static str {
"Subspace"
}

const STORAGE_PREFIX: &'static str = "Subspace";
}

pub mod v1 {
use super::*;

pub struct MigrateToV1<T>(sp_std::marker::PhantomData<T>);

impl<T: Config> OnRuntimeUpgrade for MigrateToV1<T> {
fn on_runtime_upgrade() -> Weight {
let on_chain_version = StorageVersion::get::<Pallet<T>>();

// Migrate GlobalParams to v1
if on_chain_version == 0 {
let encoded =
StorageValue::<Pallet<T>, OldGlobalParams>::get().unwrap_or_default().encode();
let old_global_params = OldGlobalParams::decode(&mut encoded.as_slice())
.expect("Decoding old global params failed");

let new_global_params = GlobalParams {
burn_rate: old_global_params.burn_rate,
max_name_length: old_global_params.max_name_length,
max_allowed_subnets: old_global_params.max_allowed_subnets,
max_allowed_modules: old_global_params.max_allowed_modules,
max_registrations_per_block: old_global_params.max_registrations_per_block,
max_allowed_weights: old_global_params.max_allowed_weights,
max_proposals: old_global_params.max_proposals,
min_burn: old_global_params.min_burn,
min_stake: old_global_params.min_stake,
min_weight_stake: old_global_params.min_weight_stake,
unit_emission: old_global_params.unit_emission,
tx_rate_limit: old_global_params.tx_rate_limit,
vote_threshold: old_global_params.vote_threshold,
vote_mode: old_global_params.vote_mode,
max_burn: DefaultMaxBurn::<T>::get(),
min_delegation_fee: DefaultMinDelegationFeeGlobal::<T>::get(),
target_registrations_per_interval:
DefaultTargetRegistrationsPerInterval::<T>::get(),
target_registrations_interval: DefaultTargetRegistrationsInterval::<T>::get(),
adjustment_alpha: DefaultAdjustmentAlpha::<T>::get(),
};

StorageValue::<Pallet<T>, GlobalParams>::put(&new_global_params);

Check failure on line 76 in pallets/subspace/src/migrations.rs

View workflow job for this annotation

GitHub Actions / check

the borrowed expression implements the required traits
StorageVersion::new(1).put::<Pallet<T>>();

log::info!("Migrated GlobalParams to v1");

T::DbWeight::get().writes(1)
} else {
log::info!("GlobalParams already updated");
Weight::zero()
}
}
}
}
2 changes: 1 addition & 1 deletion pallets/subspace/src/staking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ impl<T: Config> Pallet<T> {
pub fn get_delegation_fee(netuid: u16, module_key: &T::AccountId) -> Percent {
let min_deleg_fee_global = Self::get_min_deleg_fee_global();
let delegation_fee = DelegationFee::<T>::get(netuid, module_key);

delegation_fee.max(min_deleg_fee_global)
}

Expand Down
4 changes: 3 additions & 1 deletion runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ pub mod opaque {
}
}

pub type Migrations = (pallet_subspace::migrations::v1::MigrateToV1<Runtime>,);
// To learn more about runtime versioning, see:
// https://docs.substrate.io/main-docs/build/upgrade#runtime-versioning
#[sp_version::runtime_version]
Expand All @@ -134,7 +135,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion {
// `spec_version`, and `authoring_version` are the same between Wasm and native.
// This value is set to 100 to notify Polkadot-JS App (https://polkadot.js.org/apps) to use
// the compatible custom types.
spec_version: 102,
spec_version: 103,
impl_version: 1,
apis: RUNTIME_API_VERSIONS,
transaction_version: 1,
Expand Down Expand Up @@ -534,6 +535,7 @@ pub type Executive = frame_executive::Executive<
frame_system::ChainContext<Runtime>,
Runtime,
AllPalletsWithSystem,
Migrations,
>;

impl fp_self_contained::SelfContainedCall for RuntimeCall {
Expand Down
Loading