From 9637986afaffeae6579f78522eea41311da21289 Mon Sep 17 00:00:00 2001 From: Aliaksandr Tsurko Date: Fri, 17 Jan 2025 17:49:38 +0100 Subject: [PATCH 01/10] Fix try-runtime accounting invariants check --- pallets/subtensor/src/subnets/subnet.rs | 4 ++- pallets/subtensor/src/utils/try_state.rs | 34 ++++++++++++++-------- scripts/try-runtime-upgrade.sh | 37 ++++++++++++++++++++++++ 3 files changed, 62 insertions(+), 13 deletions(-) create mode 100755 scripts/try-runtime-upgrade.sh diff --git a/pallets/subtensor/src/subnets/subnet.rs b/pallets/subtensor/src/subnets/subnet.rs index 7b7de6aeb8..5554a477b7 100644 --- a/pallets/subtensor/src/subnets/subnet.rs +++ b/pallets/subtensor/src/subnets/subnet.rs @@ -2,6 +2,8 @@ use super::*; use frame_support::IterableStorageMap; use sp_core::Get; +pub(crate) const POOL_INITIAL_TAO: u64 = 100_000_000_000; + impl Pallet { /// Retrieves the unique identifier (UID) for the root network. /// @@ -234,7 +236,7 @@ impl Pallet { ); // Set subnet token symbol. // Put 100 TAO from lock into subnet TAO and produce numerically equal amount of Alpha - let mut pool_initial_tao = 100_000_000_000; + let mut pool_initial_tao = POOL_INITIAL_TAO; if pool_initial_tao > actual_tao_lock_amount { pool_initial_tao = actual_tao_lock_amount; } diff --git a/pallets/subtensor/src/utils/try_state.rs b/pallets/subtensor/src/utils/try_state.rs index 385a21bdd0..62c4aabd65 100644 --- a/pallets/subtensor/src/utils/try_state.rs +++ b/pallets/subtensor/src/utils/try_state.rs @@ -1,4 +1,6 @@ use super::*; +#[cfg(feature = "try-runtime")] +use super::subnets::subnet::POOL_INITIAL_TAO; impl Pallet { /// Checks if the accounting invariants for [`TotalStake`], [`TotalSubnetLocked`], and [`TotalIssuance`] are correct. @@ -16,10 +18,16 @@ impl Pallet { use frame_support::traits::fungible::Inspect; // Calculate the total staked amount - let mut total_staked: u64 = 0; - for (_hotkey, _coldkey, stake) in Stake::::iter() { - total_staked = total_staked.saturating_add(stake); - } + let total_staked = SubnetTAO::::iter().fold(0u64, |acc, (netuid, stake)| { + let acc = acc.saturating_add(stake); + + if netuid == Self::get_root_netuid() { + // root network doesn't have initial pool TAO + acc + } else { + acc.saturating_sub(POOL_INITIAL_TAO) + } + }); // Verify that the calculated total stake matches the stored TotalStake ensure!( @@ -28,13 +36,13 @@ impl Pallet { ); // Get the total subnet locked amount - let total_subnet_locked: u64 = Self::get_total_subnet_locked(); + let total_subnet_locked = Self::get_total_subnet_locked(); // Get the total currency issuance - let currency_issuance: u64 = T::Currency::total_issuance(); + let currency_issuance = T::Currency::total_issuance(); // Calculate the expected total issuance - let expected_total_issuance: u64 = currency_issuance + let expected_total_issuance = currency_issuance .saturating_add(total_staked) .saturating_add(total_subnet_locked); @@ -42,15 +50,17 @@ impl Pallet { // // These values can be off slightly due to float rounding errors. // They are corrected every runtime upgrade. - const DELTA: u64 = 1000; - let diff = if TotalIssuance::::get() > expected_total_issuance { - TotalIssuance::::get().checked_sub(expected_total_issuance) + let delta = 1000; + let total_issuance = TotalIssuance::::get(); + + let diff = if total_issuance > expected_total_issuance { + total_issuance.checked_sub(expected_total_issuance) } else { - expected_total_issuance.checked_sub(TotalIssuance::::get()) + expected_total_issuance.checked_sub(total_issuance) } .expect("LHS > RHS"); ensure!( - diff <= DELTA, + diff <= delta, "TotalIssuance diff greater than allowable delta", ); diff --git a/scripts/try-runtime-upgrade.sh b/scripts/try-runtime-upgrade.sh new file mode 100755 index 0000000000..7c3e5fe77d --- /dev/null +++ b/scripts/try-runtime-upgrade.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash + +# Tries runtime upgrade (via try-runtime). +# +# Usage: +# try-runtime-upgrade.sh [-p ] [-u ] +# +# Dependencies: +# - rust toolchain +# - try-runtime-cli + +set -eou pipefail + +runtime_wasm_path="./target/release/wbuild/node-subtensor-runtime/node_subtensor_runtime.compact.wasm" +live_chain_url="wss://dev.chain.opentensor.ai:443" + +parse_args() { + while getopts "p:u:" opt; do + case "${opt}" in + p) runtime_wasm_path="${OPTARG}" ;; + u) live_chain_url="${OPTARG}" ;; + *) echo "Usage: $(basename "$0") [-p ] [-u ]" && exit 1 ;; + esac + done +} + +build_runtime() { + cargo build -p node-subtensor-runtime --release --features "metadata-hash,try-runtime" +} + +do_try_runtime() { + try-runtime --runtime "$runtime_wasm_path" on-runtime-upgrade live --uri "$live_chain_url" +} + +parse_args "$@" +build_runtime +do_try_runtime From 9df0d130664c986f844cbfff195ce8ace492188f Mon Sep 17 00:00:00 2001 From: Aliaksandr Tsurko Date: Fri, 17 Jan 2025 18:11:24 +0100 Subject: [PATCH 02/10] Reformat --- pallets/subtensor/src/utils/try_state.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/subtensor/src/utils/try_state.rs b/pallets/subtensor/src/utils/try_state.rs index 62c4aabd65..46a3ba5e4c 100644 --- a/pallets/subtensor/src/utils/try_state.rs +++ b/pallets/subtensor/src/utils/try_state.rs @@ -1,6 +1,6 @@ -use super::*; #[cfg(feature = "try-runtime")] use super::subnets::subnet::POOL_INITIAL_TAO; +use super::*; impl Pallet { /// Checks if the accounting invariants for [`TotalStake`], [`TotalSubnetLocked`], and [`TotalIssuance`] are correct. From 92a476e478803309a883d827d6318fed62101859 Mon Sep 17 00:00:00 2001 From: Aliaksandr Tsurko Date: Fri, 17 Jan 2025 22:14:15 +0100 Subject: [PATCH 03/10] Change subnet initial supply fallback value --- pallets/subtensor/src/subnets/subnet.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/pallets/subtensor/src/subnets/subnet.rs b/pallets/subtensor/src/subnets/subnet.rs index 5554a477b7..050514c4cc 100644 --- a/pallets/subtensor/src/subnets/subnet.rs +++ b/pallets/subtensor/src/subnets/subnet.rs @@ -3,6 +3,7 @@ use frame_support::IterableStorageMap; use sp_core::Get; pub(crate) const POOL_INITIAL_TAO: u64 = 100_000_000_000; +pub(crate) const POOL_INITIAL_TAO_FALLBACK: u64 = 500; impl Pallet { /// Retrieves the unique identifier (UID) for the root network. @@ -240,8 +241,8 @@ impl Pallet { if pool_initial_tao > actual_tao_lock_amount { pool_initial_tao = actual_tao_lock_amount; } - if pool_initial_tao < 1 { - pool_initial_tao = 1; + if pool_initial_tao == 0 { + pool_initial_tao = POOL_INITIAL_TAO_FALLBACK; } let actual_tao_lock_amount_less_pool_tao = actual_tao_lock_amount.saturating_sub(pool_initial_tao); From 05b5c6b56389b58290280427d60925824554580a Mon Sep 17 00:00:00 2001 From: Aliaksandr Tsurko Date: Thu, 23 Jan 2025 19:38:54 +0100 Subject: [PATCH 04/10] Disable TotalStake check in try-runtime --- pallets/subtensor/src/utils/try_state.rs | 34 +++++++++++++----------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/pallets/subtensor/src/utils/try_state.rs b/pallets/subtensor/src/utils/try_state.rs index 46a3ba5e4c..c42e75dfe7 100644 --- a/pallets/subtensor/src/utils/try_state.rs +++ b/pallets/subtensor/src/utils/try_state.rs @@ -17,23 +17,25 @@ impl Pallet { pub fn check_accounting_invariants() -> Result<(), sp_runtime::TryRuntimeError> { use frame_support::traits::fungible::Inspect; - // Calculate the total staked amount - let total_staked = SubnetTAO::::iter().fold(0u64, |acc, (netuid, stake)| { - let acc = acc.saturating_add(stake); + // Disabled: https://github.com/opentensor/subtensor/pull/1166 + // + // // Calculate the total staked amount + // let total_staked = SubnetTAO::::iter().fold(0u64, |acc, (netuid, stake)| { + // let acc = acc.saturating_add(stake); - if netuid == Self::get_root_netuid() { - // root network doesn't have initial pool TAO - acc - } else { - acc.saturating_sub(POOL_INITIAL_TAO) - } - }); + // if netuid == Self::get_root_netuid() { + // // root network doesn't have initial pool TAO + // acc + // } else { + // acc.saturating_sub(POOL_INITIAL_TAO) + // } + // }); - // Verify that the calculated total stake matches the stored TotalStake - ensure!( - total_staked == TotalStake::::get(), - "TotalStake does not match total staked", - ); + // // Verify that the calculated total stake matches the stored TotalStake + // ensure!( + // total_staked == TotalStake::::get(), + // "TotalStake does not match total staked", + // ); // Get the total subnet locked amount let total_subnet_locked = Self::get_total_subnet_locked(); @@ -43,7 +45,7 @@ impl Pallet { // Calculate the expected total issuance let expected_total_issuance = currency_issuance - .saturating_add(total_staked) + .saturating_add(TotalStake::::get()) .saturating_add(total_subnet_locked); // Verify the diff between calculated TI and actual TI is less than delta From 4163b91aae39940215fb75e2aded504b498466c3 Mon Sep 17 00:00:00 2001 From: Aliaksandr Tsurko Date: Thu, 23 Jan 2025 19:43:57 +0100 Subject: [PATCH 05/10] Reformat --- pallets/subtensor/src/utils/try_state.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/pallets/subtensor/src/utils/try_state.rs b/pallets/subtensor/src/utils/try_state.rs index c42e75dfe7..c2292eeeee 100644 --- a/pallets/subtensor/src/utils/try_state.rs +++ b/pallets/subtensor/src/utils/try_state.rs @@ -1,5 +1,3 @@ -#[cfg(feature = "try-runtime")] -use super::subnets::subnet::POOL_INITIAL_TAO; use super::*; impl Pallet { @@ -17,8 +15,8 @@ impl Pallet { pub fn check_accounting_invariants() -> Result<(), sp_runtime::TryRuntimeError> { use frame_support::traits::fungible::Inspect; - // Disabled: https://github.com/opentensor/subtensor/pull/1166 - // + // Disabled: https://github.com/opentensor/subtensor/pull/1166 + // // // Calculate the total staked amount // let total_staked = SubnetTAO::::iter().fold(0u64, |acc, (netuid, stake)| { // let acc = acc.saturating_add(stake); From 06ba8e57fccdc9b4e152711e355026d317349ee4 Mon Sep 17 00:00:00 2001 From: Aliaksandr Tsurko Date: Wed, 29 Jan 2025 14:50:06 +0100 Subject: [PATCH 06/10] Add an option to run try-runtime script with a snapshot --- scripts/try-runtime-upgrade.sh | 33 +++++++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/scripts/try-runtime-upgrade.sh b/scripts/try-runtime-upgrade.sh index 7c3e5fe77d..80495bcb1d 100755 --- a/scripts/try-runtime-upgrade.sh +++ b/scripts/try-runtime-upgrade.sh @@ -3,7 +3,7 @@ # Tries runtime upgrade (via try-runtime). # # Usage: -# try-runtime-upgrade.sh [-p ] [-u ] +# try-runtime-upgrade.sh [-p ] [-u ] [-s ] # # Dependencies: # - rust toolchain @@ -13,15 +13,28 @@ set -eou pipefail runtime_wasm_path="./target/release/wbuild/node-subtensor-runtime/node_subtensor_runtime.compact.wasm" live_chain_url="wss://dev.chain.opentensor.ai:443" +snapshot_path="" parse_args() { - while getopts "p:u:" opt; do + u_provided=false + + while getopts "r:u:s:" opt; do case "${opt}" in - p) runtime_wasm_path="${OPTARG}" ;; - u) live_chain_url="${OPTARG}" ;; - *) echo "Usage: $(basename "$0") [-p ] [-u ]" && exit 1 ;; + r) runtime_wasm_path="${OPTARG}" ;; + u) + live_chain_url="${OPTARG}" + u_provided=true + ;; + s) snapshot_path="${OPTARG}" ;; + *) echo "Usage: $(basename "$0") [-r ] [-u ] [-s ]" && exit 1 ;; esac done + + # Prevent specifying URI if snapshot is specified + if [ -n "$snapshot_path" ] && [ "$u_provided" = true ]; then + echo "Error: Either live URI or snapshot path should be specified, but not both." + exit 1 + fi } build_runtime() { @@ -29,7 +42,15 @@ build_runtime() { } do_try_runtime() { - try-runtime --runtime "$runtime_wasm_path" on-runtime-upgrade live --uri "$live_chain_url" + if [ -n "$snapshot_path" ]; then + chain_state="snap --path $snapshot_path" + else + chain_state="live --uri $live_chain_url" + fi + + eval "try-runtime --runtime $runtime_wasm_path on-runtime-upgrade \ + --no-weight-warnings --disable-spec-version-check --disable-idempotency-checks \ + $chain_state" } parse_args "$@" From 3678d4c2aee36a0984f552bb89694ef95e094428 Mon Sep 17 00:00:00 2001 From: Aliaksandr Tsurko Date: Wed, 29 Jan 2025 15:08:05 +0100 Subject: [PATCH 07/10] Update spec version --- runtime/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index 372c9a9815..2a2d2fac47 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -220,7 +220,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: 224, + spec_version: 225, impl_version: 1, apis: RUNTIME_API_VERSIONS, transaction_version: 1, From f8d5d4d7e2dfe8745e6445432c3877e976db059e Mon Sep 17 00:00:00 2001 From: Aliaksandr Tsurko Date: Thu, 30 Jan 2025 14:28:17 +0100 Subject: [PATCH 08/10] Fix rao migration did not update TotalIssuance --- .../migrations/migrate_init_total_issuance.rs | 77 ++++++++++--------- .../subtensor/src/migrations/migrate_rao.rs | 16 ++-- scripts/try-runtime-upgrade.sh | 2 +- 3 files changed, 52 insertions(+), 43 deletions(-) diff --git a/pallets/subtensor/src/migrations/migrate_init_total_issuance.rs b/pallets/subtensor/src/migrations/migrate_init_total_issuance.rs index a488771c5a..4501ccf6d5 100644 --- a/pallets/subtensor/src/migrations/migrate_init_total_issuance.rs +++ b/pallets/subtensor/src/migrations/migrate_init_total_issuance.rs @@ -1,6 +1,6 @@ use super::*; -use frame_support::pallet_prelude::OptionQuery; -use frame_support::{pallet_prelude::Identity, storage_alias}; +use frame_support::pallet_prelude::{Identity, OptionQuery, Weight}; +use frame_support::storage_alias; use sp_std::vec::Vec; // TODO: Implement comprehensive tests for this migration @@ -14,6 +14,43 @@ pub mod deprecated_loaded_emission_format { StorageMap, Identity, u16, Vec<(AccountIdOf, u64)>, OptionQuery>; } +pub(crate) fn migrate_init_total_issuance() -> Weight { + // Calculate the total locked tokens across all subnets + let subnets_len = crate::SubnetLocked::::iter().count() as u64; + let total_subnet_locked: u64 = + crate::SubnetLocked::::iter().fold(0, |acc, (_, v)| acc.saturating_add(v)); + + // Retrieve the total balance of all accounts + let total_account_balances = <::Currency as fungible::Inspect< + ::AccountId, + >>::total_issuance(); + + // Get the total stake from the system + let total_stake = crate::TotalStake::::get(); + + // Retrieve the previous total issuance for logging purposes + let prev_total_issuance = crate::TotalIssuance::::get(); + + // Calculate the new total issuance + let new_total_issuance = total_account_balances + .saturating_add(total_stake) + .saturating_add(total_subnet_locked); + + // Update the total issuance in storage + crate::TotalIssuance::::put(new_total_issuance); + + // Log the change in total issuance + log::info!( + "Subtensor Pallet Total Issuance Updated: previous: {:?}, new: {:?}", + prev_total_issuance, + new_total_issuance + ); + + // Return the weight of the operation + // We performed subnets_len + 5 reads and 1 write + ::DbWeight::get().reads_writes(subnets_len.saturating_add(5), 1) +} + pub mod initialise_total_issuance { use frame_support::pallet_prelude::Weight; use frame_support::traits::{fungible, OnRuntimeUpgrade}; @@ -33,41 +70,7 @@ pub mod initialise_total_issuance { /// /// Returns the weight of the migration operation. fn on_runtime_upgrade() -> Weight { - // Calculate the total locked tokens across all subnets - let subnets_len = crate::SubnetLocked::::iter().count() as u64; - let total_subnet_locked: u64 = - crate::SubnetLocked::::iter().fold(0, |acc, (_, v)| acc.saturating_add(v)); - - // Retrieve the total balance of all accounts - let total_account_balances = <::Currency as fungible::Inspect< - ::AccountId, - >>::total_issuance(); - - // Get the total stake from the system - let total_stake = crate::TotalStake::::get(); - - // Retrieve the previous total issuance for logging purposes - let prev_total_issuance = crate::TotalIssuance::::get(); - - // Calculate the new total issuance - let new_total_issuance = total_account_balances - .saturating_add(total_stake) - .saturating_add(total_subnet_locked); - - // Update the total issuance in storage - crate::TotalIssuance::::put(new_total_issuance); - - // Log the change in total issuance - log::info!( - "Subtensor Pallet Total Issuance Updated: previous: {:?}, new: {:?}", - prev_total_issuance, - new_total_issuance - ); - - // Return the weight of the operation - // We performed subnets_len + 5 reads and 1 write - ::DbWeight::get() - .reads_writes(subnets_len.saturating_add(5), 1) + super::migrate_init_total_issuance::() } /// Performs post-upgrade checks to ensure the migration was successful. diff --git a/pallets/subtensor/src/migrations/migrate_rao.rs b/pallets/subtensor/src/migrations/migrate_rao.rs index 3c034b7dad..136bd4c59a 100644 --- a/pallets/subtensor/src/migrations/migrate_rao.rs +++ b/pallets/subtensor/src/migrations/migrate_rao.rs @@ -1,11 +1,13 @@ -use super::*; use alloc::string::String; + use frame_support::IterableStorageMap; use frame_support::{traits::Get, weights::Weight}; -use log; use sp_runtime::format; use substrate_fixed::types::U64F64; +use super::*; +use crate::subnets::subnet::POOL_INITIAL_TAO; + pub fn migrate_rao() -> Weight { let migration_name = b"migrate_rao".to_vec(); @@ -69,12 +71,12 @@ pub fn migrate_rao() -> Weight { TokenSymbol::::insert(netuid, Pallet::::get_symbol_for_subnet(0)); continue; } - let owner: T::AccountId = SubnetOwner::::get(netuid); - let lock: u64 = SubnetLocked::::get(netuid); + let owner = SubnetOwner::::get(netuid); + let lock = SubnetLocked::::get(netuid); // Put initial TAO from lock into subnet TAO and produce numerically equal amount of Alpha // The initial TAO is the locked amount, with a minimum of 1 RAO and a cap of 100 TAO. - let pool_initial_tao = 100_000_000_000.min(lock.max(1)); + let pool_initial_tao = POOL_INITIAL_TAO.min(lock.max(1)); let remaining_lock = lock.saturating_sub(pool_initial_tao); // Refund the owner for the remaining lock. @@ -127,6 +129,10 @@ pub fn migrate_rao() -> Weight { // TargetStakesPerInterval::::put(10); (DEPRECATED) } + // update `TotalIssuance`, because currency issuance (`T::Currency`) has changed due to lock + // refunds above + weight = weight.saturating_add(migrate_init_total_issuance::migrate_init_total_issuance::()); + // Mark the migration as completed HasMigrationRun::::insert(&migration_name, true); weight = weight.saturating_add(T::DbWeight::get().writes(1)); diff --git a/scripts/try-runtime-upgrade.sh b/scripts/try-runtime-upgrade.sh index 80495bcb1d..bf8ac8393f 100755 --- a/scripts/try-runtime-upgrade.sh +++ b/scripts/try-runtime-upgrade.sh @@ -49,7 +49,7 @@ do_try_runtime() { fi eval "try-runtime --runtime $runtime_wasm_path on-runtime-upgrade \ - --no-weight-warnings --disable-spec-version-check --disable-idempotency-checks \ + --no-weight-warnings --disable-spec-version-check --disable-idempotency-checks --checks=all \ $chain_state" } From a7fffd8dec7f59281003b159fd6fa66a207444b3 Mon Sep 17 00:00:00 2001 From: Aliaksandr Tsurko Date: Thu, 30 Jan 2025 15:55:00 +0100 Subject: [PATCH 09/10] Refactor TryState --- pallets/subtensor/src/macros/hooks.rs | 7 +- .../migrations/migrate_init_total_issuance.rs | 7 +- pallets/subtensor/src/utils/mod.rs | 1 + pallets/subtensor/src/utils/try_state.rs | 71 ++++++++++--------- scripts/try-runtime-upgrade.sh | 2 +- 5 files changed, 48 insertions(+), 40 deletions(-) diff --git a/pallets/subtensor/src/macros/hooks.rs b/pallets/subtensor/src/macros/hooks.rs index 2a43238ab3..cefc2e24b2 100644 --- a/pallets/subtensor/src/macros/hooks.rs +++ b/pallets/subtensor/src/macros/hooks.rs @@ -4,6 +4,9 @@ use frame_support::pallet_macros::pallet_section; /// This can later be imported into the pallet using [`import_section`]. #[pallet_section] mod hooks { + #[cfg(feature = "try-runtime")] + use crate::utils::try_state::TryState; + // ================ // ==== Hooks ===== // ================ @@ -82,7 +85,9 @@ mod hooks { #[cfg(feature = "try-runtime")] fn try_state(_n: BlockNumberFor) -> Result<(), sp_runtime::TryRuntimeError> { - Self::check_accounting_invariants()?; + TryState::::check_total_issuance()?; + // Disabled: https://github.com/opentensor/subtensor/pull/1166 + // TryState::::check_total_stake()?; Ok(()) } } diff --git a/pallets/subtensor/src/migrations/migrate_init_total_issuance.rs b/pallets/subtensor/src/migrations/migrate_init_total_issuance.rs index 4501ccf6d5..e1423a6256 100644 --- a/pallets/subtensor/src/migrations/migrate_init_total_issuance.rs +++ b/pallets/subtensor/src/migrations/migrate_init_total_issuance.rs @@ -53,9 +53,10 @@ pub(crate) fn migrate_init_total_issuance() -> Weight { pub mod initialise_total_issuance { use frame_support::pallet_prelude::Weight; - use frame_support::traits::{fungible, OnRuntimeUpgrade}; - use sp_core::Get; + use frame_support::traits::OnRuntimeUpgrade; + #[cfg(feature = "try-runtime")] + use crate::utils::try_state::TryState; use crate::*; pub struct Migration(PhantomData); @@ -79,7 +80,7 @@ pub mod initialise_total_issuance { #[cfg(feature = "try-runtime")] fn post_upgrade(_state: Vec) -> Result<(), sp_runtime::TryRuntimeError> { // Verify that all accounting invariants are satisfied after the migration - crate::Pallet::::check_accounting_invariants()?; + TryState::::check_total_issuance()?; Ok(()) } } diff --git a/pallets/subtensor/src/utils/mod.rs b/pallets/subtensor/src/utils/mod.rs index a42c91119e..909ad89593 100644 --- a/pallets/subtensor/src/utils/mod.rs +++ b/pallets/subtensor/src/utils/mod.rs @@ -2,4 +2,5 @@ use super::*; pub mod identity; pub mod misc; pub mod rate_limiting; +#[cfg(feature = "try-runtime")] pub mod try_state; diff --git a/pallets/subtensor/src/utils/try_state.rs b/pallets/subtensor/src/utils/try_state.rs index c2292eeeee..9899131c3c 100644 --- a/pallets/subtensor/src/utils/try_state.rs +++ b/pallets/subtensor/src/utils/try_state.rs @@ -1,42 +1,17 @@ -use super::*; - -impl Pallet { - /// Checks if the accounting invariants for [`TotalStake`], [`TotalSubnetLocked`], and [`TotalIssuance`] are correct. - /// - /// This function verifies that: - /// 1. The sum of all stakes matches the [`TotalStake`]. - /// 2. The [`TotalSubnetLocked`] is correctly calculated. - /// 3. The [`TotalIssuance`] equals the sum of currency issuance, total stake, and total subnet locked. - /// - /// # Returns - /// - /// Returns `Ok(())` if all invariants are correct, otherwise returns an error. - #[cfg(feature = "try-runtime")] - pub fn check_accounting_invariants() -> Result<(), sp_runtime::TryRuntimeError> { +use core::marker::PhantomData; use frame_support::traits::fungible::Inspect; - // Disabled: https://github.com/opentensor/subtensor/pull/1166 - // - // // Calculate the total staked amount - // let total_staked = SubnetTAO::::iter().fold(0u64, |acc, (netuid, stake)| { - // let acc = acc.saturating_add(stake); - - // if netuid == Self::get_root_netuid() { - // // root network doesn't have initial pool TAO - // acc - // } else { - // acc.saturating_sub(POOL_INITIAL_TAO) - // } - // }); +use crate::subnets::subnet::POOL_INITIAL_TAO; +use super::*; - // // Verify that the calculated total stake matches the stored TotalStake - // ensure!( - // total_staked == TotalStake::::get(), - // "TotalStake does not match total staked", - // ); +pub(crate) struct TryState(PhantomData); +impl TryState { + /// Checks [`TotalIssuance`] equals the sum of currency issuance, total stake, and total subnet + /// locked. + pub(crate) fn check_total_issuance() -> Result<(), sp_runtime::TryRuntimeError> { // Get the total subnet locked amount - let total_subnet_locked = Self::get_total_subnet_locked(); + let total_subnet_locked = Pallet::::get_total_subnet_locked(); // Get the total currency issuance let currency_issuance = T::Currency::total_issuance(); @@ -59,11 +34,37 @@ impl Pallet { expected_total_issuance.checked_sub(total_issuance) } .expect("LHS > RHS"); + ensure!( diff <= delta, "TotalIssuance diff greater than allowable delta", ); - Ok(()) + Ok(()) } + + /// Checks the sum of all stakes matches the [`TotalStake`]. + pub(crate) fn check_total_stake() -> Result<(), sp_runtime::TryRuntimeError> { + // Calculate the total staked amount + let total_staked = SubnetTAO::::iter().fold(0u64, |acc, (netuid, stake)| { + let acc = acc.saturating_add(stake); + + if netuid == Pallet::::get_root_netuid() { + // root network doesn't have initial pool TAO + acc + } else { + acc.saturating_sub(POOL_INITIAL_TAO) + } + }); + + log::warn!("total_staked: {}, TotalStake: {}", total_staked, TotalStake::::get()); + + // Verify that the calculated total stake matches the stored TotalStake + ensure!( + total_staked == TotalStake::::get(), + "TotalStake does not match total staked", + ); + + Ok(()) + } } diff --git a/scripts/try-runtime-upgrade.sh b/scripts/try-runtime-upgrade.sh index bf8ac8393f..11ce78147f 100755 --- a/scripts/try-runtime-upgrade.sh +++ b/scripts/try-runtime-upgrade.sh @@ -49,7 +49,7 @@ do_try_runtime() { fi eval "try-runtime --runtime $runtime_wasm_path on-runtime-upgrade \ - --no-weight-warnings --disable-spec-version-check --disable-idempotency-checks --checks=all \ + --disable-spec-version-check --disable-idempotency-checks --checks=all \ $chain_state" } From d39a6ea31d13eb4a64875ccd61ff3fa5a3fa948f Mon Sep 17 00:00:00 2001 From: Aliaksandr Tsurko Date: Thu, 30 Jan 2025 15:56:44 +0100 Subject: [PATCH 10/10] Reformat --- pallets/subtensor/src/macros/hooks.rs | 9 ++---- .../migrations/migrate_init_total_issuance.rs | 4 +-- pallets/subtensor/src/utils/try_state.rs | 32 ++++++++++--------- scripts/try-runtime-upgrade.sh | 2 +- 4 files changed, 22 insertions(+), 25 deletions(-) diff --git a/pallets/subtensor/src/macros/hooks.rs b/pallets/subtensor/src/macros/hooks.rs index cefc2e24b2..4310d3b1e3 100644 --- a/pallets/subtensor/src/macros/hooks.rs +++ b/pallets/subtensor/src/macros/hooks.rs @@ -4,9 +4,6 @@ use frame_support::pallet_macros::pallet_section; /// This can later be imported into the pallet using [`import_section`]. #[pallet_section] mod hooks { - #[cfg(feature = "try-runtime")] - use crate::utils::try_state::TryState; - // ================ // ==== Hooks ===== // ================ @@ -85,9 +82,9 @@ mod hooks { #[cfg(feature = "try-runtime")] fn try_state(_n: BlockNumberFor) -> Result<(), sp_runtime::TryRuntimeError> { - TryState::::check_total_issuance()?; - // Disabled: https://github.com/opentensor/subtensor/pull/1166 - // TryState::::check_total_stake()?; + Self::check_total_issuance()?; + // Disabled: https://github.com/opentensor/subtensor/pull/1166 + // Self::check_total_stake()?; Ok(()) } } diff --git a/pallets/subtensor/src/migrations/migrate_init_total_issuance.rs b/pallets/subtensor/src/migrations/migrate_init_total_issuance.rs index e1423a6256..ba9d85badc 100644 --- a/pallets/subtensor/src/migrations/migrate_init_total_issuance.rs +++ b/pallets/subtensor/src/migrations/migrate_init_total_issuance.rs @@ -55,8 +55,6 @@ pub mod initialise_total_issuance { use frame_support::pallet_prelude::Weight; use frame_support::traits::OnRuntimeUpgrade; - #[cfg(feature = "try-runtime")] - use crate::utils::try_state::TryState; use crate::*; pub struct Migration(PhantomData); @@ -80,7 +78,7 @@ pub mod initialise_total_issuance { #[cfg(feature = "try-runtime")] fn post_upgrade(_state: Vec) -> Result<(), sp_runtime::TryRuntimeError> { // Verify that all accounting invariants are satisfied after the migration - TryState::::check_total_issuance()?; + crate::Pallet::::check_total_issuance()?; Ok(()) } } diff --git a/pallets/subtensor/src/utils/try_state.rs b/pallets/subtensor/src/utils/try_state.rs index 9899131c3c..db7e4352ea 100644 --- a/pallets/subtensor/src/utils/try_state.rs +++ b/pallets/subtensor/src/utils/try_state.rs @@ -1,17 +1,14 @@ -use core::marker::PhantomData; - use frame_support::traits::fungible::Inspect; +use frame_support::traits::fungible::Inspect; -use crate::subnets::subnet::POOL_INITIAL_TAO; use super::*; +use crate::subnets::subnet::POOL_INITIAL_TAO; -pub(crate) struct TryState(PhantomData); - -impl TryState { - /// Checks [`TotalIssuance`] equals the sum of currency issuance, total stake, and total subnet - /// locked. +impl Pallet { + /// Checks [`TotalIssuance`] equals the sum of currency issuance, total stake, and total subnet + /// locked. pub(crate) fn check_total_issuance() -> Result<(), sp_runtime::TryRuntimeError> { // Get the total subnet locked amount - let total_subnet_locked = Pallet::::get_total_subnet_locked(); + let total_subnet_locked = Self::get_total_subnet_locked(); // Get the total currency issuance let currency_issuance = T::Currency::total_issuance(); @@ -40,16 +37,17 @@ impl TryState { "TotalIssuance diff greater than allowable delta", ); - Ok(()) + Ok(()) } - /// Checks the sum of all stakes matches the [`TotalStake`]. + /// Checks the sum of all stakes matches the [`TotalStake`]. + #[allow(dead_code)] pub(crate) fn check_total_stake() -> Result<(), sp_runtime::TryRuntimeError> { // Calculate the total staked amount let total_staked = SubnetTAO::::iter().fold(0u64, |acc, (netuid, stake)| { let acc = acc.saturating_add(stake); - if netuid == Pallet::::get_root_netuid() { + if netuid == Self::get_root_netuid() { // root network doesn't have initial pool TAO acc } else { @@ -57,7 +55,11 @@ impl TryState { } }); - log::warn!("total_staked: {}, TotalStake: {}", total_staked, TotalStake::::get()); + log::warn!( + "total_staked: {}, TotalStake: {}", + total_staked, + TotalStake::::get() + ); // Verify that the calculated total stake matches the stored TotalStake ensure!( @@ -65,6 +67,6 @@ impl TryState { "TotalStake does not match total staked", ); - Ok(()) - } + Ok(()) + } } diff --git a/scripts/try-runtime-upgrade.sh b/scripts/try-runtime-upgrade.sh index 11ce78147f..bf8ac8393f 100755 --- a/scripts/try-runtime-upgrade.sh +++ b/scripts/try-runtime-upgrade.sh @@ -49,7 +49,7 @@ do_try_runtime() { fi eval "try-runtime --runtime $runtime_wasm_path on-runtime-upgrade \ - --disable-spec-version-check --disable-idempotency-checks --checks=all \ + --no-weight-warnings --disable-spec-version-check --disable-idempotency-checks --checks=all \ $chain_state" }