diff --git a/.claude/skills/fix/SKILL.md b/.claude/skills/fix/SKILL.md new file mode 100644 index 0000000000..15d8adebf9 --- /dev/null +++ b/.claude/skills/fix/SKILL.md @@ -0,0 +1,45 @@ +--- +name: fix +description: Commit changes, run Rust fix tools, run tests, and amend with any fixes +--- + +# Fix Skill + +Commit current changes with a descriptive message, then run Rust fix tools one by one, amending the commit after each tool if it produced changes, then run unit tests and fix any failures. + +## Steps + +1. **Initial commit**: Stage all changes and create a commit with a descriptive message summarizing the changes (use `git add -A && git commit -m ""`). If there are no changes to commit, create no commit but still proceed with the fix tools below. + +2. **Run each fix tool in order**. After EACH tool, check `git status --porcelain` for changes. If there are changes, stage them and amend the commit (`git add -A && git commit --amend --no-edit`). + + The tools to run in order: + + a. `cargo check --workspace` + b. `cargo clippy --fix --workspace --all-features --all-targets --allow-dirty` + c. `cargo fix --workspace --all-features --all-targets --allow-dirty` + d. `cargo fmt --all` + +3. **Run unit tests in a Sonnet subagent**: Launch a Task subagent (subagent_type: `general-purpose`, model: `sonnet`) that runs: + ``` + cargo test -p pallet-subtensor --lib + ``` + The subagent must: + - Run the test command and capture full output. + - If all tests pass, report success and return. + - If any tests fail, analyze the failures: read the failing test code AND the source code it tests, determine the root cause, apply fixes using Edit tools, and re-run the tests to confirm the fix works. + - After fixing, if there are further failures, repeat (up to 3 fix-and-retest cycles). + - Return a summary of: which tests failed, what was fixed, and whether all tests pass now. + +4. **Amend commit with test fixes**: After the subagent returns, if any code changes were made (check `git status --porcelain`), stage and amend the commit (`git add -A && git commit --amend --no-edit`). Then re-run the fix tools from step 2 (since code changes from test fixes may need formatting/clippy cleanup), amending after each if there are changes. + +5. **Final output**: Show `git log --oneline -1` so the user can see the resulting commit. + +## Important + +- Use `--allow-dirty` flags on clippy --fix and cargo fix since the working tree may have unstaged changes between steps. +- If a fix tool fails (step 2/4), stop and report the error to the user rather than continuing. +- Do NOT run `scripts/fix_rust.sh` itself — run the individual commands listed above instead. +- Do NOT skip any step. Run all four fix tools even if earlier ones produced no changes. +- The test subagent must fix source code to make tests pass, NOT modify tests to make them pass (unless the test itself is clearly wrong). +- If the test subagent cannot fix all failures after 3 cycles, it must return the remaining failures so the main agent can report them to the user. diff --git a/.claude/skills/ship/SKILL.md b/.claude/skills/ship/SKILL.md new file mode 100644 index 0000000000..58ca7e0e32 --- /dev/null +++ b/.claude/skills/ship/SKILL.md @@ -0,0 +1,94 @@ +--- +name: ship +description: Ship the current branch: fix, push, create PR, watch CI, fix failures, code review +--- + +# Ship Skill + +Ship the current branch: fix, push, create PR if needed, watch CI, fix failures, and perform code review. + +## Phase 1: Fix and Push + +1. **Run `/fix`** — invoke the fix skill to commit, lint, and format. +2. **Push the branch** to origin: `git push -u origin HEAD`. +3. **Create a PR if none exists**: + - Check: `gh pr view --json number 2>/dev/null` — if it fails, no PR exists yet. + - If no PR exists, create one: + - Use `git log main..HEAD --oneline` to understand all commits on the branch. + - Read the changed files with `git diff main...HEAD --stat` to understand scope. + - Create the PR with `gh pr create --title "" --body "" --label "skip-cargo-audit"`. + - The description must include: a **Summary** section (bullet points of what changed and why), a **Changes** section (key files/modules affected), and a **Test plan** section. + - If a PR already exists, just note its number/URL. + +## Phase 2: Watch CI and Fix Failures + +4. **Poll CI status** in a loop: + - Run: `gh pr checks --json name,state,conclusion,link --watch --fail-fast 2>/dev/null || gh pr checks` + - If `--watch` is not available, poll manually every 90 seconds using `gh pr checks --json name,state,conclusion,link` until all checks have completed (no checks with state "pending" or conclusion ""). + - **Ignore these known-flaky/irrelevant checks** — treat them as passing even if they fail: + - `validate-benchmarks` (benchmark CI — not relevant) + - Any `Contract E2E Tests` check that failed only due to a timeout (look for timeout in the failure link/logs) + - `cargo-audit` (we already added the skip label) + - Also ignore any checks related to `check-spec-version` and `e2e` tests — these are environment-dependent and not fixable from code. + +5. **If there are real CI failures** (failures NOT in the ignore list above): + - For EACH distinct failing check, launch a **separate Task subagent** (subagent_type: `general-purpose`, model: `sonnet`) in parallel. Each subagent must: + - Fetch the failed check's logs: use `gh run view --log-failed` or the check link to get failure details. + - Investigate the root cause by reading relevant source files. + - Return a **fix plan**: a description of what needs to change and in which files, with specific code snippets showing the fix. + - **Wait for all subagents** to return their fix plans. + +6. **Aggregate and apply fixes**: + - Review all returned fix plans for conflicts or overlaps. + - Apply the fixes using Edit/Write tools. + - Run `/fix` again (invoke the fix skill) to commit, lint, and format the fixes. + - Push: `git push`. + +7. **Re-check CI**: Go back to step 4 and poll again. Repeat the fix cycle up to **3 times**. If CI still fails after 3 rounds, report the remaining failures to the user and stop. + +## Phase 3: Code Review + +8. **Once CI is green** (or only ignored checks are failing), perform a thorough code review. + +9. **Launch a single Opus subagent** (subagent_type: `general-purpose`, model: `opus`) for the review: + - It must get the full PR diff: `git diff main...HEAD`. + - It must read every changed file in full. + - It must produce a numbered list of **issues** found, where each issue has: + - A unique sequential ID (e.g., `R-1`, `R-2`, ...). + - **Severity**: critical / major / minor / nit. + - **File and line(s)** affected. + - **Description** of the problem. + - The review must check for: correctness, safety (no panics, no unchecked arithmetic, no indexing), edge cases, naming, documentation gaps, test coverage, and adherence to Substrate/Rust best practices. + - Return the full list of issues. + +10. **For each issue**, launch TWO subagents **in parallel**: + - **Fix designer** (subagent_type: `general-purpose`, model: `sonnet`): Given the issue description and relevant code context, design a concrete proposed fix with exact code changes (old code -> new code). Return the fix as a structured plan. + - **Fix reviewer** (subagent_type: `general-purpose`, model: `opus`): Given the issue description, the relevant code context, and the proposed fix (once the fix designer returns — so the reviewer runs AFTER the designer, but reviewers for different issues run in parallel with each other). The reviewer must check: + - Does the fix actually solve the issue? + - Does it introduce new problems? + - Is it the simplest correct fix? + - Return: approved / rejected with reasoning. + + Implementation note: For each issue, first launch the fix designer. Once the fix designer for that issue returns, launch the fix reviewer for that issue. But all issues should be processed in parallel — i.e., launch all fix designers at once, then as each designer returns, launch its corresponding reviewer. You may batch reviewers if designers finish close together. + +11. **Report to user**: Present a formatted summary: + ``` + ## Code Review Results + + ### R-1: [severity] + **File**: path/to/file.rs:42 + **Issue**: <description> + **Proposed fix**: <summary of fix> + **Review**: Approved / Rejected — <reasoning> + + ### R-2: ... + ``` + Ask the user which fixes to apply (all approved ones, specific ones by ID, or none). + +## Important Rules + +- Never force-push. Always use regular `git push`. +- All CI polling must have a maximum total wall-clock timeout of 45 minutes. If CI hasn't finished by then, report current status and stop waiting. +- When fetching CI logs, if `gh run view` output is very long, focus on the failed step output only. +- Do NOT apply code review fixes automatically — always present them for user approval first. +- Use HEREDOC syntax for PR body and commit messages to preserve formatting. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000000..f095488a7b --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,2 @@ +- never use slice indexing like `arr[n..]` or `arr[i]`; use `.get(n..)`, `.get(i)` etc. instead to avoid panics (clippy::indexing_slicing) +- never use `*`, `+`, `-`, `/` for arithmetic; use `.saturating_mul()`, `.saturating_add()`, `.saturating_sub()`, `.saturating_div()` or checked variants instead (clippy::arithmetic_side_effects) diff --git a/pallets/subtensor/src/coinbase/root.rs b/pallets/subtensor/src/coinbase/root.rs index ba7d54ed3c..3de85295f1 100644 --- a/pallets/subtensor/src/coinbase/root.rs +++ b/pallets/subtensor/src/coinbase/root.rs @@ -300,6 +300,11 @@ impl<T: Config> Pallet<T> { SubnetTaoFlow::<T>::remove(netuid); SubnetEmaTaoFlow::<T>::remove(netuid); + // --- 12b. Emission suppression. + EmissionSuppression::<T>::remove(netuid); + EmissionSuppressionOverride::<T>::remove(netuid); + let _ = EmissionSuppressionVote::<T>::clear_prefix(netuid, u32::MAX, None); + // --- 13. Token / mechanism / registration toggles. TokenSymbol::<T>::remove(netuid); SubnetMechanism::<T>::remove(netuid); diff --git a/pallets/subtensor/src/coinbase/run_coinbase.rs b/pallets/subtensor/src/coinbase/run_coinbase.rs index f40d4e704b..307821e62c 100644 --- a/pallets/subtensor/src/coinbase/run_coinbase.rs +++ b/pallets/subtensor/src/coinbase/run_coinbase.rs @@ -187,6 +187,7 @@ impl<T: Config> Pallet<T> { // --- 3. Inject ALPHA for participants. let cut_percent: U96F32 = Self::get_float_subnet_owner_cut(); + let root_sell_pressure_mode = KeepRootSellPressureOnSuppressedSubnets::<T>::get(); for netuid_i in subnets_to_emit_to.iter() { // Get alpha_out for this block. @@ -212,6 +213,9 @@ impl<T: Config> Pallet<T> { let root_proportion = Self::root_proportion(*netuid_i); log::debug!("root_proportion: {root_proportion:?}"); + // Check if subnet emission is suppressed (compute once to avoid double storage read). + let is_suppressed = Self::is_subnet_emission_suppressed(*netuid_i); + // Get root alpha from root prop. let root_alpha: U96F32 = root_proportion .saturating_mul(alpha_out_i) // Total alpha emission per block remaining. @@ -239,10 +243,37 @@ impl<T: Config> Pallet<T> { }); if root_sell_flag { - // Only accumulate root alpha divs if root sell is allowed. - PendingRootAlphaDivs::<T>::mutate(*netuid_i, |total| { - *total = total.saturating_add(tou64!(root_alpha).into()); - }); + // Determine disposition of root alpha based on suppression mode. + if is_suppressed + && root_sell_pressure_mode == RootSellPressureOnSuppressedSubnetsMode::Disable + { + // Disable mode: recycle root alpha back to subnet validators. + PendingValidatorEmission::<T>::mutate(*netuid_i, |total| { + *total = total.saturating_add(tou64!(root_alpha).into()); + }); + } else if is_suppressed + && root_sell_pressure_mode == RootSellPressureOnSuppressedSubnetsMode::Recycle + { + // Recycle mode: swap alpha → TAO via AMM, then burn the TAO. + let root_alpha_currency = AlphaCurrency::from(tou64!(root_alpha)); + if let Ok(swap_result) = Self::swap_alpha_for_tao( + *netuid_i, + root_alpha_currency, + TaoCurrency::ZERO, // no price limit + true, // drop fees + ) { + Self::record_tao_outflow(*netuid_i, swap_result.amount_paid_out); + Self::recycle_tao(swap_result.amount_paid_out); + } else { + // Swap failed: recycle alpha back to subnet to prevent loss. + Self::recycle_subnet_alpha(*netuid_i, root_alpha_currency); + } + } else { + // Enable mode (or non-suppressed subnet): accumulate for root validators. + PendingRootAlphaDivs::<T>::mutate(*netuid_i, |total| { + *total = total.saturating_add(tou64!(root_alpha).into()); + }); + } } else { // If we are not selling the root alpha, we should recycle it. Self::recycle_subnet_alpha(*netuid_i, AlphaCurrency::from(tou64!(root_alpha))); @@ -269,6 +300,9 @@ impl<T: Config> Pallet<T> { if Self::should_run_epoch(netuid, current_block) && Self::is_epoch_input_state_consistent(netuid) { + // Collect emission suppression votes for this subnet. + Self::collect_emission_suppression_votes(netuid); + // Restart counters. BlocksSinceLastStep::<T>::insert(netuid, 0); LastMechansimStepBlock::<T>::insert(netuid, current_block); diff --git a/pallets/subtensor/src/coinbase/subnet_emissions.rs b/pallets/subtensor/src/coinbase/subnet_emissions.rs index 477a678864..5395187c72 100644 --- a/pallets/subtensor/src/coinbase/subnet_emissions.rs +++ b/pallets/subtensor/src/coinbase/subnet_emissions.rs @@ -4,6 +4,10 @@ use safe_math::FixedExt; use substrate_fixed::transcendental::{exp, ln}; use substrate_fixed::types::{I32F32, I64F64, U64F64, U96F32}; +/// Emission suppression threshold (50%). Subnets with suppression fraction +/// above this value are considered emission-suppressed. +const EMISSION_SUPPRESSION_THRESHOLD: f64 = 0.5; + impl<T: Config> Pallet<T> { pub fn get_subnets_to_emit_to(subnets: &[NetUid]) -> Vec<NetUid> { // Filter out root subnet. @@ -27,7 +31,8 @@ impl<T: Config> Pallet<T> { block_emission: U96F32, ) -> BTreeMap<NetUid, U96F32> { // Get subnet TAO emissions. - let shares = Self::get_shares(subnets_to_emit_to); + let mut shares = Self::get_shares(subnets_to_emit_to); + Self::apply_emission_suppression(&mut shares); log::debug!("Subnet emission shares = {shares:?}"); shares @@ -246,4 +251,78 @@ impl<T: Config> Pallet<T> { }) .collect::<BTreeMap<NetUid, U64F64>>() } + + /// Normalize shares so they sum to 1.0. + pub(crate) fn normalize_shares(shares: &mut BTreeMap<NetUid, U64F64>) { + let sum: U64F64 = shares + .values() + .copied() + .fold(U64F64::saturating_from_num(0), |acc, v| { + acc.saturating_add(v) + }); + if sum > U64F64::saturating_from_num(0) { + for s in shares.values_mut() { + *s = s.safe_div(sum); + } + } + } + + /// Check if a subnet is currently emission-suppressed, considering override first. + pub(crate) fn is_subnet_emission_suppressed(netuid: NetUid) -> bool { + match EmissionSuppressionOverride::<T>::get(netuid) { + Some(true) => true, + Some(false) => false, + None => { + EmissionSuppression::<T>::get(netuid) + > U64F64::saturating_from_num(EMISSION_SUPPRESSION_THRESHOLD) + } + } + } + + /// Zero the emission share of any subnet whose suppression fraction exceeds 50% + /// (or is force-suppressed via override), then re-normalize the remaining shares. + pub(crate) fn apply_emission_suppression(shares: &mut BTreeMap<NetUid, U64F64>) { + let zero = U64F64::saturating_from_num(0); + let mut any_zeroed = false; + for (netuid, share) in shares.iter_mut() { + if Self::is_subnet_emission_suppressed(*netuid) { + *share = zero; + any_zeroed = true; + } + } + if any_zeroed { + Self::normalize_shares(shares); + } + } + + /// Collect emission suppression votes from root validators for a subnet + /// and update the EmissionSuppression storage. + /// Called once per subnet per epoch. No-op for root subnet. + pub(crate) fn collect_emission_suppression_votes(netuid: NetUid) { + if netuid.is_root() { + return; + } + let root_n = SubnetworkN::<T>::get(NetUid::ROOT); + let mut suppress_stake = U64F64::saturating_from_num(0u64); + let mut total_root_stake = U64F64::saturating_from_num(0u64); + + for uid in 0..root_n { + let hotkey = Keys::<T>::get(NetUid::ROOT, uid); + let root_stake = Self::get_stake_for_hotkey_on_subnet(&hotkey, NetUid::ROOT); + let stake_u64f64 = U64F64::saturating_from_num(u64::from(root_stake)); + total_root_stake = total_root_stake.saturating_add(stake_u64f64); + + let coldkey = Owner::<T>::get(&hotkey); + if let Some(true) = EmissionSuppressionVote::<T>::get(netuid, &coldkey) { + suppress_stake = suppress_stake.saturating_add(stake_u64f64); + } + } + + let suppression = if total_root_stake > U64F64::saturating_from_num(0u64) { + suppress_stake.safe_div(total_root_stake) + } else { + U64F64::saturating_from_num(0u64) + }; + EmissionSuppression::<T>::insert(netuid, suppression); + } } diff --git a/pallets/subtensor/src/lib.rs b/pallets/subtensor/src/lib.rs index c137b92371..cd524f5d0e 100644 --- a/pallets/subtensor/src/lib.rs +++ b/pallets/subtensor/src/lib.rs @@ -344,6 +344,23 @@ pub mod pallet { }, } + /// Controls how root alpha dividends are handled on emission-suppressed subnets. + #[derive( + Encode, Decode, Default, TypeInfo, Clone, Copy, PartialEq, Eq, Debug, DecodeWithMemTracking, + )] + pub enum RootSellPressureOnSuppressedSubnetsMode { + /// Root gets no alpha on suppressed subnets; root alpha recycled to subnet validators. + #[codec(index = 0)] + Disable, + /// Root still accumulates alpha on suppressed subnets (old `true`). + #[codec(index = 1)] + Enable, + /// Root alpha is swapped to TAO via AMM and the TAO is burned. + #[default] + #[codec(index = 2)] + Recycle, + } + /// Default minimum root claim amount. /// This is the minimum amount of root claim that can be made. /// Any amount less than this will not be claimed. @@ -2409,6 +2426,34 @@ pub mod pallet { pub type PendingChildKeyCooldown<T: Config> = StorageValue<_, u64, ValueQuery, DefaultPendingChildKeyCooldown<T>>; + /// Stake-weighted suppression fraction for each subnet. + /// Updated every epoch from root validator votes. + /// When this value exceeds 0.5, the subnet's emission share is zeroed. + #[pallet::storage] + pub type EmissionSuppression<T: Config> = StorageMap<_, Identity, NetUid, U64F64, ValueQuery>; + + /// Root override for emission suppression per subnet. + /// Some(true) = force suppressed, Some(false) = force unsuppressed, + /// None = use vote-based EmissionSuppression value. + #[pallet::storage] + pub type EmissionSuppressionOverride<T: Config> = + StorageMap<_, Identity, NetUid, bool, OptionQuery>; + + /// Per-(netuid, coldkey) vote on whether to suppress a subnet's emissions. + /// Keyed by coldkey because coldkey swaps must migrate votes and one coldkey + /// can control multiple root hotkeys. + #[pallet::storage] + pub type EmissionSuppressionVote<T: Config> = + StorageDoubleMap<_, Identity, NetUid, Blake2_128Concat, T::AccountId, bool, OptionQuery>; + + /// Controls how root alpha dividends are handled on emission-suppressed subnets. + /// - Disable (0x00): root gets no alpha; root alpha recycled to subnet validators. + /// - Enable (0x01): root still accumulates alpha (old behaviour). + /// - Recycle (0x02, default): root alpha swapped to TAO and TAO burned. + #[pallet::storage] + pub type KeepRootSellPressureOnSuppressedSubnets<T: Config> = + StorageValue<_, RootSellPressureOnSuppressedSubnetsMode, ValueQuery>; + #[pallet::genesis_config] pub struct GenesisConfig<T: Config> { /// Stakes record in genesis. diff --git a/pallets/subtensor/src/macros/dispatches.rs b/pallets/subtensor/src/macros/dispatches.rs index 60c37de2fe..75a00083f1 100644 --- a/pallets/subtensor/src/macros/dispatches.rs +++ b/pallets/subtensor/src/macros/dispatches.rs @@ -2599,5 +2599,104 @@ mod dispatches { ) -> DispatchResult { Self::do_add_stake_burn(origin, hotkey, netuid, amount, limit) } + + /// --- Set or clear the root override for emission suppression on a subnet. + /// Some(true) forces suppression, Some(false) forces unsuppression, + /// None removes the override and falls back to vote-based suppression. + #[pallet::call_index(133)] + #[pallet::weight(( + Weight::from_parts(5_000_000, 0) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)), + DispatchClass::Operational, + Pays::No + ))] + pub fn sudo_set_emission_suppression_override( + origin: OriginFor<T>, + netuid: NetUid, + override_value: Option<bool>, + ) -> DispatchResult { + ensure_root(origin)?; + ensure!(Self::if_subnet_exist(netuid), Error::<T>::SubnetNotExists); + ensure!(!netuid.is_root(), Error::<T>::CannotVoteOnRootSubnet); + match override_value { + Some(val) => EmissionSuppressionOverride::<T>::insert(netuid, val), + None => EmissionSuppressionOverride::<T>::remove(netuid), + } + Self::deposit_event(Event::EmissionSuppressionOverrideSet { + netuid, + override_value, + }); + Ok(()) + } + + /// --- Vote to suppress or unsuppress emissions for a subnet. + /// The caller must be a coldkey that owns at least one hotkey registered on root + /// with stake >= StakeThreshold. Pass suppress=None to clear the vote. + #[pallet::call_index(134)] + #[pallet::weight(( + Weight::from_parts(20_000_000, 0) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().reads(128)) + .saturating_add(T::DbWeight::get().writes(1)), + DispatchClass::Normal, + Pays::Yes + ))] + pub fn vote_emission_suppression( + origin: OriginFor<T>, + netuid: NetUid, + suppress: Option<bool>, + ) -> DispatchResult { + let coldkey = ensure_signed(origin)?; + ensure!(Self::if_subnet_exist(netuid), Error::<T>::SubnetNotExists); + ensure!(!netuid.is_root(), Error::<T>::CannotVoteOnRootSubnet); + + // Only require root registration + stake threshold when *setting* a vote. + // Clearing (None) is always allowed so that deregistered/understaked coldkeys + // can clean up their own stale entries. + if suppress.is_some() { + // Coldkey must own at least one hotkey registered on root with enough stake. + let stake_threshold = Self::get_stake_threshold(); + let hotkeys = OwnedHotkeys::<T>::get(&coldkey); + let has_qualifying_hotkey = hotkeys.iter().any(|hk| { + Self::is_hotkey_registered_on_network(NetUid::ROOT, hk) + && u64::from(Self::get_stake_for_hotkey_on_subnet(hk, NetUid::ROOT)) + >= stake_threshold + }); + ensure!(has_qualifying_hotkey, Error::<T>::NotEnoughStakeToVote); + } + + match suppress { + Some(val) => EmissionSuppressionVote::<T>::insert(netuid, &coldkey, val), + None => EmissionSuppressionVote::<T>::remove(netuid, &coldkey), + } + Self::deposit_event(Event::EmissionSuppressionVoteCast { + coldkey, + netuid, + suppress, + }); + Ok(()) + } + + /// --- Set the mode for root alpha dividends on emission-suppressed subnets. + /// - Disable: root gets no alpha; root alpha recycled to subnet validators. + /// - Enable: root still accumulates alpha (old behaviour). + /// - Recycle: root alpha swapped to TAO via AMM, TAO burned. + #[pallet::call_index(135)] + #[pallet::weight(( + Weight::from_parts(5_000_000, 0) + .saturating_add(T::DbWeight::get().writes(1)), + DispatchClass::Operational, + Pays::No + ))] + pub fn sudo_set_root_sell_pressure_on_suppressed_subnets_mode( + origin: OriginFor<T>, + mode: RootSellPressureOnSuppressedSubnetsMode, + ) -> DispatchResult { + ensure_root(origin)?; + KeepRootSellPressureOnSuppressedSubnets::<T>::put(mode); + Self::deposit_event(Event::RootSellPressureOnSuppressedSubnetsModeSet { mode }); + Ok(()) + } } } diff --git a/pallets/subtensor/src/macros/errors.rs b/pallets/subtensor/src/macros/errors.rs index 7d50373f19..49f1975af4 100644 --- a/pallets/subtensor/src/macros/errors.rs +++ b/pallets/subtensor/src/macros/errors.rs @@ -282,5 +282,11 @@ mod errors { Deprecated, /// "Add stake and burn" exceeded the operation rate limit AddStakeBurnRateLimitExceeded, + /// Cannot vote on emission suppression for the root subnet. + CannotVoteOnRootSubnet, + /// Coldkey does not own a root-registered hotkey with enough stake. + NotEnoughStakeToVote, + /// Coldkey swap destination already has emission suppression votes. + DestinationColdkeyHasExistingVotes, } } diff --git a/pallets/subtensor/src/macros/events.rs b/pallets/subtensor/src/macros/events.rs index 65c33aee87..3225970f6e 100644 --- a/pallets/subtensor/src/macros/events.rs +++ b/pallets/subtensor/src/macros/events.rs @@ -517,6 +517,30 @@ mod events { alpha: AlphaCurrency, }, + /// A root validator cast (or cleared) an emission suppression vote. + EmissionSuppressionVoteCast { + /// The coldkey that cast the vote + coldkey: T::AccountId, + /// The subnet voted on + netuid: NetUid, + /// The vote: Some(true) = suppress, Some(false) = unsuppress, None = cleared + suppress: Option<bool>, + }, + + /// Root set or cleared the emission suppression override for a subnet. + EmissionSuppressionOverrideSet { + /// The subnet affected + netuid: NetUid, + /// The override value: Some(true) = force suppress, Some(false) = force unsuppress, None = cleared + override_value: Option<bool>, + }, + + /// Root set the RootSellPressureOnSuppressedSubnetsMode. + RootSellPressureOnSuppressedSubnetsModeSet { + /// The new mode + mode: RootSellPressureOnSuppressedSubnetsMode, + }, + /// "Add stake and burn" event: alpha token was purchased and burned. AddStakeBurn { /// The subnet ID diff --git a/pallets/subtensor/src/swap/swap_coldkey.rs b/pallets/subtensor/src/swap/swap_coldkey.rs index 54b07d9dbf..4491f732d8 100644 --- a/pallets/subtensor/src/swap/swap_coldkey.rs +++ b/pallets/subtensor/src/swap/swap_coldkey.rs @@ -16,6 +16,13 @@ impl<T: Config> Pallet<T> { !Self::hotkey_account_exists(new_coldkey), Error::<T>::NewColdKeyIsHotkey ); + // Verify the destination coldkey has no existing emission suppression votes. + for netuid in Self::get_all_subnet_netuids() { + ensure!( + EmissionSuppressionVote::<T>::get(netuid, new_coldkey).is_none(), + Error::<T>::DestinationColdkeyHasExistingVotes + ); + } // Swap the identity if the old coldkey has one and the new coldkey doesn't if IdentitiesV2::<T>::get(new_coldkey).is_none() @@ -31,6 +38,7 @@ impl<T: Config> Pallet<T> { } Self::transfer_staking_hotkeys(old_coldkey, new_coldkey); Self::transfer_hotkeys_ownership(old_coldkey, new_coldkey); + Self::transfer_emission_suppression_votes(old_coldkey, new_coldkey); // Transfer any remaining balance from old_coldkey to new_coldkey let remaining_balance = Self::get_coldkey_balance(old_coldkey); @@ -159,4 +167,17 @@ impl<T: Config> Pallet<T> { OwnedHotkeys::<T>::remove(old_coldkey); OwnedHotkeys::<T>::insert(new_coldkey, new_owned_hotkeys); } + + /// Transfer emission suppression votes from the old coldkey to the new coldkey. + /// Since EmissionSuppressionVote is keyed by (netuid, coldkey), we must iterate + /// all subnets to find votes belonging to the old coldkey. + /// NOTE: The caller must verify the new coldkey has no existing votes before calling this. + fn transfer_emission_suppression_votes(old_coldkey: &T::AccountId, new_coldkey: &T::AccountId) { + let all_netuids = Self::get_all_subnet_netuids(); + for netuid in all_netuids { + if let Some(vote) = EmissionSuppressionVote::<T>::take(netuid, old_coldkey) { + EmissionSuppressionVote::<T>::insert(netuid, new_coldkey, vote); + } + } + } } diff --git a/pallets/subtensor/src/tests/emission_suppression.rs b/pallets/subtensor/src/tests/emission_suppression.rs new file mode 100644 index 0000000000..71c18a2b08 --- /dev/null +++ b/pallets/subtensor/src/tests/emission_suppression.rs @@ -0,0 +1,1347 @@ +#![allow(clippy::indexing_slicing, clippy::panic, clippy::unwrap_used)] +use super::mock::*; +use crate::*; +use alloc::collections::BTreeMap; +use frame_support::{assert_err, assert_ok}; +use sp_core::U256; +use substrate_fixed::types::{U64F64, U96F32}; +use subtensor_runtime_common::{AlphaCurrency, NetUid, TaoCurrency}; + +/// Helper: set up root network + register a hotkey on root with given stake. +/// Returns (hotkey, coldkey). +fn setup_root_validator(hotkey_seed: u64, coldkey_seed: u64, root_stake: u64) -> (U256, U256) { + let hotkey = U256::from(hotkey_seed); + let coldkey = U256::from(coldkey_seed); + assert_ok!(SubtensorModule::root_register( + RuntimeOrigin::signed(coldkey), + hotkey, + )); + SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( + &hotkey, + &coldkey, + NetUid::ROOT, + root_stake.into(), + ); + (hotkey, coldkey) +} + +/// Helper: create a non-root subnet with TAO flow so it gets shares. +fn setup_subnet_with_flow(netuid: NetUid, tempo: u16, tao_flow: i64) { + add_network(netuid, tempo, 0); + SubnetTaoFlow::<Test>::insert(netuid, tao_flow); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Test 1: >50% stake votes suppress → share=0, rest renormalized +// ───────────────────────────────────────────────────────────────────────────── +#[test] +fn test_suppression_zeroes_share_majority() { + new_test_ext(1).execute_with(|| { + let sn1 = NetUid::from(1); + let sn2 = NetUid::from(2); + setup_subnet_with_flow(sn1, 10, 100_000_000); + setup_subnet_with_flow(sn2, 10, 100_000_000); + + // Directly set suppression > 0.5 for sn1. + EmissionSuppression::<Test>::insert(sn1, U64F64::from_num(0.6)); + + let mut shares = SubtensorModule::get_shares(&[sn1, sn2]); + SubtensorModule::apply_emission_suppression(&mut shares); + + // sn1 should be zeroed. + assert_eq!( + shares.get(&sn1).copied().unwrap_or(U64F64::from_num(0)), + U64F64::from_num(0) + ); + // sn2 should get the full share (renormalized to 1.0). + let sn2_share = shares.get(&sn2).copied().unwrap_or(U64F64::from_num(0)); + assert!( + sn2_share > U64F64::from_num(0.99), + "sn2 share should be ~1.0, got {sn2_share:?}" + ); + }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Test 2: <50% stake votes suppress → share unchanged +// ───────────────────────────────────────────────────────────────────────────── +#[test] +fn test_suppression_no_effect_below_half() { + new_test_ext(1).execute_with(|| { + let sn1 = NetUid::from(1); + let sn2 = NetUid::from(2); + setup_subnet_with_flow(sn1, 10, 100_000_000); + setup_subnet_with_flow(sn2, 10, 100_000_000); + + // Set suppression <= 0.5 for sn1. + EmissionSuppression::<Test>::insert(sn1, U64F64::from_num(0.4)); + + let mut shares = SubtensorModule::get_shares(&[sn1, sn2]); + let shares_before = shares.clone(); + SubtensorModule::apply_emission_suppression(&mut shares); + + // Both shares should be unchanged. + assert_eq!(shares, shares_before); + }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Test 3: Root override=Some(true), no votes → suppressed +// ───────────────────────────────────────────────────────────────────────────── +#[test] +fn test_override_force_suppress() { + new_test_ext(1).execute_with(|| { + let sn1 = NetUid::from(1); + let sn2 = NetUid::from(2); + setup_subnet_with_flow(sn1, 10, 100_000_000); + setup_subnet_with_flow(sn2, 10, 100_000_000); + + // No votes, suppression is 0. But override forces suppression. + EmissionSuppressionOverride::<Test>::insert(sn1, true); + + let mut shares = SubtensorModule::get_shares(&[sn1, sn2]); + SubtensorModule::apply_emission_suppression(&mut shares); + + assert_eq!( + shares.get(&sn1).copied().unwrap_or(U64F64::from_num(0)), + U64F64::from_num(0) + ); + let sn2_share = shares.get(&sn2).copied().unwrap_or(U64F64::from_num(0)); + assert!( + sn2_share > U64F64::from_num(0.99), + "sn2 share should be ~1.0, got {sn2_share:?}" + ); + }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Test 4: Majority votes suppress, override=Some(false) → not suppressed +// ───────────────────────────────────────────────────────────────────────────── +#[test] +fn test_override_force_unsuppress() { + new_test_ext(1).execute_with(|| { + let sn1 = NetUid::from(1); + let sn2 = NetUid::from(2); + setup_subnet_with_flow(sn1, 10, 100_000_000); + setup_subnet_with_flow(sn2, 10, 100_000_000); + + // Set high suppression fraction. + EmissionSuppression::<Test>::insert(sn1, U64F64::from_num(0.9)); + // But override forces unsuppression. + EmissionSuppressionOverride::<Test>::insert(sn1, false); + + let mut shares = SubtensorModule::get_shares(&[sn1, sn2]); + let shares_before = shares.clone(); + SubtensorModule::apply_emission_suppression(&mut shares); + + // Shares should be unchanged (not suppressed). + assert_eq!(shares, shares_before); + }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Test 5: Override=None, votes determine outcome +// ───────────────────────────────────────────────────────────────────────────── +#[test] +fn test_override_none_uses_votes() { + new_test_ext(1).execute_with(|| { + let sn1 = NetUid::from(1); + let sn2 = NetUid::from(2); + setup_subnet_with_flow(sn1, 10, 100_000_000); + setup_subnet_with_flow(sn2, 10, 100_000_000); + + // No override (default). + // Set suppression > 0.5. + EmissionSuppression::<Test>::insert(sn1, U64F64::from_num(0.7)); + + let mut shares = SubtensorModule::get_shares(&[sn1, sn2]); + SubtensorModule::apply_emission_suppression(&mut shares); + + assert_eq!( + shares.get(&sn1).copied().unwrap_or(U64F64::from_num(0)), + U64F64::from_num(0) + ); + }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Test 6: Non-root validator → error +// ───────────────────────────────────────────────────────────────────────────── +#[test] +fn test_vote_requires_root_registration() { + new_test_ext(1).execute_with(|| { + add_network(NetUid::ROOT, 1, 0); + let sn1 = NetUid::from(1); + setup_subnet_with_flow(sn1, 10, 100_000_000); + + // coldkey with no root-registered hotkey. + let coldkey = U256::from(999); + + assert_err!( + SubtensorModule::vote_emission_suppression( + RuntimeOrigin::signed(coldkey), + sn1, + Some(true), + ), + Error::<Test>::NotEnoughStakeToVote + ); + }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Test 7: Below threshold → error +// ───────────────────────────────────────────────────────────────────────────── +#[test] +fn test_vote_requires_minimum_stake() { + new_test_ext(1).execute_with(|| { + add_network(NetUid::ROOT, 1, 0); + let sn1 = NetUid::from(1); + setup_subnet_with_flow(sn1, 10, 100_000_000); + + // Set a non-zero stake threshold. + StakeThreshold::<Test>::put(1_000_000); + + let hotkey = U256::from(10); + let coldkey = U256::from(11); + assert_ok!(SubtensorModule::root_register( + RuntimeOrigin::signed(coldkey), + hotkey, + )); + // Stake below threshold. + SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( + &hotkey, + &coldkey, + NetUid::ROOT, + 999_999u64.into(), + ); + + assert_err!( + SubtensorModule::vote_emission_suppression( + RuntimeOrigin::signed(coldkey), + sn1, + Some(true), + ), + Error::<Test>::NotEnoughStakeToVote + ); + }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Test 8: Vote then clear (None) → suppression drops +// ───────────────────────────────────────────────────────────────────────────── +#[test] +fn test_vote_clear() { + new_test_ext(1).execute_with(|| { + add_network(NetUid::ROOT, 1, 0); + let sn1 = NetUid::from(1); + setup_subnet_with_flow(sn1, 10, 100_000_000); + + let (_hotkey, coldkey) = setup_root_validator(10, 11, 1_000_000); + + // Vote to suppress. + assert_ok!(SubtensorModule::vote_emission_suppression( + RuntimeOrigin::signed(coldkey), + sn1, + Some(true), + )); + assert_eq!( + EmissionSuppressionVote::<Test>::get(sn1, coldkey), + Some(true) + ); + + // Clear vote. + assert_ok!(SubtensorModule::vote_emission_suppression( + RuntimeOrigin::signed(coldkey), + sn1, + None, + )); + assert_eq!(EmissionSuppressionVote::<Test>::get(sn1, coldkey), None); + + // Collect votes - should result in 0 suppression. + SubtensorModule::collect_emission_suppression_votes(sn1); + let suppression = EmissionSuppression::<Test>::get(sn1); + assert_eq!(suppression, U64F64::from_num(0)); + }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Test 9: Suppression only updates on epoch +// ───────────────────────────────────────────────────────────────────────────── +#[test] +fn test_votes_collected_on_epoch() { + new_test_ext(1).execute_with(|| { + add_network(NetUid::ROOT, 1, 0); + let sn1 = NetUid::from(1); + setup_subnet_with_flow(sn1, 10, 100_000_000); + + let (_hotkey, coldkey) = setup_root_validator(10, 11, 1_000_000); + + // Vote to suppress. + assert_ok!(SubtensorModule::vote_emission_suppression( + RuntimeOrigin::signed(coldkey), + sn1, + Some(true), + )); + + // Before epoch, suppression should still be 0 (default). + assert_eq!(EmissionSuppression::<Test>::get(sn1), U64F64::from_num(0)); + + // Run epochs so vote collection occurs. + step_epochs(1, sn1); + + // After epoch, suppression should be updated. + let suppression = EmissionSuppression::<Test>::get(sn1); + assert!( + suppression > U64F64::from_num(0), + "suppression should be > 0 after epoch, got {suppression:?}" + ); + }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Test 10: Swap coldkey → votes follow +// ───────────────────────────────────────────────────────────────────────────── +#[test] +fn test_coldkey_swap_migrates_votes() { + new_test_ext(1).execute_with(|| { + add_network(NetUid::ROOT, 1, 0); + let sn1 = NetUid::from(1); + setup_subnet_with_flow(sn1, 10, 100_000_000); + + let (_hotkey, old_coldkey) = setup_root_validator(10, 11, 1_000_000); + + // Vote to suppress. + assert_ok!(SubtensorModule::vote_emission_suppression( + RuntimeOrigin::signed(old_coldkey), + sn1, + Some(true), + )); + assert_eq!( + EmissionSuppressionVote::<Test>::get(sn1, old_coldkey), + Some(true) + ); + + // Perform coldkey swap. + let new_coldkey = U256::from(999); + assert_ok!(SubtensorModule::do_swap_coldkey(&old_coldkey, &new_coldkey)); + + // Vote should be on new coldkey. + assert_eq!( + EmissionSuppressionVote::<Test>::get(sn1, new_coldkey), + Some(true) + ); + // Old coldkey should have no vote. + assert_eq!(EmissionSuppressionVote::<Test>::get(sn1, old_coldkey), None); + }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Test 11: Dissolve subnet → votes + suppression cleaned +// ───────────────────────────────────────────────────────────────────────────── +#[test] +fn test_dissolution_clears_all() { + new_test_ext(1).execute_with(|| { + add_network(NetUid::ROOT, 1, 0); + let sn1 = NetUid::from(1); + setup_subnet_with_flow(sn1, 10, 100_000_000); + + let (_hotkey, coldkey) = setup_root_validator(10, 11, 1_000_000); + + // Vote and set suppression. + assert_ok!(SubtensorModule::vote_emission_suppression( + RuntimeOrigin::signed(coldkey), + sn1, + Some(true), + )); + EmissionSuppression::<Test>::insert(sn1, U64F64::from_num(0.8)); + EmissionSuppressionOverride::<Test>::insert(sn1, true); + + // Remove the network. + SubtensorModule::remove_network(sn1); + + // Everything should be cleaned up. + assert_eq!(EmissionSuppression::<Test>::get(sn1), U64F64::from_num(0)); + assert_eq!(EmissionSuppressionOverride::<Test>::get(sn1), None); + assert_eq!(EmissionSuppressionVote::<Test>::get(sn1, coldkey), None); + }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Test 12: 3 subnets, suppress 1 → others sum to 1.0 +// ───────────────────────────────────────────────────────────────────────────── +#[test] +fn test_shares_renormalize() { + new_test_ext(1).execute_with(|| { + let sn1 = NetUid::from(1); + let sn2 = NetUid::from(2); + let sn3 = NetUid::from(3); + setup_subnet_with_flow(sn1, 10, 100_000_000); + setup_subnet_with_flow(sn2, 10, 200_000_000); + setup_subnet_with_flow(sn3, 10, 300_000_000); + + // Suppress sn2. + EmissionSuppression::<Test>::insert(sn2, U64F64::from_num(0.9)); + + let mut shares = SubtensorModule::get_shares(&[sn1, sn2, sn3]); + SubtensorModule::apply_emission_suppression(&mut shares); + + // sn2 should be 0. + assert_eq!( + shares.get(&sn2).copied().unwrap_or(U64F64::from_num(0)), + U64F64::from_num(0) + ); + + // Remaining shares should sum to ~1.0. + let sum: U64F64 = shares + .values() + .copied() + .fold(U64F64::from_num(0), |a, b| a.saturating_add(b)); + let sum_f64: f64 = sum.to_num(); + assert!( + (sum_f64 - 1.0).abs() < 1e-9, + "shares should sum to 1.0, got {sum_f64}" + ); + }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Test 13: Extra unstaked TAO → no effect on suppression fraction +// ───────────────────────────────────────────────────────────────────────────── +#[test] +fn test_unstaked_tao_not_in_denominator() { + new_test_ext(1).execute_with(|| { + add_network(NetUid::ROOT, 1, 0); + let sn1 = NetUid::from(1); + setup_subnet_with_flow(sn1, 10, 100_000_000); + + // Two root validators: one votes suppress, one doesn't. + let (_hk1, ck1) = setup_root_validator(10, 11, 1_000_000); + let (_hk2, _ck2) = setup_root_validator(20, 21, 1_000_000); + + // Only ck1 votes to suppress. + assert_ok!(SubtensorModule::vote_emission_suppression( + RuntimeOrigin::signed(ck1), + sn1, + Some(true), + )); + + // Collect votes. + SubtensorModule::collect_emission_suppression_votes(sn1); + + // Suppression should be 0.5 (1M / 2M). + let suppression: f64 = EmissionSuppression::<Test>::get(sn1).to_num(); + assert!( + (suppression - 0.5).abs() < 1e-6, + "suppression should be 0.5, got {suppression}" + ); + + // Adding free balance (unstaked TAO) to some account should NOT affect denominator. + let random_account = U256::from(999); + SubtensorModule::add_balance_to_coldkey_account(&random_account, 100_000_000_000); + + // Re-collect. + SubtensorModule::collect_emission_suppression_votes(sn1); + let suppression2: f64 = EmissionSuppression::<Test>::get(sn1).to_num(); + assert!( + (suppression2 - 0.5).abs() < 1e-6, + "suppression should still be 0.5 after adding unstaked TAO, got {suppression2}" + ); + }); +} + +/// Helper: set up root + subnet with proper SubnetTAO and alpha issuance +/// so that root_proportion returns a meaningful nonzero value. +fn setup_root_with_tao(sn: NetUid) { + // Set SubnetTAO for root so root_proportion numerator is nonzero. + SubnetTAO::<Test>::insert(NetUid::ROOT, TaoCurrency::from(1_000_000_000)); + // Set alpha issuance for subnet so denominator is meaningful. + SubnetAlphaOut::<Test>::insert(sn, AlphaCurrency::from(1_000_000_000)); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Test 14: Suppress subnet, Enable mode → root still gets alpha +// ───────────────────────────────────────────────────────────────────────────── +#[test] +fn test_suppressed_subnet_root_alpha_by_default() { + new_test_ext(1).execute_with(|| { + add_network(NetUid::ROOT, 1, 0); + let sn1 = NetUid::from(1); + setup_subnet_with_flow(sn1, 10, 100_000_000); + + // Register a root validator and add stake on root so root_proportion > 0. + let hotkey = U256::from(10); + let coldkey = U256::from(11); + assert_ok!(SubtensorModule::root_register( + RuntimeOrigin::signed(coldkey), + hotkey, + )); + SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( + &hotkey, + &coldkey, + NetUid::ROOT, + 1_000_000_000u64.into(), + ); + // Set TAO weight so root_proportion is nonzero. + SubtensorModule::set_tao_weight(u64::MAX); + setup_root_with_tao(sn1); + + // Force-suppress sn1. + EmissionSuppressionOverride::<Test>::insert(sn1, true); + + // Default mode is Recycle; verify that, then set to Enable for this test. + assert_eq!( + KeepRootSellPressureOnSuppressedSubnets::<Test>::get(), + RootSellPressureOnSuppressedSubnetsMode::Recycle, + ); + KeepRootSellPressureOnSuppressedSubnets::<Test>::put( + RootSellPressureOnSuppressedSubnetsMode::Enable, + ); + + // Clear any pending emissions. + PendingRootAlphaDivs::<Test>::insert(sn1, AlphaCurrency::ZERO); + + // Build emission map with some emission for sn1. + let mut subnet_emissions = BTreeMap::new(); + subnet_emissions.insert(sn1, U96F32::from_num(1_000_000)); + + SubtensorModule::emit_to_subnets(&[sn1], &subnet_emissions, true); + + // Root should have received some alpha (pending root alpha divs > 0). + let pending_root = PendingRootAlphaDivs::<Test>::get(sn1); + assert!( + pending_root > AlphaCurrency::ZERO, + "with Enable mode, root should still get alpha on suppressed subnet" + ); + }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Test 15: Suppress subnet, Disable mode → root gets no alpha, validators get more +// ───────────────────────────────────────────────────────────────────────────── +#[test] +fn test_suppressed_subnet_no_root_alpha_flag_off() { + new_test_ext(1).execute_with(|| { + add_network(NetUid::ROOT, 1, 0); + let sn1 = NetUid::from(1); + setup_subnet_with_flow(sn1, 10, 100_000_000); + + // Register a root validator and add stake on root so root_proportion > 0. + let hotkey = U256::from(10); + let coldkey = U256::from(11); + assert_ok!(SubtensorModule::root_register( + RuntimeOrigin::signed(coldkey), + hotkey, + )); + SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( + &hotkey, + &coldkey, + NetUid::ROOT, + 1_000_000_000u64.into(), + ); + SubtensorModule::set_tao_weight(u64::MAX); + setup_root_with_tao(sn1); + + // Force-suppress sn1. + EmissionSuppressionOverride::<Test>::insert(sn1, true); + + // Set mode to Disable: no root sell pressure on suppressed subnets. + KeepRootSellPressureOnSuppressedSubnets::<Test>::put( + RootSellPressureOnSuppressedSubnetsMode::Disable, + ); + + // Clear any pending emissions. + PendingRootAlphaDivs::<Test>::insert(sn1, AlphaCurrency::ZERO); + PendingValidatorEmission::<Test>::insert(sn1, AlphaCurrency::ZERO); + + // Build emission map. + let mut subnet_emissions = BTreeMap::new(); + subnet_emissions.insert(sn1, U96F32::from_num(1_000_000)); + + SubtensorModule::emit_to_subnets(&[sn1], &subnet_emissions, true); + + // Root should get NO alpha. + let pending_root = PendingRootAlphaDivs::<Test>::get(sn1); + assert_eq!( + pending_root, + AlphaCurrency::ZERO, + "with Disable mode, root should get no alpha on suppressed subnet" + ); + + // Validator emission should be non-zero (root alpha recycled to validators). + let pending_validator = PendingValidatorEmission::<Test>::get(sn1); + assert!( + pending_validator > AlphaCurrency::ZERO, + "validators should receive recycled root alpha" + ); + }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Test 15b: Disable mode actually recycles root alpha to validators +// (validators get more than with Enable mode) +// ───────────────────────────────────────────────────────────────────────────── +#[test] +fn test_disable_mode_recycles_root_alpha_to_validators() { + new_test_ext(1).execute_with(|| { + add_network(NetUid::ROOT, 1, 0); + let sn1 = NetUid::from(1); + setup_subnet_with_flow(sn1, 10, 100_000_000); + + let hotkey = U256::from(10); + let coldkey = U256::from(11); + assert_ok!(SubtensorModule::root_register( + RuntimeOrigin::signed(coldkey), + hotkey, + )); + SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( + &hotkey, + &coldkey, + NetUid::ROOT, + 1_000_000_000u64.into(), + ); + SubtensorModule::set_tao_weight(u64::MAX); + setup_root_with_tao(sn1); + + // Force-suppress sn1. + EmissionSuppressionOverride::<Test>::insert(sn1, true); + + let mut subnet_emissions = BTreeMap::new(); + subnet_emissions.insert(sn1, U96F32::from_num(1_000_000)); + + // ── Run with Enable mode first to get baseline ── + KeepRootSellPressureOnSuppressedSubnets::<Test>::put( + RootSellPressureOnSuppressedSubnetsMode::Enable, + ); + PendingRootAlphaDivs::<Test>::insert(sn1, AlphaCurrency::ZERO); + PendingValidatorEmission::<Test>::insert(sn1, AlphaCurrency::ZERO); + + SubtensorModule::emit_to_subnets(&[sn1], &subnet_emissions, true); + + let enable_validator = PendingValidatorEmission::<Test>::get(sn1); + let enable_root = PendingRootAlphaDivs::<Test>::get(sn1); + + // In Enable mode, root should accumulate some alpha. + assert!( + enable_root > AlphaCurrency::ZERO, + "Enable mode: root should get alpha" + ); + + // ── Now run with Disable mode ── + KeepRootSellPressureOnSuppressedSubnets::<Test>::put( + RootSellPressureOnSuppressedSubnetsMode::Disable, + ); + PendingRootAlphaDivs::<Test>::insert(sn1, AlphaCurrency::ZERO); + PendingValidatorEmission::<Test>::insert(sn1, AlphaCurrency::ZERO); + + SubtensorModule::emit_to_subnets(&[sn1], &subnet_emissions, true); + + let disable_validator = PendingValidatorEmission::<Test>::get(sn1); + let disable_root = PendingRootAlphaDivs::<Test>::get(sn1); + + // In Disable mode, root should get nothing. + assert_eq!( + disable_root, + AlphaCurrency::ZERO, + "Disable mode: root should get no alpha" + ); + + // Disable validators should get MORE than Enable validators because + // root alpha is recycled to them instead of going to root. + assert!( + disable_validator > enable_validator, + "Disable mode validators ({disable_validator:?}) should get more \ + than Enable mode ({enable_validator:?}) because root alpha is recycled" + ); + + // The difference should equal the root alpha from Enable mode + // (root alpha is recycled to validators instead). + assert_eq!( + disable_validator.saturating_sub(enable_validator), + enable_root, + "difference should equal the root alpha that was recycled" + ); + }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Test 16: Non-suppressed subnet → root alpha normal regardless of mode +// ───────────────────────────────────────────────────────────────────────────── +#[test] +fn test_unsuppressed_subnet_unaffected_by_flag() { + new_test_ext(1).execute_with(|| { + add_network(NetUid::ROOT, 1, 0); + let sn1 = NetUid::from(1); + setup_subnet_with_flow(sn1, 10, 100_000_000); + + let hotkey = U256::from(10); + let coldkey = U256::from(11); + assert_ok!(SubtensorModule::root_register( + RuntimeOrigin::signed(coldkey), + hotkey, + )); + SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( + &hotkey, + &coldkey, + NetUid::ROOT, + 1_000_000_000u64.into(), + ); + SubtensorModule::set_tao_weight(u64::MAX); + setup_root_with_tao(sn1); + + // sn1 is NOT suppressed. + // Set mode to Disable (should not matter for unsuppressed subnets). + KeepRootSellPressureOnSuppressedSubnets::<Test>::put( + RootSellPressureOnSuppressedSubnetsMode::Disable, + ); + + PendingRootAlphaDivs::<Test>::insert(sn1, AlphaCurrency::ZERO); + + let mut subnet_emissions = BTreeMap::new(); + subnet_emissions.insert(sn1, U96F32::from_num(1_000_000)); + + SubtensorModule::emit_to_subnets(&[sn1], &subnet_emissions, true); + + // Root should still get alpha since subnet is not suppressed. + let pending_root = PendingRootAlphaDivs::<Test>::get(sn1); + assert!( + pending_root > AlphaCurrency::ZERO, + "non-suppressed subnet should still give root alpha regardless of mode" + ); + }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Test 17: Voting on root subnet returns CannotVoteOnRootSubnet +// ───────────────────────────────────────────────────────────────────────────── +#[test] +fn test_vote_on_root_subnet_rejected() { + new_test_ext(1).execute_with(|| { + add_network(NetUid::ROOT, 1, 0); + let sn1 = NetUid::from(1); + setup_subnet_with_flow(sn1, 10, 100_000_000); + + let (_hk, ck) = setup_root_validator(10, 11, 1_000_000); + + assert_err!( + SubtensorModule::vote_emission_suppression( + RuntimeOrigin::signed(ck), + NetUid::ROOT, + Some(true), + ), + Error::<Test>::CannotVoteOnRootSubnet + ); + }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Test 18: Some(false) vote is stored and treated as no-suppress weight +// ───────────────────────────────────────────────────────────────────────────── +#[test] +fn test_vote_explicit_false() { + new_test_ext(1).execute_with(|| { + add_network(NetUid::ROOT, 1, 0); + let sn1 = NetUid::from(1); + setup_subnet_with_flow(sn1, 10, 100_000_000); + + // Single root validator votes Some(false). + let (_hk, ck) = setup_root_validator(10, 11, 1_000_000); + + assert_ok!(SubtensorModule::vote_emission_suppression( + RuntimeOrigin::signed(ck), + sn1, + Some(false), + )); + assert_eq!(EmissionSuppressionVote::<Test>::get(sn1, ck), Some(false)); + + // Collect votes: sole validator voted false → suppression should be 0. + SubtensorModule::collect_emission_suppression_votes(sn1); + let suppression: f64 = EmissionSuppression::<Test>::get(sn1).to_num(); + assert!( + suppression.abs() < 1e-9, + "explicit false vote should produce 0 suppression, got {suppression}" + ); + }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Test 19: All subnets suppressed → all zeroed, no panic +// ───────────────────────────────────────────────────────────────────────────── +#[test] +fn test_all_subnets_suppressed() { + new_test_ext(1).execute_with(|| { + let sn1 = NetUid::from(1); + let sn2 = NetUid::from(2); + setup_subnet_with_flow(sn1, 10, 100_000_000); + setup_subnet_with_flow(sn2, 10, 100_000_000); + + // Suppress both. + EmissionSuppression::<Test>::insert(sn1, U64F64::from_num(0.9)); + EmissionSuppression::<Test>::insert(sn2, U64F64::from_num(0.8)); + + let mut shares = SubtensorModule::get_shares(&[sn1, sn2]); + SubtensorModule::apply_emission_suppression(&mut shares); + + // Both should be zero. + let s1 = shares.get(&sn1).copied().unwrap_or(U64F64::from_num(0)); + let s2 = shares.get(&sn2).copied().unwrap_or(U64F64::from_num(0)); + assert_eq!(s1, U64F64::from_num(0)); + assert_eq!(s2, U64F64::from_num(0)); + + // Total emission via get_subnet_block_emissions should be zero. + let emissions = + SubtensorModule::get_subnet_block_emissions(&[sn1, sn2], U96F32::from_num(1_000_000)); + let total: u64 = emissions + .values() + .map(|e| e.saturating_to_num::<u64>()) + .fold(0u64, |a, b| a.saturating_add(b)); + assert_eq!(total, 0, "all-suppressed should yield zero total emission"); + }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Test 20: Coldkey swap blocked by existing votes on destination +// ───────────────────────────────────────────────────────────────────────────── +#[test] +fn test_coldkey_swap_blocked_by_existing_votes() { + new_test_ext(1).execute_with(|| { + add_network(NetUid::ROOT, 1, 0); + let sn1 = NetUid::from(1); + setup_subnet_with_flow(sn1, 10, 100_000_000); + + // Set up old coldkey with a vote. + let (_hk_old, old_ck) = setup_root_validator(10, 11, 1_000_000); + assert_ok!(SubtensorModule::vote_emission_suppression( + RuntimeOrigin::signed(old_ck), + sn1, + Some(true), + )); + + // Set up new coldkey that already has a vote via direct storage insert. + let new_ck = U256::from(999); + EmissionSuppressionVote::<Test>::insert(sn1, new_ck, false); + + // Swap should fail. + assert_err!( + SubtensorModule::do_swap_coldkey(&old_ck, &new_ck), + Error::<Test>::DestinationColdkeyHasExistingVotes + ); + + // Old coldkey's vote should still be intact (no partial state change). + assert_eq!( + EmissionSuppressionVote::<Test>::get(sn1, old_ck), + Some(true) + ); + }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Test 21: Coldkey with multiple root hotkeys → vote weight = sum of stakes +// ───────────────────────────────────────────────────────────────────────────── +#[test] +fn test_multi_hotkey_coldkey_vote_weight() { + new_test_ext(1).execute_with(|| { + add_network(NetUid::ROOT, 1, 0); + let sn1 = NetUid::from(1); + setup_subnet_with_flow(sn1, 10, 100_000_000); + + let coldkey = U256::from(100); + let hk1 = U256::from(1); + let hk2 = U256::from(2); + let hk3 = U256::from(3); + + // Register all 3 hotkeys on root under the same coldkey. + assert_ok!(SubtensorModule::root_register( + RuntimeOrigin::signed(coldkey), + hk1, + )); + assert_ok!(SubtensorModule::root_register( + RuntimeOrigin::signed(coldkey), + hk2, + )); + assert_ok!(SubtensorModule::root_register( + RuntimeOrigin::signed(coldkey), + hk3, + )); + + // Stake: hk1=100, hk2=200, hk3=300 → total root stake = 600. + SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( + &hk1, + &coldkey, + NetUid::ROOT, + 100u64.into(), + ); + SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( + &hk2, + &coldkey, + NetUid::ROOT, + 200u64.into(), + ); + SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( + &hk3, + &coldkey, + NetUid::ROOT, + 300u64.into(), + ); + + // Vote to suppress. + assert_ok!(SubtensorModule::vote_emission_suppression( + RuntimeOrigin::signed(coldkey), + sn1, + Some(true), + )); + + // Collect votes. Only coldkey's hotkeys exist on root, + // and all stakes belong to the suppressing coldkey. + SubtensorModule::collect_emission_suppression_votes(sn1); + + // Suppression should be 1.0 (all stake voted suppress). + let suppression: f64 = EmissionSuppression::<Test>::get(sn1).to_num(); + assert!( + (suppression - 1.0).abs() < 1e-6, + "suppression should be 1.0 when all root stake votes suppress, got {suppression}" + ); + }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Test 22: sudo_set_emission_suppression_override emits event +// ───────────────────────────────────────────────────────────────────────────── +#[test] +fn test_sudo_override_emits_event() { + new_test_ext(1).execute_with(|| { + let sn1 = NetUid::from(1); + setup_subnet_with_flow(sn1, 10, 100_000_000); + + System::set_block_number(1); + System::reset_events(); + + assert_ok!(SubtensorModule::sudo_set_emission_suppression_override( + RuntimeOrigin::root(), + sn1, + Some(true), + )); + + assert!( + System::events().iter().any(|e| { + matches!( + &e.event, + RuntimeEvent::SubtensorModule( + Event::EmissionSuppressionOverrideSet { netuid, override_value } + ) if *netuid == sn1 && *override_value == Some(true) + ) + }), + "should emit EmissionSuppressionOverrideSet event" + ); + }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Test 23: sudo_set_root_sell_pressure_on_suppressed_subnets_mode emits event +// ───────────────────────────────────────────────────────────────────────────── +#[test] +fn test_sudo_sell_pressure_emits_event() { + new_test_ext(1).execute_with(|| { + System::set_block_number(1); + System::reset_events(); + + assert_ok!( + SubtensorModule::sudo_set_root_sell_pressure_on_suppressed_subnets_mode( + RuntimeOrigin::root(), + RootSellPressureOnSuppressedSubnetsMode::Disable, + ) + ); + + assert!( + System::events().iter().any(|e| { + matches!( + &e.event, + RuntimeEvent::SubtensorModule( + Event::RootSellPressureOnSuppressedSubnetsModeSet { mode } + ) if *mode == RootSellPressureOnSuppressedSubnetsMode::Disable + ) + }), + "should emit RootSellPressureOnSuppressedSubnetsModeSet event" + ); + }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Test 24: collect_emission_suppression_votes(ROOT) is a no-op +// ───────────────────────────────────────────────────────────────────────────── +#[test] +fn test_collect_votes_skips_root() { + new_test_ext(1).execute_with(|| { + add_network(NetUid::ROOT, 1, 0); + + // Ensure no EmissionSuppression entry for ROOT. + assert_eq!( + EmissionSuppression::<Test>::get(NetUid::ROOT), + U64F64::from_num(0) + ); + + // Call collect on ROOT — should be a no-op. + SubtensorModule::collect_emission_suppression_votes(NetUid::ROOT); + + // Still no entry. + assert_eq!( + EmissionSuppression::<Test>::get(NetUid::ROOT), + U64F64::from_num(0) + ); + }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Test 25: default mode is Recycle +// ───────────────────────────────────────────────────────────────────────────── +#[test] +fn test_default_mode_is_recycle() { + new_test_ext(1).execute_with(|| { + assert_eq!( + KeepRootSellPressureOnSuppressedSubnets::<Test>::get(), + RootSellPressureOnSuppressedSubnetsMode::Recycle, + ); + }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Test 26: Recycle mode, suppressed subnet → alpha swapped to TAO, TAO burned +// ───────────────────────────────────────────────────────────────────────────── +#[test] +fn test_recycle_mode_suppressed_subnet_swaps_and_recycles() { + new_test_ext(1).execute_with(|| { + add_network(NetUid::ROOT, 1, 0); + // Use add_dynamic_network to properly initialize the AMM. + let owner_hk = U256::from(50); + let owner_ck = U256::from(51); + let sn1 = add_dynamic_network(&owner_hk, &owner_ck); + + // Seed the pool with TAO and alpha reserves. + let initial_tao = TaoCurrency::from(500_000_000u64); + let initial_alpha_in = AlphaCurrency::from(500_000_000u64); + SubnetTAO::<Test>::insert(sn1, initial_tao); + SubnetAlphaIn::<Test>::insert(sn1, initial_alpha_in); + SubnetTaoFlow::<Test>::insert(sn1, 100_000_000i64); + + // Also set root TAO so root_proportion is nonzero. + SubnetTAO::<Test>::insert(NetUid::ROOT, TaoCurrency::from(1_000_000_000)); + SubnetAlphaOut::<Test>::insert(sn1, AlphaCurrency::from(1_000_000_000)); + + // Register a root validator. + let hotkey = U256::from(10); + let coldkey = U256::from(11); + assert_ok!(SubtensorModule::root_register( + RuntimeOrigin::signed(coldkey), + hotkey, + )); + SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( + &hotkey, + &coldkey, + NetUid::ROOT, + 1_000_000_000u64.into(), + ); + SubtensorModule::set_tao_weight(u64::MAX); + + // Force-suppress sn1. + EmissionSuppressionOverride::<Test>::insert(sn1, true); + + // Default mode is Recycle. + assert_eq!( + KeepRootSellPressureOnSuppressedSubnets::<Test>::get(), + RootSellPressureOnSuppressedSubnetsMode::Recycle, + ); + + // Record TotalIssuance before emission. + let issuance_before = TotalIssuance::<Test>::get(); + + // Clear pending. + PendingRootAlphaDivs::<Test>::insert(sn1, AlphaCurrency::ZERO); + + // Build emission map. + let mut subnet_emissions = BTreeMap::new(); + subnet_emissions.insert(sn1, U96F32::from_num(1_000_000)); + + SubtensorModule::emit_to_subnets(&[sn1], &subnet_emissions, true); + + // PendingRootAlphaDivs should be 0 (root did NOT accumulate alpha). + let pending_root = PendingRootAlphaDivs::<Test>::get(sn1); + assert_eq!( + pending_root, + AlphaCurrency::ZERO, + "in Recycle mode, PendingRootAlphaDivs should be 0" + ); + + // SubnetAlphaIn should have increased (alpha was swapped into pool). + let alpha_in_after = SubnetAlphaIn::<Test>::get(sn1); + assert!( + alpha_in_after > initial_alpha_in, + "SubnetAlphaIn should increase after swap" + ); + + // TotalIssuance should have decreased (TAO was recycled/burned). + let issuance_after = TotalIssuance::<Test>::get(); + assert!( + issuance_after < issuance_before, + "TotalIssuance should decrease (TAO recycled)" + ); + }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Test 27: Recycle mode on non-suppressed subnet → normal PendingRootAlphaDivs +// ───────────────────────────────────────────────────────────────────────────── +#[test] +fn test_recycle_mode_non_suppressed_subnet_normal() { + new_test_ext(1).execute_with(|| { + add_network(NetUid::ROOT, 1, 0); + let sn1 = NetUid::from(1); + setup_subnet_with_flow(sn1, 10, 100_000_000); + + let hotkey = U256::from(10); + let coldkey = U256::from(11); + assert_ok!(SubtensorModule::root_register( + RuntimeOrigin::signed(coldkey), + hotkey, + )); + SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( + &hotkey, + &coldkey, + NetUid::ROOT, + 1_000_000_000u64.into(), + ); + SubtensorModule::set_tao_weight(u64::MAX); + setup_root_with_tao(sn1); + + // sn1 is NOT suppressed. Mode is Recycle (default). + assert_eq!( + KeepRootSellPressureOnSuppressedSubnets::<Test>::get(), + RootSellPressureOnSuppressedSubnetsMode::Recycle, + ); + + PendingRootAlphaDivs::<Test>::insert(sn1, AlphaCurrency::ZERO); + + let mut subnet_emissions = BTreeMap::new(); + subnet_emissions.insert(sn1, U96F32::from_num(1_000_000)); + + SubtensorModule::emit_to_subnets(&[sn1], &subnet_emissions, true); + + // Root should still get alpha — Recycle only affects suppressed subnets. + let pending_root = PendingRootAlphaDivs::<Test>::get(sn1); + assert!( + pending_root > AlphaCurrency::ZERO, + "non-suppressed subnet should still give root alpha in Recycle mode" + ); + }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Test 28: Recycle mode ignores RootClaimType (alpha never enters claim flow) +// ───────────────────────────────────────────────────────────────────────────── +#[test] +fn test_recycle_mode_ignores_root_claim_type() { + new_test_ext(1).execute_with(|| { + add_network(NetUid::ROOT, 1, 0); + // Use add_dynamic_network to properly initialize the AMM. + let owner_hk = U256::from(50); + let owner_ck = U256::from(51); + let sn1 = add_dynamic_network(&owner_hk, &owner_ck); + + SubnetTAO::<Test>::insert(sn1, TaoCurrency::from(500_000_000u64)); + SubnetAlphaIn::<Test>::insert(sn1, AlphaCurrency::from(500_000_000u64)); + SubnetTaoFlow::<Test>::insert(sn1, 100_000_000i64); + SubnetTAO::<Test>::insert(NetUid::ROOT, TaoCurrency::from(1_000_000_000)); + SubnetAlphaOut::<Test>::insert(sn1, AlphaCurrency::from(1_000_000_000)); + + let hotkey = U256::from(10); + let coldkey = U256::from(11); + assert_ok!(SubtensorModule::root_register( + RuntimeOrigin::signed(coldkey), + hotkey, + )); + SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( + &hotkey, + &coldkey, + NetUid::ROOT, + 1_000_000_000u64.into(), + ); + SubtensorModule::set_tao_weight(u64::MAX); + + // Force-suppress sn1. + EmissionSuppressionOverride::<Test>::insert(sn1, true); + + // Set RootClaimType to Keep — in normal flow this would keep alpha. + // But Recycle mode should override and swap+burn regardless. + RootClaimType::<Test>::insert(coldkey, RootClaimTypeEnum::Keep); + + // Default mode is Recycle. + assert_eq!( + KeepRootSellPressureOnSuppressedSubnets::<Test>::get(), + RootSellPressureOnSuppressedSubnetsMode::Recycle, + ); + + PendingRootAlphaDivs::<Test>::insert(sn1, AlphaCurrency::ZERO); + + let issuance_before = TotalIssuance::<Test>::get(); + + let mut subnet_emissions = BTreeMap::new(); + subnet_emissions.insert(sn1, U96F32::from_num(1_000_000)); + + SubtensorModule::emit_to_subnets(&[sn1], &subnet_emissions, true); + + // PendingRootAlphaDivs should still be 0 (recycled, not claimed). + let pending_root = PendingRootAlphaDivs::<Test>::get(sn1); + assert_eq!( + pending_root, + AlphaCurrency::ZERO, + "Recycle mode should swap+burn regardless of RootClaimType" + ); + + // TAO was burned. + let issuance_after = TotalIssuance::<Test>::get(); + assert!( + issuance_after < issuance_before, + "TotalIssuance should decrease even with RootClaimType::Keep" + ); + }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Test 29: sudo_set_mode all 3 variants emit events +// ───────────────────────────────────────────────────────────────────────────── +#[test] +fn test_sudo_set_mode_all_variants_emit_events() { + new_test_ext(1).execute_with(|| { + System::set_block_number(1); + + for mode in [ + RootSellPressureOnSuppressedSubnetsMode::Disable, + RootSellPressureOnSuppressedSubnetsMode::Enable, + RootSellPressureOnSuppressedSubnetsMode::Recycle, + ] { + System::reset_events(); + + assert_ok!( + SubtensorModule::sudo_set_root_sell_pressure_on_suppressed_subnets_mode( + RuntimeOrigin::root(), + mode, + ) + ); + + assert_eq!(KeepRootSellPressureOnSuppressedSubnets::<Test>::get(), mode,); + + assert!( + System::events().iter().any(|e| { + matches!( + &e.event, + RuntimeEvent::SubtensorModule( + Event::RootSellPressureOnSuppressedSubnetsModeSet { mode: m } + ) if *m == mode + ) + }), + "should emit RootSellPressureOnSuppressedSubnetsModeSet for {mode:?}" + ); + } + }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Test 30: Recycle mode decreases price and flow EMA; Disable/Enable do not +// ───────────────────────────────────────────────────────────────────────────── +#[test] +fn test_recycle_mode_decreases_price_and_flow_ema() { + new_test_ext(1).execute_with(|| { + add_network(NetUid::ROOT, 1, 0); + // Use add_dynamic_network to properly initialize the AMM. + let owner_hk = U256::from(50); + let owner_ck = U256::from(51); + let sn1 = add_dynamic_network(&owner_hk, &owner_ck); + + // Large pool reserves to ensure swaps produce measurable effects. + let pool_reserve = 1_000_000_000u64; + SubnetTAO::<Test>::insert(sn1, TaoCurrency::from(pool_reserve)); + SubnetAlphaIn::<Test>::insert(sn1, AlphaCurrency::from(pool_reserve)); + SubnetTAO::<Test>::insert(NetUid::ROOT, TaoCurrency::from(pool_reserve)); + SubnetAlphaOut::<Test>::insert(sn1, AlphaCurrency::from(pool_reserve)); + SubnetTaoFlow::<Test>::insert(sn1, 100_000_000i64); + + let hotkey = U256::from(10); + let coldkey = U256::from(11); + assert_ok!(SubtensorModule::root_register( + RuntimeOrigin::signed(coldkey), + hotkey, + )); + SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( + &hotkey, + &coldkey, + NetUid::ROOT, + 1_000_000_000u64.into(), + ); + SubtensorModule::set_tao_weight(u64::MAX); + + // Force-suppress sn1. + EmissionSuppressionOverride::<Test>::insert(sn1, true); + + let emission_amount = U96F32::from_num(10_000_000); + let mut subnet_emissions = BTreeMap::new(); + subnet_emissions.insert(sn1, emission_amount); + + // ── First: verify that Disable and Enable modes do NOT cause TAO outflow ── + + for mode in [ + RootSellPressureOnSuppressedSubnetsMode::Disable, + RootSellPressureOnSuppressedSubnetsMode::Enable, + ] { + // Reset pool state. + SubnetTAO::<Test>::insert(sn1, TaoCurrency::from(pool_reserve)); + SubnetAlphaIn::<Test>::insert(sn1, AlphaCurrency::from(pool_reserve)); + SubnetTaoFlow::<Test>::insert(sn1, 0i64); + PendingRootAlphaDivs::<Test>::insert(sn1, AlphaCurrency::ZERO); + SubnetAlphaOut::<Test>::insert(sn1, AlphaCurrency::from(pool_reserve)); + + KeepRootSellPressureOnSuppressedSubnets::<Test>::put(mode); + + SubtensorModule::emit_to_subnets(&[sn1], &subnet_emissions, true); + + let flow = SubnetTaoFlow::<Test>::get(sn1); + assert!( + flow >= 0, + "mode {mode:?}: SubnetTaoFlow should not be negative, got {flow}" + ); + } + + // ── Now: verify that Recycle mode DOES cause TAO outflow ── + + // Reset pool state. + SubnetTAO::<Test>::insert(sn1, TaoCurrency::from(pool_reserve)); + SubnetAlphaIn::<Test>::insert(sn1, AlphaCurrency::from(pool_reserve)); + SubnetTaoFlow::<Test>::insert(sn1, 0i64); + PendingRootAlphaDivs::<Test>::insert(sn1, AlphaCurrency::ZERO); + SubnetAlphaOut::<Test>::insert(sn1, AlphaCurrency::from(pool_reserve)); + + // Set Recycle mode. + KeepRootSellPressureOnSuppressedSubnets::<Test>::put( + RootSellPressureOnSuppressedSubnetsMode::Recycle, + ); + + // Record TAO reserve before. + let tao_before = SubnetTAO::<Test>::get(sn1); + + SubtensorModule::emit_to_subnets(&[sn1], &subnet_emissions, true); + + // SubnetTaoFlow should be negative (TAO left the pool via swap). + let flow_after = SubnetTaoFlow::<Test>::get(sn1); + assert!( + flow_after < 0, + "Recycle mode: SubnetTaoFlow should be negative (TAO outflow), got {flow_after}" + ); + + // SubnetTAO should have decreased (TAO left the pool in the swap). + // Note: emit_to_subnets injects some TAO via inject_and_maybe_swap, + // but the swap_alpha_for_tao pulls TAO back out. The net flow recorded + // as negative proves outflow dominated. + let tao_after = SubnetTAO::<Test>::get(sn1); + assert!( + tao_after < tao_before, + "Recycle mode: SubnetTAO should decrease (TAO outflow), before={tao_before:?} after={tao_after:?}" + ); + }); +} diff --git a/pallets/subtensor/src/tests/mod.rs b/pallets/subtensor/src/tests/mod.rs index 8f07572e25..6402bd6b31 100644 --- a/pallets/subtensor/src/tests/mod.rs +++ b/pallets/subtensor/src/tests/mod.rs @@ -7,6 +7,7 @@ mod consensus; mod delegate_info; mod difficulty; mod emission; +mod emission_suppression; mod ensure; mod epoch; mod epoch_logs;