#![cfg_attr(not(feature = "std"), no_std)] #![recursion_limit = "512"] #![allow(clippy::too_many_arguments)] #![allow(clippy::zero_prefixed_literal)] // Edit this file to define custom logic or remove it if it is not needed. // Learn more about FRAME and the core library of Substrate FRAME pallets: // use frame_system::{self as system, ensure_signed}; pub use pallet::*; use codec::{Decode, Encode}; use frame_support::{ dispatch::{self, DispatchResult, DispatchResultWithPostInfo}, ensure, pallet_macros::import_section, pallet_prelude::*, traits::tokens::fungible, weights::WeightMeter, }; use scale_info::TypeInfo; use sp_core::Get; use sp_runtime::{DispatchError, PerU16, Perbill}; use sp_std::marker::PhantomData; use subtensor_runtime_common::{AlphaBalance, NetUid, TaoBalance, Token, TokenReserve}; // ============================ // ==== Benchmark Imports ===== // ============================ #[path = "benchmarks/benchmarks.rs"] mod benchmarks; // ========================= // ==== Pallet Imports ===== // ========================= pub mod coinbase; pub mod epoch; pub mod extensions; pub mod guards; pub mod macros; pub mod migrations; pub mod rpc_info; pub mod staking; pub mod subnets; pub mod swap; pub mod utils; pub mod weights; use crate::utils::rate_limiting::{Hyperparameter, TransactionType}; use macros::{config, dispatches, errors, events, genesis, hooks}; pub use extensions::*; pub use guards::*; pub use subnets::emission_weights::{ EMISSION_WEIGHT_ONE, EMISSION_WEIGHT_SLOTS, EMISSION_WEIGHTS_VIEW_READS, EmissionIndex, EmissionSlot, EmissionSplit, EmissionWeights, EmissionWeightsVec, EmissionWeightsView, GammaEmission, MAX_BURN_RECYCLE_EMISSION, MAX_EMISSION_SLOTS, MAX_GAMMA_EMISSION, MAX_GAMMA_SHARES, MAX_OWNER_EMISSION, MAX_VALIDATOR_EMISSION, MIN_MINER_EMISSION, emission_fraction, emission_share_to_parts, normalize_tao_weight, root_emission_share, }; /// Prevent an owner relationship from weakening a hotkey's authorization. /// `allows_coldkey_swap` must preserve the invariant established by /// `allows_owner`: swapping a coldkey must not weaken any of its hotkeys. pub trait HotkeyOwnerPolicy { fn allows_owner(coldkey: &AccountId, hotkey: &AccountId) -> bool; fn allows_coldkey_swap(old: &AccountId, new: &AccountId) -> bool; fn weight() -> Weight; } impl HotkeyOwnerPolicy for () { fn allows_owner(_: &AccountId, _: &AccountId) -> bool { true } fn allows_coldkey_swap(_: &AccountId, _: &AccountId) -> bool { true } fn weight() -> Weight { Weight::zero() } } #[cfg(test)] pub(crate) mod tests; // apparently this is stabilized since rust 1.36 extern crate alloc; pub type OriginFor = ::RuntimeOrigin; /// SCALE bound includes room for a full 4,096-entry encrypted weight row. pub const MAX_CRV3_COMMIT_SIZE_BYTES: u32 = 32 * 1024; pub const YUMA_COMMIT_SIZE_BYTES: u32 = 5000; /// Existing per-hotkey, per-mechanism, per-epoch Yuma timelock admission limit. pub const DEFAULT_MAX_TIMELOCKED_COMMITS_PER_HOTKEY: u8 = 10; /// Bound ciphertext storage and decryption work per Null subnet epoch, /// shared across all emission mechanisms. pub const NULL_COMMIT_QUEUE_BYTES: usize = 64 * 1024; pub const NULL_COMMIT_QUEUE_COUNT: usize = 64; pub const ALPHA_MAP_BATCH_SIZE: usize = 30; /// Maximum bonds moving average allowed for subnet owners. pub const MAX_BONDS_MOVING_AVERAGE: u64 = 975_000; /// Smallest u16 alpha encoding that is not below `1 - MAX_BONDS_MOVING_AVERAGE / 1_000_000`. pub const MIN_ALPHA_LOW: u16 = 1_639; pub const MAX_ROOT_CLAIM_THRESHOLD: u64 = 10_000_000; /// Benchmark and admission ceiling for coldkey-wide root claims and scans /// (`Linear<1, N>`). Weight calculation cannot inspect the signer, so this path /// reserves the full envelope and refunds unused weight after dispatch. pub const MAX_ROOT_CLAIM_WORK: u32 = 256; /// Largest single-hotkey claim, in claim units: one validator, 256 non-root subnet slots, /// and the root/TAO slot. A single-hotkey claim declares the weight of its own fund /// ([`Pallet::root_claim_hotkey_declared_weight_for`]); this is the admission ceiling and /// the size of the largest declaration. A full fund stays claimable while the subnet limit /// is at most this value minus two, so raise both in the same runtime upgrade. pub const MAX_ROOT_CLAIM_HOTKEY_WORK: u32 = 258; /// Smallest single-hotkey claim declaration, in claim units. It is the number of units the /// runtime bills a root claim for (`ROOT_CLAIM_FEE_ALLOWANCE`), so the fee quoted before /// dispatch does not depend on the size of the fund. pub const MIN_ROOT_CLAIM_HOTKEY_WORK: u32 = 4; /// Most times that one transaction counts the rows and the queued credits of one fund for /// the weight of a single-hotkey claim. A transaction counts a fund one time and keeps /// the count ([`BasketRowsCountedAt`]). The first transaction of a block is the exception: /// the block executive computes its weight before it marks the inherents as applied, and /// a count from that moment is not kept. That transaction counts the fund once more. pub const ROOT_CLAIM_HOTKEY_COUNTS: u32 = 2; /// Reads of the kept count and of the same-transaction guard that the weight of one /// single-hotkey claim covers. The weight of the call is computed by the block executive, /// by the fee logic (in validation and in preparation; two times each for a call in a /// batch or a proxy), and by each batch or proxy that holds the call. Each of these is /// one read of the kept count. The claim reads the kept count and the guard one time /// each. A claim in a batch in a proxy makes nine of these reads. Only two of them go to /// the database: the first read of the kept count, and the read of the guard. The others /// find the kept count in the storage overlay of the block, also in a deeper nest. Each /// lookup also reads three values of the system pallet (the inherents flag, the extrinsic /// index and the block number); the block wrote them, so they are in the overlay too. /// /// A hotkey without a fund has no kept count. Each computation of its weight then reads /// that there is no kept count and probes the end of each map of the fund. Its weight has /// those reads this number of times. pub const ROOT_CLAIM_HOTKEY_COUNT_READS: u32 = 10; /// Longest `StakingHotkeys` list a third party may leave behind on a coldkey through /// stake transfers. Half the root-claim admission budget, so a coldkey with up to as many /// hotkeys of its own still passes the coldkey-wide `claim_root` gate. pub const MAX_THIRD_PARTY_STAKING_HOTKEYS: u32 = MAX_ROOT_CLAIM_WORK / 2; /// Longest `StakingHotkeys` list a coldkey may hold in total. Every stake exit walks this /// list (lock and collateral availability), so its length is a weight dimension of every /// unstake-side call; bounding it keeps [`Pallet::staking_hotkeys_walk_bound`] finite. Equal /// to the root-claim admission budget, so any coldkey that can stake can also claim /// coldkey-wide. A coldkey at the cap keeps operating its existing hotkeys and may only add /// a new one after consolidating. pub const MAX_STAKING_HOTKEYS: u32 = MAX_ROOT_CLAIM_WORK; /// Storage reads one `StakingHotkeys` entry costs on an unstake-side call: the position quote /// (legacy and current share rows, pool value, both denominator maps, epoch) taken twice /// (validation and the debit path). pub const STAKING_HOTKEYS_WALK_READS_PER_ENTRY: u64 = 14; /// Most hotkeys (source ∪ destination staking lists plus claim-only basket credits) a /// coldkey swap admits in one call. Sized from the production distribution: the 99.9th /// percentile list is under 100 entries and four coldkeys exceed this value; they /// consolidate before swapping. Merges into an already-used destination count both sides. pub const MAX_COLDKEY_SWAP_HOTKEYS: u32 = MAX_STAKING_HOTKEYS; /// Most stake positions `(hotkey, netuid)` a coldkey swap moves in one call. Each position is /// one `transfer_stake` worth of work; the declared weight reserves this many (about three /// quarters of the normal block budget) and refunds the rest post-dispatch. Four production /// coldkeys exceed it today. pub const MAX_COLDKEY_SWAP_POSITIONS: u32 = 1024; /// Most destination `Lock` rows a coldkey swap may scan/purge. Sized so the /// declared swap envelope still fits the normal-class `max_extrinsic` after /// charging the full per-row admission + re-check + purge + aggregate path /// (independent of source positions). See `coldkey_swap_weight`. pub const MAX_COLDKEY_SWAP_DEST_LOCKS: u32 = 128; /// Most pending network-registration queue rows one coldkey swap rewrites. /// Escrow is updated only via those queue `lock_id`s (no global escrow scan). pub const MAX_COLDKEY_SWAP_PENDING_REGISTRATIONS: u32 = 32; /// Most `NetworkRegistrationQueue` entries a coldkey swap may scan or rewrite. /// The queue is a single unbounded `Vec`; visiting beyond this fails closed so /// work cannot grow with unrelated accounts' registrations outside the weight /// envelope. pub const MAX_COLDKEY_SWAP_REGISTRATION_QUEUE_SCAN: u32 = 256; /// Most subnet legs one `unstake_all` / `unstake_all_alpha` call will validate or /// unstake. Each successful leg is one `remove_stake` plus a [`MAX_STAKING_HOTKEYS`] /// walk (~9.3e10 ref-time at RocksDbWeight). The normal-class `max_extrinsic` is /// 75% of the 4e12 block = 3e12; ~33 uncapped legs already exceed that, so a live /// walk of ~568 subnets cannot be submitted. 16 legs is ~1.5e12 — half the /// normal class — and remaining positions stay for a later call. pub const MAX_UNSTAKE_ALL_LEGS: u32 = 16; /// Default [`BasketConcentrationCap`]: the largest u16-normalized share of a fund's NAV a /// single holding may reach through a `swap_basket` buy. `u16::MAX / 16 + 1` (= 4096) is /// the smallest cap that admits a 16-way equal split, so a traded fund must spread across /// at least 16 holdings. pub const DEFAULT_BASKET_CONCENTRATION_CAP: u16 = u16::MAX / 16 + 1; /// Default [`BasketDailyTurnoverCap`]: the `swap_basket` turnover bucket holds 10% of fund /// NAV (u16-normalized). pub const DEFAULT_BASKET_DAILY_TURNOVER_CAP: u16 = u16::MAX / 10; /// Default [`BasketTradeRefillBlocks`]: an empty `swap_basket` turnover bucket refills /// completely in one day at 12-second blocks. The bucket refills continuously, so at any /// instant at most one full budget can be spent. pub const DEFAULT_BASKET_TRADE_REFILL_BLOCKS: u64 = 7200; /// Legacy test-only spelling retained for protected tests whose arithmetic must not change. /// Runtime code reads [`BasketTradeRefillBlocks`] instead. #[cfg(test)] pub const BASKET_TRADE_REFILL_BLOCKS: u64 = DEFAULT_BASKET_TRADE_REFILL_BLOCKS; /// Most legs accepted by one [`Pallet::swap_basket_many`] call. The call values the /// basket and flushes queued dividends once, then updates the two affected marks after /// each leg. This bound keeps encoded calls plus dispatch and transaction-validation /// weights below the normal-class maximum extrinsic weight. pub const MAX_BASKET_SWAP_LEGS: u32 = 64; /// Default [`BasketLiquidityCap`]: a fund's holding on a subnet may not exceed 10% of that /// subnet's alpha reserve after a `swap_basket` buy (u16-normalized). pub const DEFAULT_BASKET_LIQUIDITY_CAP: u16 = u16::MAX / 10; /// Default [`BasketClaimRowDustCapTao`]: the row-dust floor of a root claim is at most 1 TAO. /// A claim does not sell a fund row whose whole holding is worth less than /// `min(cap, bps × anchored NAV)` at the anchored mark ([`Pallet::anchored_basket_holding_value`]); /// the claimant's slice of such a row stays in the fund for the remaining holders (see /// [`Pallet::root_claim_for_hotkey`]). pub const DEFAULT_BASKET_CLAIM_ROW_DUST_CAP_TAO: u64 = 1_000_000_000; /// Default [`BasketClaimRowDustBps`]: the row-dust floor is 0.1% of the fund's anchored NAV /// (10 basis points), capped at [`DEFAULT_BASKET_CLAIM_ROW_DUST_CAP_TAO`]. Relative so a /// small validator's fund — where every row may be under 1 TAO — still redeems its rows. pub const DEFAULT_BASKET_CLAIM_ROW_DUST_BPS: u16 = 10; /// Default [`BasketClaimSliceDustTao`]: a root claim does not sell a fund row when the /// claimant's own slice of it is worth less than 0.0001 TAO at the anchored mark. The slice /// is forfeited to the fund, so the floor is set where the forfeit is rounding-sized: on /// finney's claim flow it removes about a fifth of the swaps while a median claim leaves /// under 1% of its value behind (a 0.001 TAO floor would remove half the swaps but leave 12%). pub const DEFAULT_BASKET_CLAIM_SLICE_DUST_TAO: u64 = 100_000; /// Default [`BasketClaimForfeitCapTao`]: whatever rule marks a row as dust, a claim skips it /// only if the claimant's own slice of it is worth at most 0.01 TAO at the anchored mark. /// This is the hard bound on what any one skipped slice can leave in the fund; a bigger slice /// of a small row is sold as before. pub const DEFAULT_BASKET_CLAIM_FORFEIT_CAP_TAO: u64 = 10_000_000; /// Default [`BasketTradeMaxSlippageBps`]: preserve the pre-upgrade 2% band around the /// strictest slow-EMA, fast-EMA, and spot reference. Governance can opt into a 5% band /// and [`BasketTradePriceReference::SpotOnly`] separately. /// Applied to the sell leg as a floor and the buy leg as a ceiling via the AMM `price_limit`; /// a leg that cannot fill fully within the bound fails. pub const DEFAULT_BASKET_TRADE_MAX_SLIPPAGE_BPS: u16 = 200; /// Maximum basket NAV impact of out-of-band prices on dividend share minting (0.1%). /// The configured per-pool trade band defines which prices require an anchored comparison. pub const BASKET_DIVIDEND_PRICE_IMPACT_BPS: u64 = 10; /// Gross incoming-dividend and combined mint-ratio impact budget (2%). This preserves /// the existing price-band tolerance at the batch level while allowing small outliers. pub const BASKET_DIVIDEND_MINT_IMPACT_BPS: u64 = 200; /// Half-life, in blocks, of the fast subnet price EMA ([`SubnetFastMovingPrice`]) that /// anchors `swap_basket` price bounds: 600 blocks (about two hours at 12s blocks). Short /// enough that honest trading self-heals after a real price move within hours; long enough /// that pulling the anchor toward a manipulated price requires holding that price — and /// the capital behind it — against arbitrage for several half-lives. pub const BASKET_FAST_EMA_HALF_LIFE_BLOCKS: u64 = 600; pub struct SubtensorDustRemoval(PhantomData); impl frame_support::traits::OnUnbalanced> for SubtensorDustRemoval where T: Config + pallet_balances::Config, ::Balance: Into + Copy, { fn on_nonzero_unbalanced(dust: pallet_balances::CreditOf) { let amount: TaoBalance = frame_support::traits::Imbalance::peek(&dust).into(); TotalIssuance::::mutate(|total| { *total = total.saturating_sub(amount); }); } } /// Maximum number of UIDs (per subnet) that may be associated with a single EVM address. /// /// This bounds the size of the `AssociatedUidsByEvmAddress` reverse-index value, keeping /// `uid_lookup` reads and association writes cheap and their PoV footprint small. Only the /// holder of an EVM key's private key can grow its bucket (each association requires a /// signature from that key), so this only limits how many of one's own UIDs may point at a /// single EVM address. pub const MAX_ASSOCIATED_UIDS_PER_EVM_ADDRESS: u32 = 32; /// Maximum number of distinct hotkeys that may hold miner collateral for one /// coldkey on a single subnet. /// /// Bounds [`ColdkeyCollateralHotkeys`] so coldkey swaps migrate collateral via /// an O(bound) indexed walk instead of scanning unbounded /// `StakingHotkeys` / `OwnedHotkeys` association vectors. pub const MAX_COLDKEY_COLLATERAL_HOTKEYS: u32 = 32; /// Maximum number of gamma deposits one coldkey holds on a single subnet. pub const MAX_GAMMA_DEPOSITS: u32 = 64; /// Most deposits across subnets that other coldkeys may leave behind on a coldkey by opening /// deposits for it through transfers. Half of [`MAX_GAMMA_DEPOSITS`], so the coldkey keeps as /// many on every subnet for its own, and deposits others opened on both coldkeys of a swap fit /// within [`MAX_COLDKEY_SWAP_GAMMA_DEPOSITS`]. pub const MAX_THIRD_PARTY_GAMMA_DEPOSITS: u32 = MAX_GAMMA_DEPOSITS / 2; /// Maximum number of gamma deposits one coldkey swap admits, counting both coldkeys. pub const MAX_COLDKEY_SWAP_GAMMA_DEPOSITS: u32 = 128; /// Blocks over which a daily spend cap refills in full: one day. pub const GAMMA_REFILL_BLOCKS: u64 = 7200; /// Smallest gamma a mint or transfer credits, and a spend, move, deposit or withdrawal takes, or /// a move, deposit, withdrawal or transfer leaves, unless it empties its source: 0.1 gamma. pub const MIN_GAMMA_AMOUNT: u64 = 100_000_000; /// How far a gamma emission trade may fill from its pool's fast moving and spot prices: 2%. pub const GAMMA_EMISSION_MAX_SLIPPAGE_BPS: u64 = 200; /// Oldest TAO/USD feed, in blocks, a mint accepts: one hour. pub const TAO_USD_PRICE_MAX_AGE: u64 = 300; /// Largest rise per block of the accepted TAO/USD price toward the feed: about 2% per hour. pub const TAO_USD_PRICE_MAX_STEP: Perbill = Perbill::from_parts(66_000); /// Longest service url, in bytes. pub const MAX_SERVICE_URL_LEN: u32 = 256; /// Account flag bit that opts into receiving locked alpha transfers. pub const ACCOUNT_FLAGS_ACCEPT_LOCKED_ALPHA: u128 = 1u128 << 0; /// Refuse staking-list growth initiated by another coldkey. pub const ACCOUNT_FLAGS_REJECT_STAKING_HOTKEY_GROWTH: u128 = 1u128 << 1; #[allow(deprecated)] #[deny(missing_docs)] #[import_section(errors::errors)] #[import_section(events::events)] #[import_section(dispatches::dispatches)] #[import_section(genesis::genesis)] #[import_section(hooks::hooks)] #[import_section(config::config)] #[frame_support::pallet] #[allow(clippy::expect_used)] pub mod pallet { use crate::migrations; use crate::staking::lock::LockState; use crate::subnets::dissolution::DissolveCleanupStatus; use crate::subnets::emission_weights::{EmissionWeightsVec, GammaEmission}; use crate::subnets::leasing::{LeaseId, SubnetLeaseOf}; use crate::subnets::subnet::NetworkRegistrationInfo; use crate::weights::WeightInfo; use crate::{ DEFAULT_MAX_TIMELOCKED_COMMITS_PER_HOTKEY, MAX_ASSOCIATED_UIDS_PER_EVM_ADDRESS, MAX_COLDKEY_COLLATERAL_HOTKEYS, MAX_GAMMA_DEPOSITS, MAX_SERVICE_URL_LEN, RateLimitKey, }; use frame_support::Twox64Concat; use frame_support::{ BoundedVec, dispatch::GetDispatchInfo, pallet_prelude::{DispatchResult, StorageMap, ValueQuery, *}, traits::{ OriginTrait, QueryPreimage, StorePreimage, UnfilteredDispatchable, tokens::fungible, }, weights::{Weight, WeightMeter}, }; use frame_system::pallet_prelude::*; use pallet_drand::types::RoundNumber; use runtime_common::prod_or_fast; use share_pool::SafeFloat; use sp_core::{ConstU32, H160, H256}; use sp_runtime::PerU16; use sp_runtime::traits::{Dispatchable, TrailingZeroInput}; use sp_std::collections::btree_map::BTreeMap; use sp_std::collections::btree_set::BTreeSet; use sp_std::collections::vec_deque::VecDeque; use sp_std::vec; use sp_std::vec::Vec; use substrate_fixed::types::{I64F64, I96F32, U64F64, U96F32}; use subtensor_macros::freeze_struct; use subtensor_runtime_common::{ AlphaBalance, GammaBalance, MechId, NetUid, NetUidStorageIndex, TaoBalance, Token, }; /// Origin for the pallet pub type PalletsOriginOf = <::RuntimeOrigin as OriginTrait>::PalletsOrigin; /// Call type for the pallet pub type CallOf = ::RuntimeCall; /// Tracks version for migrations. Should be monotonic with respect to the /// order of migrations. (i.e. always increasing) const STORAGE_VERSION: StorageVersion = StorageVersion::new(7); /// Minimum balance required to perform a coldkey swap pub const MIN_BALANCE_TO_PERFORM_COLDKEY_SWAP: TaoBalance = TaoBalance::new(100_000_000); // 0.1 TAO in RAO /// Minimum commit reveal periods pub const MIN_COMMIT_REVEAL_PEROIDS: u64 = 1; /// Maximum commit reveal periods pub const MAX_COMMIT_REVEAL_PEROIDS: u64 = 100; #[pallet::pallet] #[pallet::without_storage_info] #[pallet::storage_version(STORAGE_VERSION)] pub struct Pallet(_); /// Alias for the account ID. pub type AccountIdOf = ::AccountId; /// Struct for Axon. pub type AxonInfoOf = AxonInfo; /// local one pub type LocalCallOf = ::RuntimeCall; /// Data structure for Axon information. #[crate::freeze_struct("3545cfb0cac4c1f5")] #[derive(Encode, Decode, Default, TypeInfo, Clone, PartialEq, Eq, Debug)] pub struct AxonInfo { /// Axon serving block. pub block: u64, /// Axon version pub version: u32, /// Axon u128 encoded ip address of type v6 or v4. pub ip: u128, /// Axon u16 encoded port. pub port: u16, /// Axon ip type, 4 for ipv4 and 6 for ipv6. pub ip_type: u8, /// Axon protocol. TCP, UDP, other. pub protocol: u8, /// Axon proto placeholder 1. pub placeholder1: u8, /// Axon proto placeholder 2. pub placeholder2: u8, } /// User-visible lifecycle state of a subnet. /// /// This state is deliberately separate from [`NetworksAdded`]. The latter remains the /// authority for whether runtime operations may target a subnet, while this state keeps a /// dissolved subnet visible to reporting APIs until its deferred cleanup has settled stake. #[derive( Encode, Decode, DecodeWithMemTracking, TypeInfo, MaxEncodedLen, Clone, Copy, PartialEq, Eq, Debug, )] pub enum SubnetLifecycleState { /// The subnet exists but its start call has not completed. #[codec(index = 0)] Registered, /// The subnet's start call has completed. #[codec(index = 1)] Started, /// The subnet has left the active set and is waiting for cleanup. #[codec(index = 2)] PendingDissolution, /// The subnet is currently being cleaned up by `on_idle`. #[codec(index = 3)] Dissolving, } /// Struct for NeuronCertificate. pub type NeuronCertificateOf = NeuronCertificate; /// Data structure for NeuronCertificate information. #[freeze_struct("1c232be200d9ec6c")] #[derive(Decode, Encode, Default, TypeInfo, PartialEq, Eq, Clone, Debug)] pub struct NeuronCertificate { /// The neuron TLS public key pub public_key: BoundedVec>, /// The algorithm used to generate the public key pub algorithm: u8, } impl TryFrom> for NeuronCertificate { type Error = (); fn try_from(value: Vec) -> Result { if value.len() > 65 { return Err(()); } // take the first byte as the algorithm let algorithm = value.first().ok_or(())?; // and the rest as the public_key let certificate = value.get(1..).ok_or(())?.to_vec(); Ok(Self { public_key: BoundedVec::try_from(certificate).map_err(|_| ())?, algorithm: *algorithm, }) } } /// Struct for Prometheus. pub type PrometheusInfoOf = PrometheusInfo; /// Data structure for Prometheus information. #[crate::freeze_struct("5dde687e63baf0cd")] #[derive(Encode, Decode, Default, TypeInfo, Clone, PartialEq, Eq, Debug)] pub struct PrometheusInfo { /// Prometheus serving block. pub block: u64, /// Prometheus version. pub version: u32, /// Prometheus u128 encoded ip address of type v6 or v4. pub ip: u128, /// Prometheus u16 encoded port. pub port: u16, /// Prometheus ip type, 4 for ipv4 and 6 for ipv6. pub ip_type: u8, } /// Data structure for a hotkey's service. #[crate::freeze_struct("202c7e535885758")] #[derive(Encode, Decode, TypeInfo, Clone, PartialEq, Eq, Debug)] pub struct ServiceInfo { /// Url of the document describing the hotkey's services. pub url: BoundedVec>, } /// Struct for ChainIdentities. (DEPRECATED for V2) pub type ChainIdentityOf = ChainIdentity; /// Data structure for Chain Identities. (DEPRECATED for V2) #[crate::freeze_struct("bbfd00438dbe2b58")] #[derive(Encode, Decode, Default, TypeInfo, Clone, PartialEq, Eq, Debug)] pub struct ChainIdentity { /// The name of the chain identity pub name: Vec, /// The URL associated with the chain identity pub url: Vec, /// The image representation of the chain identity pub image: Vec, /// The Discord information for the chain identity pub discord: Vec, /// A description of the chain identity pub description: Vec, /// Additional information about the chain identity pub additional: Vec, } /// Struct for ChainIdentities. pub type ChainIdentityOfV2 = ChainIdentityV2; /// Data structure for Chain Identities. #[crate::freeze_struct("ad72a270be7b59d7")] #[derive(Encode, Decode, Default, TypeInfo, Clone, PartialEq, Eq, Debug)] pub struct ChainIdentityV2 { /// The name of the chain identity pub name: Vec, /// The URL associated with the chain identity pub url: Vec, /// The github repository associated with the identity pub github_repo: Vec, /// The image representation of the chain identity pub image: Vec, /// The Discord information for the chain identity pub discord: Vec, /// A description of the chain identity pub description: Vec, /// Additional information about the chain identity pub additional: Vec, } /// Struct for SubnetIdentities. (DEPRECATED for V2) pub type SubnetIdentityOf = SubnetIdentity; /// Data structure for Subnet Identities. (DEPRECATED for V2) #[crate::freeze_struct("f448dc3dad763108")] #[derive(Encode, Decode, Default, TypeInfo, Clone, PartialEq, Eq, Debug)] pub struct SubnetIdentity { /// The name of the subnet pub subnet_name: Vec, /// The github repository associated with the chain identity pub github_repo: Vec, /// The subnet's contact pub subnet_contact: Vec, } /// Struct for SubnetIdentitiesV2. (DEPRECATED for V3) pub type SubnetIdentityOfV2 = SubnetIdentityV2; /// Data structure for Subnet Identities (DEPRECATED for V3) #[crate::freeze_struct("e002be4cd05d7b3e")] #[derive(Encode, Decode, Default, TypeInfo, Clone, PartialEq, Eq, Debug)] pub struct SubnetIdentityV2 { /// The name of the subnet pub subnet_name: Vec, /// The github repository associated with the subnet pub github_repo: Vec, /// The subnet's contact pub subnet_contact: Vec, /// The subnet's website pub subnet_url: Vec, /// The subnet's discord pub discord: Vec, /// The subnet's description pub description: Vec, /// Additional information about the subnet pub additional: Vec, } /// Struct for SubnetIdentitiesV3. pub type SubnetIdentityOfV3 = SubnetIdentityV3; /// Data structure for Subnet Identities #[crate::freeze_struct("6a441335f985a0b")] #[derive( Encode, Decode, DecodeWithMemTracking, Default, TypeInfo, Clone, PartialEq, Eq, Debug, )] pub struct SubnetIdentityV3 { /// The name of the subnet pub subnet_name: Vec, /// The github repository associated with the subnet pub github_repo: Vec, /// The subnet's contact pub subnet_contact: Vec, /// The subnet's website pub subnet_url: Vec, /// The subnet's discord pub discord: Vec, /// The subnet's description pub description: Vec, /// The subnet's logo pub logo_url: Vec, /// Additional information about the subnet pub additional: Vec, } /// Enum for recycle or burn for the owner_uid(s) #[derive(TypeInfo, Encode, Decode, DecodeWithMemTracking, Clone, PartialEq, Eq, Debug)] pub enum RecycleOrBurnEnum { /// Burn the miner emission sent to the burn UID Burn, /// Recycle the miner emission sent to the recycle UID Recycle, } /// Selects the subnet's epoch reward algorithm. #[derive( Encode, Decode, DecodeWithMemTracking, Default, TypeInfo, Clone, Copy, PartialEq, Eq, Debug, MaxEncodedLen, )] pub enum EpochConsensus { /// Run the configured Yuma algorithm. #[default] #[codec(index = 0)] Yuma, /// Use the largest-stake validator's weights and stake-proportional dividends. #[codec(index = 1)] Null, } /// Selects which consensus values liquid alpha uses. #[derive( Encode, Decode, DecodeWithMemTracking, Default, TypeInfo, Clone, Copy, PartialEq, Eq, Debug, MaxEncodedLen, )] pub enum ConsensusMode { /// Use consensus calculated in the current epoch. Current, /// Use consensus persisted by the previous epoch. Previous, /// Use previous consensus at maximum bond penalty, otherwise current consensus. #[default] Auto, } /// Selects the price reference used to bound validator basket trade legs. #[derive( Encode, Decode, DecodeWithMemTracking, Default, TypeInfo, Clone, Copy, PartialEq, Eq, Debug, MaxEncodedLen, )] pub enum BasketTradePriceReference { /// Measure both the sell floor and buy ceiling from the current spot price only. /// Governance must select this mode explicitly; unlike the default, it does not /// retain the fast-EMA bound on chained same-block price manipulation. #[codec(index = 0)] SpotOnly, /// Default legacy mode: sell floor from `max(slow EMA, fast EMA, spot)` and buy /// ceiling from `min(slow EMA, fast EMA, spot)`. Missing or zero EMAs refuse the trade. #[default] #[codec(index = 1)] StrictestEmaAndSpot, } /// Miner registration collateral for a `(hotkey, coldkey)` stake position /// on a subnet. /// /// The locked alpha is real stake owned by that coldkey on the hotkey, /// flagged non-withdrawable. It is released back to free stake at /// `drain_ratio` alpha per alpha of hotkey emission earned (miner /// incentive and validator dividends), survives deregistration, and is /// credited against the collateral requirement at the next registration /// of the same `(hotkey, coldkey)` pair. #[crate::freeze_struct("5819399337dfad56")] #[derive(Encode, Decode, DecodeWithMemTracking, Clone, PartialEq, Eq, Debug, TypeInfo)] pub struct MinerCollateralState { /// Alpha still locked (non-withdrawable) on this stake position. pub locked: AlphaBalance, /// Snapshot of the subnet's drain ratio (k) at the last registration. pub drain_ratio: U64F64, /// Miner-set floor the lock self-maintains around: the drain never /// releases below it, and while `locked` is under it, earned emission /// is captured into the lock until the floor is met. Zero (the /// default) disables the floor and restores pure drain behavior. pub min_locked: AlphaBalance, /// Cumulative hotkey emission (incentive + dividends) earned while /// this collateral entry has existed (saturating). Observability for /// validators: compares lifetime extraction against the bond still at /// risk. Scoped to the entry — it disappears with the entry once the /// lock fully drains with no floor set. pub earned: AlphaBalance, } /// A coldkey's gamma on one subnet, held at a hotkey. #[crate::freeze_struct("adba87f00d4f97af")] #[derive(Encode, Decode, DecodeWithMemTracking, Clone, PartialEq, Eq, Debug, TypeInfo)] pub struct GammaDeposit { /// The coldkey that owns the deposit. pub coldkey: AccountId, /// The gamma held. pub balance: GammaBalance, /// The deposit's daily spend cap; `None` is no cap. pub daily_spend_cap: Option, } /// The gamma a deposit's hotkey may spend per day, and what it allows as of a block. #[crate::freeze_struct("b0a2e67c2cd32b3")] #[derive( Encode, Decode, DecodeWithMemTracking, Clone, Copy, PartialEq, Eq, Debug, TypeInfo, )] pub struct GammaDailySpendCap { /// The gamma the hotkey may spend per day. pub cap: GammaBalance, /// What the cap allows, and its block. pub bucket: (GammaBalance, u64), } /// The TAO/USD price, in gamma units per TAO. #[crate::freeze_struct("f3a5e8bdbc1b7763")] #[derive(Encode, Decode, DecodeWithMemTracking, Clone, PartialEq, Eq, Debug, TypeInfo)] pub struct TaoUsdPriceState { /// The accepted price at `fed_at`. pub accepted: u64, /// The oracle's latest feed. pub feed: u64, /// The block of the latest feed. pub fed_at: u64, } /// A beta-basket fund's frozen display baseline, stamped once at the fund's first /// share mint (its "first sighting") and never rewritten. /// /// Raw beta prices (`spot NAV / shares`) carry arbitrary historical baselines, so /// levels are not comparable across funds of different ages. The baseline splices /// every fund onto two common index lines at birth — the way a new share class of a /// fund launches at the master fund's current NAV rather than at $1: /// /// * display (bag) price = `raw_price / price_divisor` — starts at the basket /// index level of the stamp block (both sides marked at realizable quotes, so /// a stamp cannot be poisoned by a spot-price push); /// * total-return stake price = `tr_splice * BasketTwr` — the wealth of τ1 staked /// at the stamp block under the claim-and-restake convention, compounding only /// with dividends actually minted to stakers since then, each locked at its /// deposit-time pricing. /// /// See `staking/beta_pricing.rs` for the index and pricing math built on this. #[crate::freeze_struct("e48f71fa685b45cf")] #[derive( Encode, Decode, DecodeWithMemTracking, Clone, Copy, PartialEq, Eq, Debug, TypeInfo, )] pub struct BetaBaselineOf { /// Divisor splicing the raw beta price onto the basket index: the fund's raw /// price at the stamp block over the index level at that block. pub price_divisor: U64F64, /// The fund's `BasketRate` at the stamp block. The pending-entitlement mark /// (`staker_yield`) only counts rate accrued past this, so pre-period (e.g. /// migration-seeded legacy) history is excluded from every fund's figure the /// same way. pub rate0: I96F32, /// Splice factor for the staker total-return series: `tr_splice * BasketTwr` /// is the fund's stake price. Stamped as the stake-index level at the stamp /// block divided by the fund's TWR at that block (dividends can predate a /// deferred stamp), so the stake price starts exactly on the index line. The /// seed migration additionally folds the fund's pre-upgrade entitlement into /// this factor (see `migrate_stamp_beta_baselines`). pub tr_splice: U64F64, /// Block at which this baseline was stamped. pub first_block: u64, } /// A published beta-index snapshot: the chained `(bag, stake)` index levels, marked at /// realizable quotes. Each completed sweep pass multiplies the previous levels by the /// prior-NAV-weighted mean of per-fund price relatives, so capital flows never move /// the index — only fund returns do. Baseline stamps and the pricing runtime APIs /// splice onto / read the latest snapshot instead of sweeping inline, which is what /// keeps their work bounded (see `advance_beta_index_sweep`). #[crate::freeze_struct("dab9adbdbe9f4ef4")] #[derive( Encode, Decode, DecodeWithMemTracking, Clone, Copy, PartialEq, Eq, Debug, TypeInfo, )] pub struct BetaIndexSnapshotOf { /// Chained NAV-weighted display-price index level (realizable mark). pub bag_level: U64F64, /// Chained NAV-weighted total-return stake index level. pub stake_level: U64F64, /// Block at which the sweep that produced these levels completed. pub block: u64, } /// One fund's sample from the last completed index-sweep pass: the start-of-period /// state the next pass chains against. The fund's next price relative is /// `display_now / display`, weighted by `nav` (start-of-period size), so deposits and /// redemptions between passes change the *weight* but never fabricate a return. /// Scoped to one fund life, like `BetaBaseline`: moved on hotkey swap and removed on /// retirement, so a revived fund never chains across lives. #[crate::freeze_struct("9adef5cfda198dd3")] #[derive( Encode, Decode, DecodeWithMemTracking, Clone, Copy, PartialEq, Eq, Debug, TypeInfo, )] pub struct BetaIndexFundSampleOf { /// Realizable NAV (rao) at the sample; the fund's weight in the next relative. pub nav: u64, /// Display price at the sample (denominator of the next bag relative). pub display: U64F64, /// Total-return stake price at the sample (denominator of the next stake relative). pub stake: U64F64, } /// In-progress state of the paged beta-index sweep: partial sums of the chained-index /// relatives plus the raw storage key to resume iteration from. One bounded page /// advances per block; when the pass completes, the previous snapshot levels are /// multiplied by the aggregate relatives and published as a [`BetaIndexSnapshotOf`]. #[crate::freeze_struct("9b6150dad57406fa")] #[derive(Encode, Decode, DecodeWithMemTracking, Clone, PartialEq, Eq, Debug, TypeInfo)] pub struct BetaIndexSweepOf { /// Raw storage key of the last `BetaBaseline` entry processed; empty means the /// pass starts from the top of the map. pub cursor: Vec, /// Σ previous-pass nav (rao) across funds with samples at both ends of the period. pub weight_sum: u128, /// Σ previous nav × (display now / display previous) so far. pub rel_bag_sum: U64F64, /// Σ previous nav × (stake now / stake previous) so far. pub rel_stake_sum: U64F64, } // ============================ // ==== Staking + Accounts ==== // ============================ /// The Max Burn HalfLife Settable #[pallet::type_value] pub fn MaxBurnHalfLife() -> u16 { 36_100 } /// Default burn half-life (in blocks) for subnet registration price decay. #[pallet::type_value] pub fn DefaultBurnHalfLife() -> u16 { 360 } /// Default multiplier applied to the burn price after a successful registration. #[pallet::type_value] pub fn DefaultBurnIncreaseMult() -> U64F64 { U64F64::from_num(1.26) } /// Default Neuron Burn Cost #[pallet::type_value] pub fn DefaultNeuronBurnCost() -> TaoBalance { TaoBalance::from(1_000_000_000u64) } /// Default miner collateral lock share (p). 0 disables the collateral /// mechanism entirely: the full registration price is burned, matching /// pre-collateral behavior. #[pallet::type_value] pub fn DefaultCollateralLockShare() -> u16 { 0 } /// Maximum settable miner collateral lock share: 95% of the registration /// price (u16-normalized). The burned share must stay strictly positive so /// re-registration always pays a nonzero, floating burn. #[pallet::type_value] pub fn MaxCollateralLockShare() -> u16 { 62258 // ~0.95 * u16::MAX } /// Default miner collateral drain ratio (k): one alpha of collateral is /// released per alpha of hotkey emission earned. #[pallet::type_value] pub fn DefaultCollateralDrainRatio() -> U64F64 { U64F64::from_num(1) } /// Maximum settable miner collateral drain ratio. #[pallet::type_value] pub fn MaxCollateralDrainRatio() -> U64F64 { U64F64::from_num(10) } /// 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. #[pallet::type_value] pub fn DefaultMinRootClaimAmount() -> I96F32 { 500_000u64.into() } /// Default value for zero. #[pallet::type_value] pub fn DefaultZeroU64() -> u64 { 0 } /// Default value for zero. #[pallet::type_value] pub fn DefaultZeroI64() -> i64 { 0 } /// Default value for zero fixed-point I96F32. #[pallet::type_value] pub fn DefaultZeroI96F32() -> I96F32 { I96F32::saturating_from_num(0) } /// Default one for U64F64 accumulators (multiplicative identity). #[pallet::type_value] pub fn DefaultOneU64F64() -> U64F64 { U64F64::saturating_from_num(1) } /// Default value for Alpha currency. #[pallet::type_value] pub fn DefaultZeroAlpha() -> AlphaBalance { AlphaBalance::ZERO } /// Default value for Tao currency. #[pallet::type_value] pub fn DefaultZeroTao() -> TaoBalance { TaoBalance::ZERO } /// Default value for zero. #[pallet::type_value] pub fn DefaultZeroU128() -> u128 { 0 } /// Default value for zero. #[pallet::type_value] pub fn DefaultZeroU16() -> u16 { 0 } /// Default value for false. #[pallet::type_value] pub fn DefaultFalse() -> bool { false } /// Default value for true. #[pallet::type_value] pub fn DefaultTrue() -> bool { true } /// Total Rao in circulation. #[pallet::type_value] pub fn TotalSupply() -> u64 { 21_000_000_000_000_000 } /// Default Delegate Take. #[pallet::type_value] pub fn DefaultDelegateTake() -> PerU16 { PerU16::from_parts(T::InitialDefaultDelegateTake::get()) } /// Default childkey take. #[pallet::type_value] pub fn DefaultChildKeyTake() -> PerU16 { PerU16::from_parts(T::InitialDefaultChildKeyTake::get()) } /// Default minimum delegate take. #[pallet::type_value] pub fn DefaultMinDelegateTake() -> PerU16 { PerU16::from_parts(T::InitialMinDelegateTake::get()) } /// Default minimum childkey take. #[pallet::type_value] pub fn DefaultMinChildKeyTake() -> PerU16 { PerU16::from_parts(T::InitialMinChildKeyTake::get()) } /// Default maximum childkey take. #[pallet::type_value] pub fn DefaultMaxChildKeyTake() -> PerU16 { PerU16::from_parts(T::InitialMaxChildKeyTake::get()) } /// Default account take. #[pallet::type_value] pub fn DefaultAccountTake() -> u64 { 0 } /// Default value for global weight. #[pallet::type_value] pub fn DefaultTaoWeight() -> u64 { T::InitialTaoWeight::get() } /// Default emission per block. #[pallet::type_value] pub fn DefaultBlockEmission() -> u64 { 1_000_000_000 } /// Default allowed delegation. #[pallet::type_value] pub fn DefaultAllowsDelegation() -> bool { false } /// Default total issuance. #[pallet::type_value] pub fn DefaultTotalIssuance() -> TaoBalance { T::InitialIssuance::get().into() } /// Default account, derived from zero trailing bytes. #[pallet::type_value] pub fn DefaultAccount() -> T::AccountId { #[allow(clippy::expect_used)] T::AccountId::decode(&mut TrailingZeroInput::zeroes()) .expect("trailing zeroes always produce a valid account ID; qed") } // pub fn DefaultStakeInterval() -> u64 { // 360 // } (DEPRECATED) /// Default account linkage #[pallet::type_value] pub fn DefaultAccountLinkage() -> Vec<(u64, T::AccountId)> { vec![] } /// Default pending childkeys #[pallet::type_value] pub fn DefaultPendingChildkeys() -> (Vec<(u64, T::AccountId)>, u64) { (vec![], 0) } /// Default account linkage #[pallet::type_value] pub fn DefaultProportion() -> u64 { 0 } /// Default accumulated emission for a hotkey #[pallet::type_value] pub fn DefaultAccumulatedEmission() -> u64 { 0 } /// Default last adjustment block. #[pallet::type_value] pub fn DefaultLastAdjustmentBlock() -> u64 { 0 } /// Default last adjustment block. #[pallet::type_value] pub fn DefaultRegistrationsThisBlock() -> u16 { 0 } /// Default EMA price halving blocks #[pallet::type_value] pub fn DefaultEMAPriceMovingBlocks() -> u64 { T::InitialEmaPriceHalvingPeriod::get() } /// Default registrations this block. #[pallet::type_value] pub fn DefaultBurn() -> TaoBalance { T::InitialBurn::get().into() } /// Default burn token. #[pallet::type_value] pub fn DefaultMinBurn() -> TaoBalance { T::InitialMinBurn::get().into() } /// Default min burn token. #[pallet::type_value] pub fn DefaultMaxBurn() -> TaoBalance { T::InitialMaxBurn::get().into() } /// Default max burn token. #[pallet::type_value] pub fn DefaultDifficulty() -> u64 { T::InitialDifficulty::get() } /// Default difficulty value. #[pallet::type_value] pub fn DefaultMinDifficulty() -> u64 { T::InitialMinDifficulty::get() } /// Default min difficulty value. #[pallet::type_value] pub fn DefaultMaxDifficulty() -> u64 { T::InitialMaxDifficulty::get() } /// Default max difficulty value. #[pallet::type_value] pub fn DefaultMaxRegistrationsPerBlock() -> u16 { T::InitialMaxRegistrationsPerBlock::get() } /// Default max registrations per block. #[pallet::type_value] pub fn DefaultRAORecycledForRegistration() -> TaoBalance { T::InitialRAORecycledForRegistration::get().into() } /// Default number of networks. #[pallet::type_value] pub fn DefaultN() -> u16 { 0 } /// Default value for hotkeys. #[pallet::type_value] pub fn DefaultHotkeys() -> Vec { vec![] } /// Default value if network is added. #[pallet::type_value] pub fn DefaultNeworksAdded() -> bool { false } /// Default value for network member. #[pallet::type_value] pub fn DefaultIsNetworkMember() -> bool { false } /// Default value for registration allowed. #[pallet::type_value] pub fn DefaultRegistrationAllowed() -> bool { true } /// Default value for network registered at. #[pallet::type_value] pub fn DefaultNetworkRegisteredAt() -> u64 { 0 } /// Default value for network immunity period. #[pallet::type_value] pub fn DefaultNetworkImmunityPeriod() -> u64 { T::InitialNetworkImmunityPeriod::get() } /// Default value for network min lock cost. #[pallet::type_value] pub fn DefaultNetworkMinLockCost() -> TaoBalance { T::InitialNetworkMinLockCost::get().into() } /// Default value for network lock reduction interval. #[pallet::type_value] pub fn DefaultNetworkLockReductionInterval() -> u64 { T::InitialNetworkLockReductionInterval::get() } /// Default value for subnet owner cut. #[pallet::type_value] pub fn DefaultSubnetOwnerCut() -> u16 { T::InitialSubnetOwnerCut::get() } /// Default value for recycle or burn. #[pallet::type_value] pub fn DefaultRecycleOrBurn() -> RecycleOrBurnEnum { RecycleOrBurnEnum::Burn // default to burn } /// Default value for network rate limit. #[pallet::type_value] pub fn DefaultNetworkRateLimit() -> u64 { if cfg!(feature = "pow-faucet") { return 0; } T::InitialNetworkRateLimit::get() } /// Default value for network rate limit. #[pallet::type_value] pub fn DefaultNetworkRegistrationStartBlock() -> u64 { 0 } /// Default value for TAO-in refund deployment block. #[pallet::type_value] pub fn DefaultTaoInRefundDeploymentBlock() -> u64 { 0 } /// Default value for weights version key rate limit. /// In units of tempos. #[pallet::type_value] pub fn DefaultWeightsVersionKeyRateLimit() -> u64 { 5 // 5 tempos } /// Default value for pending emission. #[pallet::type_value] pub fn DefaultPendingEmission() -> AlphaBalance { 0.into() } /// Default value for blocks since last step. #[pallet::type_value] pub fn DefaultBlocksSinceLastStep() -> u64 { 0 } /// Default value for last mechanism step block. #[pallet::type_value] pub fn DefaultLastMechanismStepBlock() -> u64 { 0 } /// Default value for subnet owner. #[pallet::type_value] pub fn DefaultSubnetOwner() -> T::AccountId { #[allow(clippy::expect_used)] T::AccountId::decode(&mut sp_runtime::traits::TrailingZeroInput::zeroes()) .expect("trailing zeroes always produce a valid account ID; qed") } /// Default value for subnet locked. #[pallet::type_value] pub fn DefaultSubnetLocked() -> u64 { 0 } /// Default value for network tempo #[pallet::type_value] pub fn DefaultTempo() -> u16 { T::InitialTempo::get() } /// Default value for weights set rate limit. #[pallet::type_value] pub fn DefaultWeightsSetRateLimit() -> u64 { 100 } /// Default maximum Yuma timelocked commits per hotkey, mechanism, and epoch. #[pallet::type_value] pub fn DefaultMaxTimelockedCommitsPerHotkey() -> u8 { DEFAULT_MAX_TIMELOCKED_COMMITS_PER_HOTKEY } /// Default block number at registration. #[pallet::type_value] pub fn DefaultBlockAtRegistration() -> u64 { 0 } /// Default value for rho parameter. #[pallet::type_value] pub fn DefaultRho() -> u16 { T::InitialRho::get() } /// Default value for alpha sigmoid steepness. #[pallet::type_value] pub fn DefaultAlphaSigmoidSteepness() -> i16 { T::InitialAlphaSigmoidSteepness::get() } /// Default value for kappa parameter. #[pallet::type_value] pub fn DefaultKappa() -> u16 { T::InitialKappa::get() } /// Default value for network min allowed UIDs. #[pallet::type_value] pub fn DefaultMinAllowedUids() -> u16 { T::InitialMinAllowedUids::get() } /// Default maximum allowed UIDs. #[pallet::type_value] pub fn DefaultMaxAllowedUids() -> u16 { T::InitialMaxAllowedUids::get() } /// Rate limit for set max allowed UIDs #[pallet::type_value] pub fn MaxUidsTrimmingRateLimit() -> u64 { prod_or_fast!(30 * 7200, 1) } /// Default immunity period. #[pallet::type_value] pub fn DefaultImmunityPeriod() -> u16 { T::InitialImmunityPeriod::get() } /// Default activity cutoff. #[pallet::type_value] pub fn DefaultActivityCutoff() -> u16 { T::InitialActivityCutoff::get() } /// Default weights version key. #[pallet::type_value] pub fn DefaultWeightsVersionKey() -> u64 { T::InitialWeightsVersionKey::get() } /// Default minimum allowed weights. #[pallet::type_value] pub fn DefaultMinAllowedWeights() -> u16 { T::InitialMinAllowedWeights::get() } /// Default maximum allowed validators. #[pallet::type_value] pub fn DefaultMaxAllowedValidators() -> u16 { T::InitialMaxAllowedValidators::get() } /// Default adjustment interval. #[pallet::type_value] pub fn DefaultAdjustmentInterval() -> u16 { T::InitialAdjustmentInterval::get() } /// Default bonds moving average. #[pallet::type_value] pub fn DefaultBondsMovingAverage() -> u64 { T::InitialBondsMovingAverage::get() } /// Default bonds penalty. #[pallet::type_value] pub fn DefaultBondsPenalty() -> u16 { T::InitialBondsPenalty::get() } /// Default value for bonds reset - will not reset bonds #[pallet::type_value] pub fn DefaultBondsResetOn() -> bool { T::InitialBondsResetOn::get() } /// Default validator prune length. #[pallet::type_value] pub fn DefaultValidatorPruneLen() -> u64 { T::InitialValidatorPruneLen::get() } /// Default scaling law power. #[pallet::type_value] pub fn DefaultScalingLawPower() -> u16 { T::InitialScalingLawPower::get() } /// Default target registrations per interval. #[pallet::type_value] pub fn DefaultTargetRegistrationsPerInterval() -> u16 { T::InitialTargetRegistrationsPerInterval::get() } /// Default adjustment alpha. #[pallet::type_value] pub fn DefaultAdjustmentAlpha() -> u64 { T::InitialAdjustmentAlpha::get() } /// Default minimum stake for weights. #[pallet::type_value] pub fn DefaultStakeThreshold() -> u64 { 0 } /// Default Reveal Period Epochs #[pallet::type_value] pub fn DefaultRevealPeriodEpochs() -> u64 { 1 } /// Value definition for vector of u16. #[pallet::type_value] pub fn EmptyU16Vec() -> Vec { vec![] } /// Value definition for vector of PerU16. #[pallet::type_value] pub fn EmptyPerU16Vec() -> Vec { vec![] } /// Value definition for vector of u64. #[pallet::type_value] pub fn EmptyU64Vec() -> Vec { vec![] } /// Value definition for vector of bool. #[pallet::type_value] pub fn EmptyBoolVec() -> Vec { vec![] } /// Value definition for bonds with type vector of (u16, u16). #[pallet::type_value] pub fn DefaultBonds() -> Vec<(u16, u16)> { vec![] } /// Value definition for weights with vector of (u16, u16). #[pallet::type_value] pub fn DefaultWeights() -> Vec<(u16, u16)> { vec![] } /// Default value for key with type T::AccountId derived from trailing zeroes. #[pallet::type_value] pub fn DefaultKey() -> T::AccountId { #[allow(clippy::expect_used)] T::AccountId::decode(&mut sp_runtime::traits::TrailingZeroInput::zeroes()) .expect("trailing zeroes always produce a valid account ID; qed") } // pub fn DefaultHotkeyEmissionTempo() -> u64 { // T::InitialHotkeyEmissionTempo::get() // } (DEPRECATED) /// Default per-block epoch cap, seeded from the runtime-configured initial value. #[pallet::type_value] pub fn DefaultMaxEpochsPerBlock() -> u8 { T::InitialMaxEpochsPerBlock::get() } /// Default value for rate limiting #[pallet::type_value] pub fn DefaultTxRateLimit() -> u64 { T::InitialTxRateLimit::get() } /// Default value for delegate take rate limiting #[pallet::type_value] pub fn DefaultTxDelegateTakeRateLimit() -> u64 { T::InitialTxDelegateTakeRateLimit::get() } /// Default value for chidlkey take rate limiting #[pallet::type_value] pub fn DefaultTxChildKeyTakeRateLimit() -> u64 { T::InitialTxChildKeyTakeRateLimit::get() } /// Default value for last extrinsic block. #[pallet::type_value] pub fn DefaultLastTxBlock() -> u64 { 0 } /// Default value for serving rate limit. #[pallet::type_value] pub fn DefaultServingRateLimit() -> u64 { T::InitialServingRateLimit::get() } /// Default value for weight commit/reveal enabled. #[pallet::type_value] pub fn DefaultCommitRevealWeightsEnabled() -> bool { true } /// Default value for weight commit/reveal version. #[pallet::type_value] pub fn DefaultCommitRevealWeightsVersion() -> u16 { 4 } /// ITEM (switches liquid alpha on) #[pallet::type_value] pub fn DefaultLiquidAlpha() -> bool { false } /// ITEM (switches liquid alpha on) #[pallet::type_value] pub fn DefaultYuma3() -> bool { false } /// (alpha_low: 0.7, alpha_high: 0.9) #[pallet::type_value] pub fn DefaultAlphaValues() -> (u16, u16) { (45875, 58982) } /// Default consensus mode for liquid alpha. #[pallet::type_value] pub fn DefaultConsensusMode() -> ConsensusMode { ConsensusMode::Auto } /// Default value for coldkey swap announcement delay. #[pallet::type_value] pub fn DefaultColdkeySwapAnnouncementDelay() -> BlockNumberFor { T::InitialColdkeySwapAnnouncementDelay::get() } /// Default value for coldkey swap reannouncement delay. #[pallet::type_value] pub fn DefaultColdkeySwapReannouncementDelay() -> BlockNumberFor { T::InitialColdkeySwapReannouncementDelay::get() } /// Default value for applying pending items (e.g. childkeys). #[pallet::type_value] pub fn DefaultPendingCooldown() -> u64 { prod_or_fast!(7_200, 15) } /// Default minimum stake. #[pallet::type_value] pub fn DefaultMinStake() -> TaoBalance { T::InitialMinStake::get().into() } /// Default minimum stake transfer amount. #[pallet::type_value] pub fn DefaultMinTransfer() -> TaoBalance { T::InitialMinTransfer::get().into() } /// Default unicode vector for tau symbol. #[pallet::type_value] pub fn DefaultUnicodeVecU8() -> Vec { b"\xF0\x9D\x9C\x8F".to_vec() // Unicode for tau (𝜏) } /// Default value for dissolve network schedule duration #[pallet::type_value] pub fn DefaultDissolveNetworkScheduleDuration() -> BlockNumberFor { T::InitialDissolveNetworkScheduleDuration::get() } /// Default moving alpha for the moving price. #[pallet::type_value] pub fn DefaultMovingAlpha() -> I96F32 { // Moving average take 30 days to reach 50% of the price // and 3.5 months to reach 90%. I96F32::saturating_from_num(0.000003) } /// Default subnet moving price. #[pallet::type_value] pub fn DefaultMovingPrice() -> I96F32 { I96F32::saturating_from_num(0.0) } /// Default subnet root proportion. #[pallet::type_value] pub fn DefaultRootProp() -> U96F32 { U96F32::saturating_from_num(0.0) } /// Default subnet root claimable #[pallet::type_value] pub fn DefaultRootClaimable() -> BTreeMap { Default::default() } /// Default value for Share Pool variables #[pallet::type_value] pub fn DefaultSharePoolZero() -> U64F64 { U64F64::saturating_from_num(0) } /// Default value for minimum activity cutoff #[pallet::type_value] pub fn DefaultMinActivityCutoff() -> u16 { 360 } /// Default value for setting subnet owner hotkey rate limit #[pallet::type_value] pub fn DefaultSetSNOwnerHotkeyRateLimit() -> u64 { 50400 } /// Default last Alpha map key for iteration #[pallet::type_value] pub fn DefaultAlphaIterationLastKey() -> Option> { None } /// Default number of terminal blocks in a tempo during which admin operations are prohibited #[pallet::type_value] pub fn DefaultAdminFreezeWindow() -> u16 { 10 } /// Default number of tempos for owner hyperparameter update rate limit #[pallet::type_value] pub fn DefaultOwnerHyperparamRateLimit() -> u16 { 2 } /// Default value for ck burn, 0%. #[pallet::type_value] pub fn DefaultCKBurn() -> u64 { 0 } /// Default value for subnet limit. #[pallet::type_value] pub fn DefaultSubnetLimit() -> u16 { 128 } /// Default value for MinNonImmuneUids. #[pallet::type_value] pub fn DefaultMinNonImmuneUids() -> u16 { 10u16 } /// Default value for AutoParentDelegationEnabled. #[pallet::type_value] pub fn DefaultAutoParentDelegationEnabled() -> bool { true } #[pallet::storage] pub type MinActivityCutoff = StorageValue<_, u16, ValueQuery, DefaultMinActivityCutoff>; /// Global window (in blocks) at the end of each tempo where admin ops are disallowed #[pallet::storage] pub type AdminFreezeWindow = StorageValue<_, u16, ValueQuery, DefaultAdminFreezeWindow>; /// Global number of epochs used to rate limit subnet owner hyperparameter updates #[pallet::storage] pub type OwnerHyperparamRateLimit = StorageValue<_, u16, ValueQuery, DefaultOwnerHyperparamRateLimit>; /// Duration of dissolve network schedule before execution #[pallet::storage] pub type DissolveNetworkScheduleDuration = StorageValue<_, BlockNumberFor, ValueQuery, DefaultDissolveNetworkScheduleDuration>; /// DMap ( netuid, coldkey ) --> blocknumber | last hotkey swap on network. #[pallet::storage] pub type LastHotkeySwapOnNetuid = StorageDoubleMap< _, Identity, NetUid, Blake2_128Concat, T::AccountId, u64, ValueQuery, DefaultZeroU64, >; /// DMap ( netuid, hotkey ) --> blocknumber | block at which alpha moved into this /// hotkey may be moved again by an owner-driven hotkey swap. /// /// Unlike [`LastHotkeySwapOnNetuid`], this is bound to the stake position rather /// than its current owner, so changing the owning coldkey cannot reset the recovery /// window. Delegator withdrawals do not consult this map. #[pallet::storage] pub type StakeMoveCooldownUntil = StorageDoubleMap< _, Identity, NetUid, Blake2_128Concat, T::AccountId, u64, ValueQuery, DefaultZeroU64, >; /// DMap ( netuid, old_hotkey ) --> new_hotkey | hotkey swap successor on a subnet. /// /// Written on each successful hotkey swap so watchers can follow identity /// without an archive node. Per-subnet because a swap may move a UID on /// one netuid while the old hotkey remains registered elsewhere. #[pallet::storage] pub type HotkeySuccessor = StorageDoubleMap< _, Identity, NetUid, Blake2_128Concat, T::AccountId, T::AccountId, OptionQuery, >; /// DMap ( netuid, hotkey ) --> root_hotkey | first hotkey in this subnet's /// swap lineage. Absent means the hotkey is its own root (never swapped /// into, or never recorded). Ban/score against the root, not a single SS58. #[pallet::storage] pub type HotkeyRoot = StorageDoubleMap< _, Identity, NetUid, Blake2_128Concat, T::AccountId, T::AccountId, OptionQuery, >; /// MAP ( old_coldkey ) --> new_coldkey | global coldkey swap successor. /// /// Written on each successful coldkey swap so watchers can follow owner /// identity without an archive node. Global (not per-netuid) because a /// coldkey swap moves ownership everywhere at once. #[pallet::storage] pub type ColdkeySuccessor = StorageMap<_, Blake2_128Concat, T::AccountId, T::AccountId, OptionQuery>; /// MAP ( coldkey ) --> root_coldkey | first coldkey in this swap lineage. /// Absent means the coldkey is its own root. Prefer root for owner-keyed /// bans/attribution, not a single SS58. #[pallet::storage] pub type ColdkeyRoot = StorageMap<_, Blake2_128Concat, T::AccountId, T::AccountId, OptionQuery>; /// Ensures unique IDs for StakeJobs storage map #[pallet::storage] pub type NextStakeJobId = StorageValue<_, u64, ValueQuery, DefaultZeroU64>; // Staking Variables /// The Subtensor [`TotalIssuance`] represents the total issuance of tokens on the Bittensor network. /// /// It is comprised of three parts: /// * The total amount of issued tokens, tracked in the TotalIssuance of the Balances pallet /// * The total amount of tokens staked in the system, tracked in [`TotalStake`] /// * The total amount of tokens locked up for subnet reg, tracked in [`TotalSubnetLocked`] attained by iterating over subnet lock. /// /// Eventually, Bittensor should migrate to using Holds afterwhich time we will not require this /// separate accounting. /// ITEM --> Global weight #[pallet::storage] pub type TaoWeight = StorageValue<_, u64, ValueQuery, DefaultTaoWeight>; /// ITEM --> CK burn #[pallet::storage] pub type CKBurn = StorageValue<_, u64, ValueQuery, DefaultCKBurn>; /// ITEM ( default_delegate_take ) #[pallet::storage] pub type MaxDelegateTake = StorageValue<_, PerU16, ValueQuery, DefaultDelegateTake>; /// ITEM ( min_delegate_take ) #[pallet::storage] pub type MinDelegateTake = StorageValue<_, PerU16, ValueQuery, DefaultMinDelegateTake>; /// ITEM ( default_childkey_take ) #[pallet::storage] pub type MaxChildkeyTake = StorageValue<_, PerU16, ValueQuery, DefaultMaxChildKeyTake>; /// ITEM ( min_childkey_take ) #[pallet::storage] pub type MinChildkeyTake = StorageValue<_, PerU16, ValueQuery, DefaultMinChildKeyTake>; /// MAP ( netuid ) --> take | Returns the subnet-specific minimum childkey take. #[pallet::storage] pub type MinChildkeyTakePerSubnet = StorageMap<_, Identity, NetUid, PerU16, ValueQuery>; /// MAP ( hot ) --> cold | Returns the controlling coldkey for a hotkey #[pallet::storage] pub type Owner = StorageMap<_, Blake2_128Concat, T::AccountId, T::AccountId, ValueQuery, DefaultAccount>; /// MAP ( coldkey ) --> flags | Account-level flags. Defaults to zero. #[pallet::storage] pub type AccountFlags = StorageMap<_, Blake2_128Concat, T::AccountId, u128, ValueQuery>; /// Claim-only fund associations created when a root swap leaves a staker's stake /// behind. These never grow StakingHotkeys or the work of a stake exit. Claims and /// coldkey swaps bound their selection before admitting work. #[pallet::storage] pub type HotkeySwapBasketCredits = StorageDoubleMap< _, Blake2_128Concat, T::AccountId, Blake2_128Concat, T::AccountId, (), OptionQuery, >; /// MAP ( hot ) --> take | Returns the hotkey delegation take. And signals that this key is open for delegation #[pallet::storage] pub type Delegates = StorageMap<_, Blake2_128Concat, T::AccountId, PerU16, ValueQuery, DefaultDelegateTake>; /// DMAP ( hot, netuid ) --> take | Returns the hotkey childkey take for a specific subnet #[pallet::storage] pub type ChildkeyTake = StorageDoubleMap< _, Blake2_128Concat, T::AccountId, // First key: hotkey Identity, NetUid, // Second key: netuid PerU16, // Value: take ValueQuery, >; /// MAP ( parent ) --> () | Parents with live child relations whose stake just changed. /// Drained in `on_idle`, where each parent's total stake is re-checked against /// `StakeThreshold` and `ChildkeyThresholdSuspended` is set or cleared. #[pallet::storage] pub type ChildkeyThresholdChecks = StorageMap<_, Blake2_128Concat, T::AccountId, (), OptionQuery>; /// MAP ( parent ) --> () | Parents whose total stake is below `StakeThreshold`. Their child /// relations stay stored but are inert (hidden from `get_children` / `get_parents`) /// except on subnets they own, until they qualify again. #[pallet::storage] pub type ChildkeyThresholdSuspended = StorageMap<_, Blake2_128Concat, T::AccountId, (), OptionQuery>; /// DMAP ( netuid, parent ) --> (Vec<(proportion,child)>, cool_down_block) #[pallet::storage] pub type PendingChildKeys = StorageDoubleMap< _, Identity, NetUid, Blake2_128Concat, T::AccountId, (Vec<(u64, T::AccountId)>, u64), ValueQuery, DefaultPendingChildkeys, >; /// DMAP ( parent, netuid ) --> Vec<(proportion,child)> #[pallet::storage] pub type ChildKeys = StorageDoubleMap< _, Blake2_128Concat, T::AccountId, Identity, NetUid, Vec<(u64, T::AccountId)>, ValueQuery, DefaultAccountLinkage, >; /// DMAP ( child, netuid ) --> Vec<(proportion,parent)> #[pallet::storage] pub type ParentKeys = StorageDoubleMap< _, Blake2_128Concat, T::AccountId, Identity, NetUid, Vec<(u64, T::AccountId)>, ValueQuery, DefaultAccountLinkage, >; /// DMAP ( netuid, hotkey ) --> u64 | Last alpha dividend this hotkey got on tempo. #[pallet::storage] pub type AlphaDividendsPerSubnet = StorageDoubleMap< _, Identity, NetUid, Blake2_128Concat, T::AccountId, AlphaBalance, ValueQuery, DefaultZeroAlpha, >; /// DMAP ( netuid, hotkey ) --> u64 | Last root alpha dividend this hotkey got on tempo. #[pallet::storage] pub type RootAlphaDividendsPerSubnet = StorageDoubleMap< _, Identity, NetUid, Blake2_128Concat, T::AccountId, AlphaBalance, ValueQuery, DefaultZeroAlpha, >; /// DMAP ( hotkey, netuid ) --> alpha | Root dividend credits waiting to enter the /// validator's beta basket. Epochs enqueue here instead of depositing inline (a deposit /// prices a share mint against the fund's full NAV — one AMM quote per holding — so /// running one per validator inside the epoch made epoch blocks scale with /// `validators x holdings`). Credits merge per (hotkey, origin subnet) and are flushed /// as a single batched deposit per hotkey: by the one-hotkey-per-block round-robin /// drain (`flush_pending_basket_deposits_block`), or eagerly whenever the hotkey's claimant /// base or basket is touched (claims, basket stakes, root stake changes, hotkey swaps), /// so stake added after an epoch can never capture dividends earned before it arrived. /// Credits whose spot value is below `RootClaimableThreshold[ROOT]` stay queued and /// keep merging until they are worth a deposit, which is what keeps dust from ever /// becoming a basket holding row. Hotkeys deregistered from root have their remaining /// queued credits recycled and purged (pending only — basket holdings are untouched). #[pallet::storage] pub type PendingBasketDeposits = StorageDoubleMap< _, Blake2_128Concat, T::AccountId, Identity, NetUid, AlphaBalance, ValueQuery, DefaultZeroAlpha, >; /// ITEM ( raw storage key ) | Round-robin cursor of the per-block pending-basket-deposit /// flush over [`PendingBasketDeposits`]: the drain flushes one hotkey per block and /// resumes here, so every queued hotkey gets its turn even when some entries are /// deferred dust that stays in the map after its hotkey's visit. #[pallet::storage] pub type PendingBasketFlushCursor = StorageValue<_, Vec, OptionQuery>; /// Alpha-per-root-stake entitlement for a dividend batch whose valuation is deferred. #[pallet::storage] pub type DeferredBasketRates = StorageDoubleMap< _, Blake2_128Concat, T::AccountId, Identity, NetUid, crate::staking::DeferredBasketState, OptionQuery, >; /// Monotone identifier, retained across subnet reuse and pending-batch completion. #[pallet::storage] pub type DeferredBasketGeneration = StorageMap<_, Blake2_128Concat, T::AccountId, u64, ValueQuery>; /// Stake-change corrections. One bounded row per coldkey, like BasketClaimed. #[pallet::storage] pub type DeferredBasketDebts = StorageDoubleMap< _, Blake2_128Concat, T::AccountId, Blake2_128Concat, T::AccountId, frame_support::BoundedBTreeMap< NetUid, crate::staking::DeferredBasketDebt, ConstU32<{ crate::MAX_ROOT_CLAIM_WORK }>, >, ValueQuery, >; /// Final share/alpha conversion retained only until all stake-change corrections use it. #[pallet::storage] pub type DeferredBasketConversions = StorageNMap< _, ( NMapKey, NMapKey, NMapKey, ), crate::staking::DeferredBasketConversion, OptionQuery, >; /// TAO-per-root-stake accumulator for deferred credits sold during subnet dissolution. #[pallet::storage] pub type DeferredBasketCashRate = StorageMap<_, Blake2_128Concat, T::AccountId, I64F64, ValueQuery>; #[pallet::storage] pub type DeferredBasketCashClaimed = StorageDoubleMap< _, Blake2_128Concat, T::AccountId, Blake2_128Concat, T::AccountId, i128, ValueQuery, >; /// Sold deferred dividends held in the root reserves, outside the basket NAV. #[pallet::storage] pub type DeferredBasketCashReserve = StorageMap<_, Blake2_128Concat, T::AccountId, u64, ValueQuery>; // Coinbase /// ITEM ( global_block_emission ) #[deprecated(note = "Use calculate_block_emission() or the block emission RPC instead.")] #[pallet::storage] pub type BlockEmission = StorageValue<_, u64, ValueQuery, DefaultBlockEmission>; /// DMap ( hot, netuid ) --> emission | last hotkey emission on network. #[pallet::storage] pub type LastHotkeyEmissionOnNetuid = StorageDoubleMap< _, Blake2_128Concat, T::AccountId, Identity, NetUid, AlphaBalance, ValueQuery, DefaultZeroAlpha, >; // Staking Counters /// The Subtensor [`TotalIssuance`] represents the total issuance of tokens on the Bittensor network. /// /// It is comprised of three parts: /// * The total amount of issued tokens, tracked in the TotalIssuance of the Balances pallet /// * The total amount of tokens staked in the system, tracked in [`TotalStake`] /// * The total amount of tokens locked up for subnet reg, tracked in [`TotalSubnetLocked`] attained by iterating over subnet lock. /// /// Eventually, Bittensor should migrate to using Holds afterwhich time we will not require this /// separate accounting. /// ITEM ( maximum_number_of_networks ) #[pallet::storage] pub type SubnetLimit = StorageValue<_, u16, ValueQuery, DefaultSubnetLimit>; /// ITEM ( total_issuance ) #[pallet::storage] pub type TotalIssuance = StorageValue<_, TaoBalance, ValueQuery, DefaultTotalIssuance>; /// ITEM ( total_stake ) #[pallet::storage] pub type TotalStake = StorageValue<_, TaoBalance, ValueQuery, DefaultZeroTao>; /// ITEM ( moving_alpha ) -- subnet moving alpha. #[pallet::storage] pub type SubnetMovingAlpha = StorageValue<_, I96F32, ValueQuery, DefaultMovingAlpha>; /// MAP ( netuid ) --> moving_price | The subnet moving price. #[pallet::storage] pub type SubnetMovingPrice = StorageMap<_, Identity, NetUid, I96F32, ValueQuery, DefaultMovingPrice>; /// MAP ( netuid ) --> fast moving price | A fast EMA of the subnet's spot price /// (TAO per alpha, unclamped) with a [`BASKET_FAST_EMA_HALF_LIFE_BLOCKS`] half-life, /// updated once per block right after [`SubnetMovingPrice`] from the spot at the end of /// the previous block, so no extrinsic in the current block can move it. It remains an /// emission-independent valuation anchor and is required by `swap_basket` in the default /// [`BasketTradePriceReference::StrictestEmaAndSpot`] mode. Trades are refused while it /// is missing or zero; governance-selected spot-only mode does not require it. #[pallet::storage] pub type SubnetFastMovingPrice = StorageMap<_, Identity, NetUid, U64F64, OptionQuery>; /// MAP ( netuid ) --> root_prop | The subnet root proportion. #[pallet::storage] pub type RootProp = StorageMap<_, Identity, NetUid, U96F32, ValueQuery, DefaultRootProp>; /// MAP ( netuid ) --> total_volume | The total amount of TAO bought and sold since the start of the network. #[pallet::storage] pub type SubnetVolume = StorageMap<_, Identity, NetUid, u128, ValueQuery, DefaultZeroU128>; /// MAP ( netuid ) --> tao_in_subnet | Returns the amount of TAO in the subnet. #[pallet::storage] pub type SubnetTAO = StorageMap<_, Identity, NetUid, TaoBalance, ValueQuery, DefaultZeroTao>; /// MAP ( netuid ) --> alpha_in_emission | Returns the amount of alph in emission into the pool per block. #[pallet::storage] pub type SubnetAlphaInEmission = StorageMap<_, Identity, NetUid, AlphaBalance, ValueQuery, DefaultZeroAlpha>; /// MAP ( netuid ) --> subnet_emission_enabled /// /// When false, subnet pool-side emission is disabled for this subnet: /// `alpha_in`, `tao_in`, and `excess_tao` chain buys are all treated as zero. /// `alpha_out`, owner cut, root proportion, pending server emission, and pending /// validator emission are intentionally left unchanged. /// /// Defaults to true so existing subnets keep current behavior. #[pallet::storage] pub type SubnetEmissionEnabled = StorageMap<_, Identity, NetUid, bool, ValueQuery, DefaultTrue>; /// MAP ( netuid ) --> alpha_out_emission | Returns the amount of alpha out emission into the network per block. #[pallet::storage] pub type SubnetAlphaOutEmission = StorageMap<_, Identity, NetUid, AlphaBalance, ValueQuery, DefaultZeroAlpha>; /// MAP ( netuid ) --> tao_in_emission | Returns the amount of tao emitted into this subent on the last block. #[pallet::storage] pub type SubnetTaoInEmission = StorageMap<_, Identity, NetUid, TaoBalance, ValueQuery, DefaultZeroTao>; /// MAP ( netuid ) --> excess_tao | Returns the excess TAO swapped (chain buys) into this subnet on the last block. #[pallet::storage] pub type SubnetExcessTao = StorageMap<_, Identity, NetUid, TaoBalance, ValueQuery, DefaultZeroTao>; /// MAP ( netuid ) --> root_sell_tao | Returns the TAO received from root dividend sells on this subnet on the last block. #[pallet::storage] pub type SubnetRootSellTao = StorageMap<_, Identity, NetUid, TaoBalance, ValueQuery, DefaultZeroTao>; /// MAP ( netuid ) --> alpha_supply_in_pool | Returns the amount of alpha in the pool. #[pallet::storage] pub type SubnetAlphaIn = StorageMap<_, Identity, NetUid, AlphaBalance, ValueQuery, DefaultZeroAlpha>; /// MAP ( netuid ) --> alpha_supply_in_subnet | Returns the amount of alpha in the subnet. #[pallet::storage] pub type SubnetAlphaOut = StorageMap<_, Identity, NetUid, AlphaBalance, ValueQuery, DefaultZeroAlpha>; /// MAP ( netuid ) --> protocol_alpha | Returns the protocol-owned alpha cached for the subnet. #[pallet::storage] pub type SubnetProtocolAlpha = StorageMap<_, Identity, NetUid, AlphaBalance, ValueQuery, DefaultZeroAlpha>; /// MAP ( cold ) --> Vec | Maps coldkey to hotkeys that stake to it #[pallet::storage] pub type StakingHotkeys = StorageMap<_, Blake2_128Concat, T::AccountId, Vec, ValueQuery>; /// MAP ( cold ) --> Vec | Returns the vector of hotkeys controlled by this coldkey. #[pallet::storage] pub type OwnedHotkeys = StorageMap<_, Blake2_128Concat, T::AccountId, Vec, ValueQuery>; /// DMAP ( cold, netuid )--> hot | Returns the hotkey a coldkey will autostake to with mining rewards. #[pallet::storage] pub type AutoStakeDestination = StorageDoubleMap< _, Blake2_128Concat, T::AccountId, Identity, NetUid, T::AccountId, OptionQuery, >; /// DMAP ( hot, netuid )--> Vec | Returns a list of coldkeys that are autostaking to a hotkey #[pallet::storage] pub type AutoStakeDestinationColdkeys = StorageDoubleMap< _, Blake2_128Concat, T::AccountId, Identity, NetUid, Vec, ValueQuery, >; /// The delay after an announcement before a coldkey swap can be performed. #[pallet::storage] pub type ColdkeySwapAnnouncementDelay = StorageValue<_, BlockNumberFor, ValueQuery, DefaultColdkeySwapAnnouncementDelay>; /// The delay after the initial delay has passed before a new announcement can be made. #[pallet::storage] pub type ColdkeySwapReannouncementDelay = StorageValue<_, BlockNumberFor, ValueQuery, DefaultColdkeySwapReannouncementDelay>; /// A map of the coldkey swap announcements from a coldkey /// to the block number the coldkey swap can be performed. #[pallet::storage] pub type ColdkeySwapAnnouncements = StorageMap<_, Twox64Concat, T::AccountId, (BlockNumberFor, T::Hash), OptionQuery>; /// Destination account reserved by an in-flight coldkey-swap announcement. /// /// Announce takes the destination in cleartext so it can be validated before /// the fee; without a reservation a third party could register that address /// as their hotkey during the delay and force `NewColdKeyIsHotkey` at execute, /// repeatedly delaying recovery while the source stays announcement-restricted. #[pallet::storage] pub type ColdkeySwapDestinationReservations = StorageMap<_, Twox64Concat, T::AccountId, T::AccountId, OptionQuery>; /// Reverse index of [`ColdkeySwapDestinationReservations`]: announcer → reserved /// destination, so reannounce / clear / execute can free the prior reservation /// without scanning. #[pallet::storage] pub type ColdkeySwapReservedDestination = StorageMap<_, Twox64Concat, T::AccountId, T::AccountId, OptionQuery>; /// A map of the coldkey swap disputes from a coldkey to the /// block number the coldkey swap was disputed. Zero means root cleared the /// dispute but retained the recovery lock; a successful swap or full root reset releases it. #[pallet::storage] pub type ColdkeySwapDisputes = StorageMap<_, Twox64Concat, T::AccountId, BlockNumberFor, OptionQuery>; /// DMAP ( hot, netuid ) --> alpha | Returns the total amount of alpha a hotkey owns. #[pallet::storage] pub type TotalHotkeyAlpha = StorageDoubleMap< _, Blake2_128Concat, T::AccountId, Identity, NetUid, AlphaBalance, ValueQuery, DefaultZeroAlpha, >; /// MAP ( netuid ) --> alpha | Returns the total alpha staked across all hotkeys on a subnet. #[pallet::storage] pub type TotalAlphaStaked = StorageMap<_, Identity, NetUid, AlphaBalance, ValueQuery, DefaultZeroAlpha>; /// DMAP ( hot, netuid ) --> alpha | Returns the total amount of alpha a hotkey owned in the last epoch. #[pallet::storage] pub type TotalHotkeyAlphaLastEpoch = StorageDoubleMap< _, Blake2_128Concat, T::AccountId, Identity, NetUid, AlphaBalance, ValueQuery, DefaultZeroAlpha, >; /// DMAP ( hot, netuid ) --> total_alpha_shares | Returns the number of alpha shares for a hotkey on a subnet, stores SafeFloat. #[pallet::storage] pub type TotalHotkeySharesV2 = StorageDoubleMap< _, Blake2_128Concat, T::AccountId, // hot Identity, NetUid, // subnet SafeFloat, // Hotkey shares in unlimited precision ValueQuery, >; /// NMAP ( hot, cold, netuid ) --> alpha | Returns the alpha shares for a hotkey, coldkey, netuid triplet, stores SafeFloat. #[pallet::storage] pub type AlphaV2 = StorageNMap< _, ( NMapKey, // hot NMapKey, // cold NMapKey, // subnet ), SafeFloat, // Shares in unlimited precision ValueQuery, >; /// DMAP ( hot, netuid ) --> epoch | Generation of the hotkey's alpha share pool on a subnet. /// Incremented each time the pool is closed (its share denominator is written to zero /// because the pool holds no value). Share rows stamped with an older epoch belong to a /// closed pool and are read as absent, so they can never claim value deposited later. #[pallet::storage] pub type AlphaSharePoolEpoch = StorageDoubleMap< _, Blake2_128Concat, T::AccountId, // hot Identity, NetUid, // subnet u64, ValueQuery, >; /// NMAP ( hot, cold, netuid ) --> epoch | Pool epoch in which an `AlphaV2` (or legacy /// `Alpha`) share row was last written. Absent means epoch 0. #[pallet::storage] pub type AlphaShareEpoch = StorageNMap< _, ( NMapKey, // hot NMapKey, // cold NMapKey, // subnet ), u64, ValueQuery, >; /// DMAP ( coldkey, netuid, hotkey ) --> LockState | Exponential lock per coldkey per subnet. #[pallet::storage] pub type Lock = StorageNMap< _, ( NMapKey, // coldkey NMapKey, // subnet NMapKey, // hotkey ), LockState, OptionQuery, >; /// NMAP ( netuid, hotkey, coldkey ) --> () | Reverse index for non-zero locks targeting this hotkey on this subnet. #[pallet::storage] pub type LockingColdkeys = StorageNMap< _, ( NMapKey, // subnet NMapKey, // hotkey NMapKey, // coldkey ), (), OptionQuery, >; /// DMAP ( netuid, hotkey ) --> LockState | Total lock per hotkey per subnet. #[pallet::storage] pub type HotkeyLock = StorageDoubleMap< _, Identity, NetUid, // subnet Blake2_128Concat, T::AccountId, // hotkey LockState, // Total merged lock OptionQuery, >; /// DMAP ( netuid, hotkey ) --> LockState | Total decaying lock per hotkey per subnet. #[pallet::storage] pub type DecayingHotkeyLock = StorageDoubleMap< _, Identity, NetUid, // subnet Blake2_128Concat, T::AccountId, // hotkey LockState, // Total merged decaying lock OptionQuery, >; /// DMAP ( coldkey, netuid ) --> false | When present and false, this coldkey's lock is perpetual. /// Missing entries mean the lock decays by default. #[pallet::storage] pub type DecayingLock = StorageDoubleMap<_, Blake2_128Concat, T::AccountId, Identity, NetUid, bool, OptionQuery>; /// Default value for owner cut auto-locking. #[pallet::type_value] pub fn DefaultOwnerCutAutoLockEnabled() -> bool { false } /// MAP ( netuid ) --> bool | Whether subnet owner cut should be auto-locked. /// Missing entries default to false, so auto-locking is disabled unless explicitly enabled. #[pallet::storage] pub type OwnerCutAutoLockEnabled = StorageMap<_, Identity, NetUid, bool, ValueQuery, DefaultOwnerCutAutoLockEnabled>; /// Default unlock timescale: 50% lock back in ~90 days. #[pallet::type_value] pub fn DefaultUnlockRate() -> u64 { 934_866 } /// Default maturity timescale: 50% conviction in ~90 days. #[pallet::type_value] pub fn DefaultMaturityRate() -> u64 { 934_866 } /// ITEM( maturity_rate ) | Decay timescale in blocks for lock conviction. #[pallet::storage] pub type MaturityRate = StorageValue<_, u64, ValueQuery, DefaultMaturityRate>; /// ITEM( unlock_rate ) | Decay timescale in blocks for locked mass. #[pallet::storage] pub type UnlockRate = StorageValue<_, u64, ValueQuery, DefaultUnlockRate>; /// Contains last AlphaV2 storage map key to iterate (check first) #[pallet::storage] pub type AlphaV2MapLastKey = StorageValue<_, Option>, ValueQuery, DefaultAlphaIterationLastKey>; /// MAP ( netuid ) --> token_symbol | Returns the token symbol for a subnet. #[pallet::storage] pub type TokenSymbol = StorageMap<_, Identity, NetUid, Vec, ValueQuery, DefaultUnicodeVecU8>; /// MAP ( netuid ) --> subnet_tao_flow | Returns the TAO inflow-outflow balance. #[pallet::storage] pub type SubnetTaoFlow = StorageMap<_, Identity, NetUid, i64, ValueQuery, DefaultZeroI64>; /// MAP ( netuid ) --> subnet_ema_tao_flow | Returns the EMA of TAO inflow-outflow balance. #[pallet::storage] pub type SubnetEmaTaoFlow = StorageMap<_, Identity, NetUid, (u64, I64F64), OptionQuery>; /// ITEM --> net_tao_flow_enabled | When true, emission shares use net flow (user - protocol). When false, uses gross user flow only. #[pallet::type_value] pub fn DefaultNetTaoFlowEnabled() -> bool { true } #[pallet::storage] pub type NetTaoFlowEnabled = StorageValue<_, bool, ValueQuery, DefaultNetTaoFlowEnabled>; /// MAP ( netuid ) --> subnet_protocol_flow | Per-block accumulator for protocol cost (emission + chain buys - root sells). #[pallet::storage] pub type SubnetProtocolFlow = StorageMap<_, Identity, NetUid, i64, ValueQuery, DefaultZeroI64>; /// MAP ( netuid ) --> subnet_ema_protocol_flow | EMA of protocol cost flow, same smoothing as SubnetEmaTaoFlow. #[pallet::storage] pub type SubnetEmaProtocolFlow = StorageMap<_, Identity, NetUid, (u64, I64F64), OptionQuery>; /// Default value for flow cutoff. #[pallet::type_value] pub fn DefaultFlowCutoff() -> I64F64 { I64F64::saturating_from_num(0) } #[pallet::storage] /// ITEM --> TAO Flow Cutoff pub type TaoFlowCutoff = StorageValue<_, I64F64, ValueQuery, DefaultFlowCutoff>; #[pallet::type_value] /// Default value for flow normalization exponent. pub fn DefaultFlowNormExponent() -> U64F64 { U64F64::saturating_from_num(1) } #[pallet::storage] /// ITEM --> Flow Normalization Exponent (p) pub type FlowNormExponent = StorageValue<_, U64F64, ValueQuery, DefaultFlowNormExponent>; #[pallet::type_value] /// Default emission bar quantile (q). The bar theta is the demand share at /// which the sorted cumulative share distribution crosses q. pub fn DefaultEmissionBarQuantile() -> U64F64 { // 0.61: on the July 2026 distribution this lands the bar at the // uniform share (1/active_subnets), around rank 32. U64F64::saturating_from_num(0.61) } #[pallet::storage] /// ITEM --> Emission Bar Quantile (q) pub type EmissionBarQuantile = StorageValue<_, U64F64, ValueQuery, DefaultEmissionBarQuantile>; #[pallet::type_value] /// Default emission bar rank (N). N > 0 pins theta to the Nth-largest /// demand share, so the eligible set tracks rank N as the distribution /// shifts instead of drifting with a fixed q. 0 disables rank mode and /// the bar falls back to the q-mass quantile. pub fn DefaultEmissionBarRank() -> u16 { // Near the pre-upgrade q=0.75 crossing (~rank 28 on current demand) so the // upgrade does not shift the emission curve; rank mode then tracks N=32. 32 } #[pallet::storage] /// ITEM --> Emission Bar Rank (N). When non-zero, overrides the quantile. pub type EmissionBarRank = StorageValue<_, u16, ValueQuery, DefaultEmissionBarRank>; #[pallet::type_value] /// Default emission gate Hill exponent (h). Controls cliff sharpness at the bar. pub fn DefaultEmissionGateExponent() -> U64F64 { U64F64::saturating_from_num(3) } #[pallet::storage] /// ITEM --> Emission Gate Exponent (h) pub type EmissionGateExponent = StorageValue<_, U64F64, ValueQuery, DefaultEmissionGateExponent>; #[pallet::storage] /// ITEM --> Emission gate bar (theta): the q-mass demand-share threshold the /// Hill gate is centered on. Recomputed on a fixed block cadence from the /// same EMA-price shares that drive emission. Zero means "not yet computed" /// and disables the gate. pub type EmissionGateBar = StorageValue<_, U64F64, ValueQuery>; #[pallet::type_value] /// Default value for flow EMA smoothing. pub fn DefaultFlowEmaSmoothingFactor() -> u64 { // Example values: // half-life factor value i64 normalized (x 2^63) // 216000 (1 month) --> 0.000003209009576 ( 29_597_889_189_277) // 50400 (1 week) --> 0.000013752825678 (126_847_427_788_335) 29_597_889_189_277 } #[pallet::type_value] /// Flow EMA smoothing half-life. pub fn FlowHalfLife() -> u64 { 216_000 } #[pallet::storage] /// ITEM --> Flow EMA smoothing factor (flow alpha), u64 normalized pub type FlowEmaSmoothingFactor = StorageValue<_, u64, ValueQuery, DefaultFlowEmaSmoothingFactor>; // Global Parameters /// StorageItem Global Used Work. #[pallet::storage] pub type UsedWork = StorageMap<_, Identity, Vec, u64, ValueQuery>; /// ITEM( global_max_registrations_per_block ) #[pallet::storage] pub type MaxRegistrationsPerBlock = StorageMap<_, Identity, NetUid, u16, ValueQuery, DefaultMaxRegistrationsPerBlock>; /// ITEM( total_number_of_existing_networks ) #[pallet::storage] pub type TotalNetworks = StorageValue<_, u16, ValueQuery>; /// ITEM( network_immunity_period ) #[pallet::storage] pub type NetworkImmunityPeriod = StorageValue<_, u64, ValueQuery, DefaultNetworkImmunityPeriod>; /// ITEM( start_call_delay ) #[pallet::storage] pub type StartCallDelay = StorageValue<_, u64, ValueQuery, T::InitialStartCallDelay>; /// ITEM( min_network_lock_cost ) #[pallet::storage] pub type NetworkMinLockCost = StorageValue<_, TaoBalance, ValueQuery, DefaultNetworkMinLockCost>; /// ITEM( last_network_lock_cost ) #[pallet::storage] pub type NetworkLastLockCost = StorageValue<_, TaoBalance, ValueQuery, DefaultNetworkMinLockCost>; /// ITEM( network_lock_reduction_interval ) #[pallet::storage] pub type NetworkLockReductionInterval = StorageValue<_, u64, ValueQuery, DefaultNetworkLockReductionInterval>; /// ITEM( subnet_owner_cut ) /// /// Deprecated: superseded by the owner slot of [`SubnetEmissionWeights`]. Kept as the /// seed for `migrate_seed_subnet_emission_weights` and for legacy global views; no /// emission path reads it. #[pallet::storage] pub type SubnetOwnerCut = StorageValue<_, u16, ValueQuery, DefaultSubnetOwnerCut>; /// Default value for subnet owner cut enabled flag. #[pallet::type_value] pub fn DefaultOwnerCutEnabled() -> bool { true } /// MAP ( netuid ) --> owner_cut_enabled /// /// Deprecated: an owner slot of zero in [`SubnetEmissionWeights`] now means "disabled". /// Kept only as the seed for `migrate_seed_subnet_emission_weights`. #[pallet::storage] pub type OwnerCutEnabled = StorageMap<_, Identity, NetUid, bool, ValueQuery, DefaultOwnerCutEnabled>; /// Canonical emission vector for subnets that have never set one. #[pallet::type_value] pub fn DefaultSubnetEmissionWeights() -> EmissionWeightsVec { Pallet::::emission_weights_to_vec(Pallet::::default_emission_weights()) } /// MAP ( netuid ) --> `[burn, recycle, owner, validator, miner]` in `u64::MAX` parts, /// summing to one less the subnet's gamma shares. See `subnets::emission_weights`. #[pallet::storage] pub type SubnetEmissionWeights = StorageMap< _, Identity, NetUid, EmissionWeightsVec, ValueQuery, DefaultSubnetEmissionWeights, >; /// MAP ( netuid ) --> true when the subnet was registered through a lease. Persists after /// the lease ends; such subnets may not lower their owner cut below the launch default. #[pallet::storage] pub type SubnetCreatedViaLease = StorageMap<_, Identity, NetUid, bool, ValueQuery, DefaultFalse>; /// ITEM( network_rate_limit ) #[pallet::storage] pub type NetworkRateLimit = StorageValue<_, u64, ValueQuery, DefaultNetworkRateLimit>; /// ITEM( nominator_min_required_stake ) --- Factor of DefaultMinStake in per-mill format. #[pallet::storage] pub type NominatorMinRequiredStake = StorageValue<_, u64, ValueQuery, DefaultZeroU64>; /// ITEM( weights_version_key_rate_limit ) --- Rate limit in tempos. #[pallet::storage] pub type WeightsVersionKeyRateLimit = StorageValue<_, u64, ValueQuery, DefaultWeightsVersionKeyRateLimit>; // Rate Limiting /// MAP ( RateLimitKey ) --> Block number in which the last rate limited operation occured #[pallet::storage] pub type LastRateLimitedBlock = StorageMap<_, Identity, RateLimitKey, u64, ValueQuery, DefaultZeroU64>; // Subnet Locks /// MAP ( netuid ) --> transfer_toggle #[pallet::storage] pub type TransferToggle = StorageMap<_, Identity, NetUid, bool, ValueQuery, DefaultTrue>; /// MAP ( netuid ) --> total_subnet_locked #[pallet::storage] pub type SubnetLocked = StorageMap<_, Identity, NetUid, TaoBalance, ValueQuery, DefaultZeroTao>; /// MAP ( netuid ) --> largest_locked #[pallet::storage] pub type LargestLocked = StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultZeroU64>; // Tempos /// MAP ( netuid ) --> tempo #[pallet::storage] pub type Tempo = StorageMap<_, Identity, NetUid, u16, ValueQuery, DefaultTempo>; /// Lower bound for owner-set tempo. Also the fixed cooldown for `sudo_set_tempo`. pub const MIN_TEMPO: u16 = 360; /// Upper bound for owner-set tempo (≈ 7 days at 12 s/block). pub const MAX_TEMPO: u16 = 50_400; /// Lower bound for activity-cutoff factor (per-mille). 1_000 = one full tempo. pub const MIN_ACTIVITY_CUTOFF_FACTOR_MILLI: u32 = 1_000; /// Upper bound for activity-cutoff factor (per-mille). 50_000 = 50 tempos. pub const MAX_ACTIVITY_CUTOFF_FACTOR_MILLI: u32 = 50_000; /// Default activity-cutoff factor (per-mille). 13_889 ≈ legacy 5000-block cutoff /// at default tempo 360 (`13_889 * 360 / 1000 = 5_000`, exact via ceiling rounding). pub const INITIAL_ACTIVITY_CUTOFF_FACTOR_MILLI: u32 = 13_889; /// Default value for activity-cutoff factor (per-mille). #[pallet::type_value] pub fn DefaultActivityCutoffFactorMilli() -> u32 { INITIAL_ACTIVITY_CUTOFF_FACTOR_MILLI } /// MAP ( netuid ) --> last epoch attempt block (consumed slot). /// Drives normal-cadence scheduling and the admin freeze window. /// Advances on every `should_run_epoch == true` slot — including consistency-skipped slots — /// and on a successful `sudo_set_tempo` (cycle reset). #[pallet::storage] pub type LastEpochBlock = StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultZeroU64>; /// MAP ( netuid ) --> block at which a manually triggered epoch should fire. /// `0` means no trigger pending. Cleared after the triggered epoch runs. #[pallet::storage] pub type PendingEpochAt = StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultZeroU64>; /// MAP ( netuid ) --> monotonic epoch counter. /// Incremented by exactly one each time the subnet's epoch slot is consumed in `run_coinbase` #[pallet::storage] pub type SubnetEpochIndex = StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultZeroU64>; /// MAP ( netuid ) --> activity-cutoff factor in per-mille epochs (1/1000 granularity). /// Effective cutoff in blocks = `(factor × tempo) / 1000`, clamped to ≥ 1. #[pallet::storage] pub type ActivityCutoffFactorMilli = StorageMap<_, Identity, NetUid, u32, ValueQuery, DefaultActivityCutoffFactorMilli>; // Subnet Parameters /// MAP ( netuid ) --> block number of first emission #[pallet::storage] pub type FirstEmissionBlockNumber = StorageMap<_, Identity, NetUid, u64, OptionQuery>; /// MAP ( netuid ) --> subnet mechanism #[pallet::storage] pub type SubnetMechanism = StorageMap<_, Identity, NetUid, u16, ValueQuery, DefaultZeroU16>; /// MAP ( netuid ) --> subnetwork_n (Number of UIDs in the network). #[pallet::storage] pub type SubnetworkN = StorageMap<_, Identity, NetUid, u16, ValueQuery, DefaultN>; /// MAP ( netuid ) --> network_is_added #[pallet::storage] pub type NetworksAdded = StorageMap<_, Identity, NetUid, bool, ValueQuery, DefaultNeworksAdded>; /// MAP (netuid) --> user-visible subnet lifecycle state. /// /// Absence means that the netuid is neither an existing subnet nor one whose deferred /// dissolution cleanup is still in progress. #[pallet::storage] pub type SubnetState = StorageMap<_, Identity, NetUid, SubnetLifecycleState, OptionQuery>; /// DMAP ( hotkey, netuid ) --> bool #[pallet::storage] pub type IsNetworkMember = StorageDoubleMap< _, Blake2_128Concat, T::AccountId, Identity, NetUid, bool, ValueQuery, DefaultIsNetworkMember, >; /// MAP ( netuid ) --> network_registration_allowed #[pallet::storage] pub type NetworkRegistrationAllowed = StorageMap<_, Identity, NetUid, bool, ValueQuery, DefaultRegistrationAllowed>; /// MAP ( netuid ) --> network_pow_allowed #[pallet::storage] pub type NetworkPowRegistrationAllowed = StorageMap<_, Identity, NetUid, bool, ValueQuery>; /// Last accepted PoW challenge block per hotkey. Keeping one watermark /// prevents recent proof replay without an ever-growing used-seal list. #[pallet::storage] pub type LastPowRegistrationBlock = StorageMap<_, Blake2_128Concat, T::AccountId, u64, OptionQuery>; /// MAP ( netuid ) --> block_created #[pallet::storage] pub type NetworkRegisteredAt = StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultNetworkRegisteredAt>; /// MAP ( netuid ) --> registered_subnet_counter /// /// Monotonic counter incremented on every successful `do_register_network` /// for a given netuid. Consumers that persist per-netuid state keyed by /// `(user, netuid)` (e.g. the staking precompile `AllowancesStorage`) can /// mix the current counter value into their storage key so that entries /// written under a previous registration of the same netuid become /// unreachable after the netuid is re-registered, without requiring /// unbounded storage iteration on deregistration. #[pallet::storage] pub type RegisteredSubnetCounter = StorageMap<_, Identity, NetUid, u64, ValueQuery>; /// MAP ( netuid ) --> pending_server_emission #[pallet::storage] pub type PendingServerEmission = StorageMap<_, Identity, NetUid, AlphaBalance, ValueQuery, DefaultZeroAlpha>; /// MAP ( netuid ) --> pending_validator_emission #[pallet::storage] pub type PendingValidatorEmission = StorageMap<_, Identity, NetUid, AlphaBalance, ValueQuery, DefaultZeroAlpha>; /// MAP ( netuid ) --> pending_root_alpha_emission #[pallet::storage] pub type PendingRootAlphaDivs = StorageMap<_, Identity, NetUid, AlphaBalance, ValueQuery, DefaultZeroAlpha>; /// MAP ( netuid ) --> pending_owner_cut #[pallet::storage] pub type PendingOwnerCut = StorageMap<_, Identity, NetUid, AlphaBalance, ValueQuery, DefaultZeroAlpha>; /// MAP ( netuid ) --> cumulative alpha accrued to the owner slot since the subnet was /// registered (seeded at migration from the legacy global cut; written as an explicit /// zero at registration). The legacy lock refund on dissolution deducts this history, /// so it must not depend on the owner's current, adjustable share. An absent entry /// means the subnet pre-dates the seed migration; the refund then falls back to the /// legacy `issuance × SubnetOwnerCut` deduction (`owner_cut_alpha_for_lock_refund`). #[pallet::storage] pub type SubnetOwnerCutAccrued = StorageMap<_, Identity, NetUid, AlphaBalance, ValueQuery, DefaultZeroAlpha>; /// Default miner-burned proportion. #[pallet::type_value] pub fn DefaultMinerBurned() -> U96F32 { U96F32::saturating_from_num(0.0) } /// MAP ( netuid ) --> miner_burned | Proportion (0..1) of this tempo's miner /// (incentive) emission that was withheld from miners during emission distribution /// because the recipient hotkey is owned by the subnet owner (immune key). Counts /// emission that is either recycled or burned, so the value is independent of the /// subnet's RecycleOrBurn configuration. #[pallet::storage] pub type MinerBurned = StorageMap<_, Identity, NetUid, U96F32, ValueQuery, DefaultMinerBurned>; /// MAP ( netuid ) --> blocks_since_last_step, capped at the subnet's `tempo + 1` #[pallet::storage] pub type BlocksSinceLastStep = StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultBlocksSinceLastStep>; /// MAP ( netuid ) --> last_mechanism_step_block #[pallet::storage] pub type LastMechansimStepBlock = StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultLastMechanismStepBlock>; /// Last epoch that actually updated bonds. Frozen while Null consensus runs. #[pallet::storage] pub type LastYumaStepBlock = StorageMap<_, Identity, NetUid, u64, OptionQuery>; /// Explicit Null pruning continuation. Every completed batch leaves a usable subnet. #[pallet::storage] pub type NullPruningTarget = StorageMap<_, Identity, NetUid, u16, OptionQuery>; /// Restore the Yuma validator capacity when leaving sole-permit Null mode. #[pallet::storage] pub type SavedYumaMaxAllowedValidators = StorageMap<_, Identity, NetUid, u16, OptionQuery>; /// MAP ( netuid ) --> subnet_owner #[pallet::storage] pub type SubnetOwner = StorageMap<_, Identity, NetUid, T::AccountId, ValueQuery, DefaultSubnetOwner>; /// MAP ( netuid ) --> subnet_owner_hotkey #[pallet::storage] pub type SubnetOwnerHotkey = StorageMap<_, Identity, NetUid, T::AccountId, ValueQuery, DefaultSubnetOwner>; /// MAP ( netuid ) --> recycle_or_burn #[pallet::storage] pub type RecycleOrBurn = StorageMap<_, Identity, NetUid, RecycleOrBurnEnum, ValueQuery, DefaultRecycleOrBurn>; /// MAP ( netuid ) --> serving_rate_limit #[pallet::storage] pub type ServingRateLimit = StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultServingRateLimit>; /// MAP ( netuid ) --> Rho #[pallet::storage] pub type Rho = StorageMap<_, Identity, NetUid, u16, ValueQuery, DefaultRho>; /// MAP ( netuid ) --> AlphaSigmoidSteepness #[pallet::storage] pub type AlphaSigmoidSteepness = StorageMap<_, Identity, NetUid, i16, ValueQuery, DefaultAlphaSigmoidSteepness>; /// MAP ( netuid ) --> Kappa #[pallet::storage] pub type Kappa = StorageMap<_, Identity, NetUid, u16, ValueQuery, DefaultKappa>; /// MAP ( netuid ) --> registrations_this_interval #[pallet::storage] pub type RegistrationsThisInterval = StorageMap<_, Identity, NetUid, u16, ValueQuery>; /// MAP ( netuid ) --> pow_registrations_this_interval #[pallet::storage] pub type POWRegistrationsThisInterval = StorageMap<_, Identity, NetUid, u16, ValueQuery>; /// MAP ( netuid ) --> burn_registrations_this_interval #[pallet::storage] pub type BurnRegistrationsThisInterval = StorageMap<_, Identity, NetUid, u16, ValueQuery>; /// MAP ( netuid ) --> min_allowed_uids #[pallet::storage] pub type MinAllowedUids = StorageMap<_, Identity, NetUid, u16, ValueQuery, DefaultMinAllowedUids>; /// MAP ( netuid ) --> max_allowed_uids #[pallet::storage] pub type MaxAllowedUids = StorageMap<_, Identity, NetUid, u16, ValueQuery, DefaultMaxAllowedUids>; /// MAP ( netuid ) --> immunity_period #[pallet::storage] pub type ImmunityPeriod = StorageMap<_, Identity, NetUid, u16, ValueQuery, DefaultImmunityPeriod>; /// MAP ( netuid ) --> activity_cutoff // #[deprecated(note = "Replaced by `ActivityCutoffFactorMilli` (per-mille of `Tempo`).")] #[pallet::storage] pub type ActivityCutoff = StorageMap<_, Identity, NetUid, u16, ValueQuery, DefaultActivityCutoff>; #[pallet::type_value] /// Default maximum weights limit. pub fn DefaultMaxWeightsLimit() -> u16 { u16::MAX } /// MAP ( netuid ) --> max_weight_limit #[pallet::storage] pub type MaxWeightsLimit = StorageMap<_, Identity, NetUid, u16, ValueQuery, DefaultMaxWeightsLimit>; /// MAP ( netuid ) --> weights_version_key #[pallet::storage] pub type WeightsVersionKey = StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultWeightsVersionKey>; /// MAP ( netuid ) --> min_allowed_weights #[pallet::storage] pub type MinAllowedWeights = StorageMap<_, Identity, NetUid, u16, ValueQuery, DefaultMinAllowedWeights>; /// MAP ( netuid ) --> max_allowed_validators #[pallet::storage] pub type MaxAllowedValidators = StorageMap<_, Identity, NetUid, u16, ValueQuery, DefaultMaxAllowedValidators>; /// MAP ( netuid ) --> adjustment_interval #[pallet::storage] pub type AdjustmentInterval = StorageMap<_, Identity, NetUid, u16, ValueQuery, DefaultAdjustmentInterval>; /// MAP ( netuid ) --> bonds_moving_average #[pallet::storage] pub type BondsMovingAverage = StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultBondsMovingAverage>; /// MAP ( netuid ) --> bonds_penalty #[pallet::storage] pub type BondsPenalty = StorageMap<_, Identity, NetUid, u16, ValueQuery, DefaultBondsPenalty>; /// MAP ( netuid ) --> bonds_reset #[pallet::storage] pub type BondsResetOn = StorageMap<_, Identity, NetUid, bool, ValueQuery, DefaultBondsResetOn>; /// MAP ( netuid ) --> weights_set_rate_limit #[pallet::storage] pub type WeightsSetRateLimit = StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultWeightsSetRateLimit>; /// MAP ( netuid ) --> maximum Yuma timelocked commits per hotkey and queue epoch. #[pallet::storage] pub type MaxTimelockedCommitsPerHotkey = StorageMap<_, Identity, NetUid, u8, ValueQuery, DefaultMaxTimelockedCommitsPerHotkey>; /// MAP ( netuid ) --> validator_prune_len #[pallet::storage] pub type ValidatorPruneLen = StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultValidatorPruneLen>; /// MAP ( netuid ) --> scaling_law_power #[pallet::storage] pub type ScalingLawPower = StorageMap<_, Identity, NetUid, u16, ValueQuery, DefaultScalingLawPower>; /// MAP ( netuid ) --> target_registrations_this_interval #[pallet::storage] pub type TargetRegistrationsPerInterval = StorageMap<_, Identity, NetUid, u16, ValueQuery, DefaultTargetRegistrationsPerInterval>; /// MAP ( netuid ) --> adjustment_alpha #[pallet::storage] pub type AdjustmentAlpha = StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultAdjustmentAlpha>; /// MAP ( netuid ) --> commit reveal v2 weights are enabled #[pallet::storage] pub type CommitRevealWeightsEnabled = StorageMap<_, Identity, NetUid, bool, ValueQuery, DefaultCommitRevealWeightsEnabled>; /// MAP ( netuid ) --> Burn #[pallet::storage] pub type Burn = StorageMap<_, Identity, NetUid, TaoBalance, ValueQuery, DefaultBurn>; /// MAP ( netuid ) --> Difficulty #[pallet::storage] pub type Difficulty = StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultDifficulty>; /// MAP ( netuid ) --> MinBurn #[pallet::storage] pub type MinBurn = StorageMap<_, Identity, NetUid, TaoBalance, ValueQuery, DefaultMinBurn>; /// MAP ( netuid ) --> MaxBurn #[pallet::storage] pub type MaxBurn = StorageMap<_, Identity, NetUid, TaoBalance, ValueQuery, DefaultMaxBurn>; /// MAP ( netuid ) --> MinDifficulty #[pallet::storage] pub type MinDifficulty = StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultMinDifficulty>; /// MAP ( netuid ) --> MaxDifficulty #[pallet::storage] pub type MaxDifficulty = StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultMaxDifficulty>; /// MAP ( netuid ) --> Block at last adjustment. #[pallet::storage] pub type LastAdjustmentBlock = StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultLastAdjustmentBlock>; /// MAP ( netuid ) --> Registrations of this Block. #[pallet::storage] pub type RegistrationsThisBlock = StorageMap<_, Identity, NetUid, u16, ValueQuery, DefaultRegistrationsThisBlock>; /// MAP ( netuid ) --> Halving time of average moving price. #[pallet::storage] pub type EMAPriceHalvingBlocks = StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultEMAPriceMovingBlocks>; /// MAP ( netuid ) --> global_RAO_recycled_for_registration #[pallet::storage] pub type RAORecycledForRegistration = StorageMap< _, Identity, NetUid, TaoBalance, ValueQuery, DefaultRAORecycledForRegistration, >; /// ITEM ( max_epochs_per_block ) #[pallet::storage] pub type MaxEpochsPerBlock = StorageValue<_, u8, ValueQuery, DefaultMaxEpochsPerBlock>; /// ITEM ( tx_rate_limit ) #[pallet::storage] pub type TxRateLimit = StorageValue<_, u64, ValueQuery, DefaultTxRateLimit>; /// ITEM ( tx_delegate_take_rate_limit ) #[pallet::storage] pub type TxDelegateTakeRateLimit = StorageValue<_, u64, ValueQuery, DefaultTxDelegateTakeRateLimit>; /// ITEM ( tx_childkey_take_rate_limit ) #[pallet::storage] pub type TxChildkeyTakeRateLimit = StorageValue<_, u64, ValueQuery, DefaultTxChildKeyTakeRateLimit>; /// MAP ( netuid ) --> Whether or not Liquid Alpha is enabled #[pallet::storage] pub type LiquidAlphaOn = StorageMap<_, Blake2_128Concat, NetUid, bool, ValueQuery, DefaultLiquidAlpha>; /// MAP ( netuid ) --> Whether or not Yuma3 is enabled #[pallet::storage] pub type Yuma3On = StorageMap<_, Blake2_128Concat, NetUid, bool, ValueQuery, DefaultYuma3>; /// MAP ( netuid ) --> (alpha_low, alpha_high) #[pallet::storage] pub type AlphaValues = StorageMap<_, Identity, NetUid, (u16, u16), ValueQuery, DefaultAlphaValues>; /// Consensus mode used by liquid alpha for each subnet. #[pallet::storage] pub type LiquidAlphaConsensusMode = StorageMap<_, Identity, NetUid, ConsensusMode, ValueQuery, DefaultConsensusMode>; /// Epoch reward algorithm per subnet. Existing and new subnets default to Yuma. #[pallet::storage] pub type SubnetEpochConsensus = StorageMap<_, Identity, NetUid, EpochConsensus, ValueQuery>; /// MAP ( netuid ) --> If subtoken trading enabled #[pallet::storage] pub type SubtokenEnabled = StorageMap<_, Identity, NetUid, bool, ValueQuery, DefaultFalse>; /// ITEM ( dissolve_cleanup_queue ) Networks dissolved but some storage not removed yet #[pallet::storage] pub type DissolveCleanupQueue = StorageValue<_, Vec, ValueQuery>; /// ITEM ( current_dissolve_cleanup_status ) dissolve status for the network #[pallet::storage] pub type CurrentDissolveCleanupStatus = StorageValue<_, DissolveCleanupStatus, OptionQuery>; /// ITEM ( network_registration_queue ) Network registrations waiting to be executed. #[pallet::storage] pub type NetworkRegistrationQueue = StorageValue<_, Vec>>, ValueQuery>; /// MAP ( coldkey ) --> lock_id #[pallet::storage] pub type NetworkRegistrationLockId = StorageValue<_, u32, ValueQuery>; /// Escrow-backed queue entries. Absence denotes a pre-upgrade balance lock. /// Keep the existing queue encoding unchanged so pending registrations remain decodable. #[pallet::storage] pub type NetworkRegistrationEscrow = StorageMap<_, Identity, u32, (AccountIdOf, TaoBalance), OptionQuery>; // ======================================= // ==== VotingPower Storage ==== // ======================================= #[pallet::type_value] /// Default VotingPower EMA alpha value (0.1 represented as u64 with 18 decimals) /// alpha = 0.1 means slow response, 10% weight to new values per epoch pub fn DefaultVotingPowerEmaAlpha() -> u64 { 0_003_570_000_000_000_000 // 0.00357 * 10^18 = 2 weeks e-folding (time-constant) @ 361 // blocks per tempo // After 2 weeks -> EMA reaches 63.2% of a step change // After ~4 weeks -> 86.5% // After ~6 weeks -> 95% } #[pallet::storage] /// DMAP ( netuid, hotkey ) --> voting_power | EMA of stake for voting /// This tracks stake EMA updated every epoch when VotingPowerTrackingEnabled is true. /// Used by smart contracts to determine validator voting power for subnet governance. pub type VotingPower = StorageDoubleMap<_, Identity, NetUid, Blake2_128Concat, T::AccountId, u64, ValueQuery>; #[pallet::storage] /// MAP ( netuid ) --> total_voting_power | Sum of all validator voting-power /// entries on the subnet. Kept in sync with `VotingPower` so consumers can /// read the aggregate without iterating the complete validator map. pub type TotalVotingPower = StorageMap<_, Identity, NetUid, u64, ValueQuery>; #[pallet::storage] /// MAP ( netuid ) --> bool | Whether voting power tracking is enabled for this subnet. /// When enabled, VotingPower EMA is updated every epoch. Default is false. /// When disabled with disable_at_block set, tracking continues until that block. pub type VotingPowerTrackingEnabled = StorageMap<_, Identity, NetUid, bool, ValueQuery, DefaultFalse>; #[pallet::storage] /// MAP ( netuid ) --> block_number | Block at which voting power tracking will be disabled. /// When set (non-zero), tracking continues until this block, then automatically disables /// and clears VotingPower entries for the subnet. Provides a 14-day grace period. pub type VotingPowerDisableAtBlock = StorageMap<_, Identity, NetUid, u64, ValueQuery>; #[pallet::storage] /// MAP ( netuid ) --> u64 | EMA alpha value for voting power calculation. /// Higher alpha = faster response to stake changes. /// Stored as u64 with 18 decimal precision (1.0 = 10^18). /// Only settable by sudo/root. pub type VotingPowerEmaAlpha = StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultVotingPowerEmaAlpha>; #[pallet::type_value] /// Default value for burn keys limit pub fn DefaultImmuneOwnerUidsLimit() -> u16 { 1 } /// Maximum value for burn keys limit #[pallet::type_value] pub fn MaxImmuneOwnerUidsLimit() -> u16 { 10 } /// Minimum value for burn keys limit #[pallet::type_value] pub fn MinImmuneOwnerUidsLimit() -> u16 { 1 } /// MAP ( netuid ) --> Burn key limit #[pallet::storage] pub type ImmuneOwnerUidsLimit = StorageMap<_, Identity, NetUid, u16, ValueQuery, DefaultImmuneOwnerUidsLimit>; // Subnetwork Consensus Storage /// DMAP ( netuid ) --> stake_weight | weight for stake used in YC. #[pallet::storage] pub type StakeWeight = StorageMap<_, Identity, NetUid, Vec, ValueQuery, EmptyU16Vec>; /// DMAP ( netuid, hotkey ) --> uid #[pallet::storage] pub type Uids = StorageDoubleMap<_, Identity, NetUid, Blake2_128Concat, T::AccountId, u16, OptionQuery>; /// DMAP ( netuid, uid ) --> hotkey #[pallet::storage] pub type Keys = StorageDoubleMap< _, Identity, NetUid, Identity, u16, T::AccountId, ValueQuery, DefaultKey, >; /// MAP ( netuid ) --> (hotkey, se, ve) #[pallet::storage] pub type LoadedEmission = StorageMap<_, Identity, NetUid, Vec<(T::AccountId, u64, u64)>, OptionQuery>; /// MAP ( netuid ) --> active #[pallet::storage] pub type Active = StorageMap<_, Identity, NetUid, Vec, ValueQuery, EmptyBoolVec>; /// MAP ( netuid ) --> consensus #[pallet::storage] pub type Consensus = StorageMap<_, Identity, NetUid, Vec, ValueQuery, EmptyPerU16Vec>; /// MAP ( netuid storage index ) --> previous epoch consensus for each mechanism #[pallet::storage] pub type ConsensusByMechanism = StorageMap<_, Identity, NetUidStorageIndex, Vec, ValueQuery, EmptyPerU16Vec>; /// MAP ( netuid ) --> incentive #[pallet::storage] pub type Incentive = StorageMap<_, Identity, NetUidStorageIndex, Vec, ValueQuery, EmptyPerU16Vec>; /// MAP ( netuid ) --> dividends #[pallet::storage] pub type Dividends = StorageMap<_, Identity, NetUid, Vec, ValueQuery, EmptyPerU16Vec>; /// MAP ( netuid ) --> emission #[pallet::storage] pub type Emission = StorageMap<_, Identity, NetUid, Vec, ValueQuery>; /// MAP ( netuid ) --> last_update #[pallet::storage] pub type LastUpdate = StorageMap<_, Identity, NetUidStorageIndex, Vec, ValueQuery, EmptyU64Vec>; /// MAP ( netuid ) --> validator_trust #[pallet::storage] pub type ValidatorTrust = StorageMap<_, Identity, NetUid, Vec, ValueQuery, EmptyPerU16Vec>; /// MAP ( netuid ) --> validator_permit #[pallet::storage] pub type ValidatorPermit = StorageMap<_, Identity, NetUid, Vec, ValueQuery, EmptyBoolVec>; /// DMAP ( netuid, uid ) --> weights #[pallet::storage] pub type Weights = StorageDoubleMap< _, Identity, NetUidStorageIndex, Identity, u16, Vec<(u16, u16)>, ValueQuery, DefaultWeights, >; /// DMAP ( netuid, uid ) --> bonds #[pallet::storage] pub type Bonds = StorageDoubleMap< _, Identity, NetUidStorageIndex, Identity, u16, Vec<(u16, u16)>, ValueQuery, DefaultBonds, >; /// DMAP ( netuid, uid ) --> block_at_registration #[pallet::storage] pub type BlockAtRegistration = StorageDoubleMap< _, Identity, NetUid, Identity, u16, u64, ValueQuery, DefaultBlockAtRegistration, >; /// MAP ( netuid, hotkey ) --> axon_info #[pallet::storage] pub type Axons = StorageDoubleMap< _, Identity, NetUid, Blake2_128Concat, T::AccountId, AxonInfoOf, OptionQuery, >; /// MAP ( netuid, hotkey ) --> certificate #[pallet::storage] pub type NeuronCertificates = StorageDoubleMap< _, Identity, NetUid, Blake2_128Concat, T::AccountId, NeuronCertificateOf, OptionQuery, >; /// MAP ( netuid, hotkey ) --> prometheus_info #[pallet::storage] pub type Prometheus = StorageDoubleMap< _, Identity, NetUid, Blake2_128Concat, T::AccountId, PrometheusInfoOf, OptionQuery, >; /// MAP ( netuid, hotkey ) --> service_info #[pallet::storage] pub type Services = StorageDoubleMap< _, Identity, NetUid, Blake2_128Concat, T::AccountId, ServiceInfo, OptionQuery, >; /// MAP ( coldkey ) --> identity #[pallet::storage] pub type IdentitiesV2 = StorageMap<_, Blake2_128Concat, T::AccountId, ChainIdentityOfV2, OptionQuery>; /// MAP ( netuid ) --> SubnetIdentityOfV3 #[pallet::storage] pub type SubnetIdentitiesV3 = StorageMap<_, Blake2_128Concat, NetUid, SubnetIdentityOfV3, OptionQuery>; // Axon / Promo Endpoints /// NMAP ( hot, netuid, name ) --> last_block | Returns the last block of a transaction for a given key, netuid, and name. #[pallet::storage] pub type TransactionKeyLastBlock = StorageNMap< _, ( NMapKey, // hot NMapKey, // netuid NMapKey, // extrinsic enum. ), u64, ValueQuery, >; /// MAP ( key ) --> last_block #[deprecated] #[pallet::storage] pub type LastTxBlock = StorageMap<_, Identity, T::AccountId, u64, ValueQuery, DefaultLastTxBlock>; /// MAP ( key ) --> last_tx_block_childkey_take #[deprecated] #[pallet::storage] pub type LastTxBlockChildKeyTake = StorageMap<_, Identity, T::AccountId, u64, ValueQuery, DefaultLastTxBlock>; /// MAP ( key ) --> last_tx_block_delegate_take #[deprecated] #[pallet::storage] pub type LastTxBlockDelegateTake = StorageMap<_, Identity, T::AccountId, u64, ValueQuery, DefaultLastTxBlock>; /// ITEM( weights_min_stake ) // FIXME: this storage is used interchangably for alpha/tao #[pallet::storage] pub type StakeThreshold = StorageValue<_, u64, ValueQuery, DefaultStakeThreshold>; /// MAP (netuid, who) --> VecDeque<(hash, commit_epoch, commit_block, _unused)> /// Stores a queue of commit-reveal-v2 commits for an account on a given netuid. #[pallet::storage] pub type WeightCommits = StorageDoubleMap< _, Twox64Concat, NetUidStorageIndex, Twox64Concat, T::AccountId, VecDeque<(H256, u64, u64, u64)>, OptionQuery, >; /// MAP (netuid, epoch) → VecDeque<(who, commit_block, ciphertext, reveal_round)> /// Stores a queue of weight commits for an account on a given subnet. #[pallet::storage] pub type TimelockedWeightCommits = StorageDoubleMap< _, Twox64Concat, NetUidStorageIndex, Twox64Concat, u64, // epoch key VecDeque<( T::AccountId, u64, // commit_block BoundedVec>, RoundNumber, )>, ValueQuery, >; /// MAP (netuid, epoch) → VecDeque<(who, ciphertext, reveal_round)> /// Deprecated: superseded by `CRV3WeightCommitsV2`. #[pallet::storage] pub type CRV3WeightCommits = StorageDoubleMap< _, Twox64Concat, NetUidStorageIndex, Twox64Concat, u64, // epoch key VecDeque<( T::AccountId, BoundedVec>, RoundNumber, )>, ValueQuery, >; /// MAP (netuid, epoch) → VecDeque<(who, commit_block, ciphertext, reveal_round)> /// Deprecated: superseded by `TimelockedWeightCommits`. #[pallet::storage] pub type CRV3WeightCommitsV2 = StorageDoubleMap< _, Twox64Concat, NetUidStorageIndex, Twox64Concat, u64, // epoch key VecDeque<( T::AccountId, u64, // commit_block BoundedVec>, RoundNumber, )>, ValueQuery, >; /// Map (netuid) --> Number of epochs allowed for commit reveal periods #[pallet::storage] pub type RevealPeriodEpochs = StorageMap<_, Twox64Concat, NetUid, u64, ValueQuery, DefaultRevealPeriodEpochs>; /// Map (coldkey, hotkey) --> u64 the last block at which **root** stake was /// added/removed/claimed for that pair. Used solely as the age basis for /// `RootStakeUnlockInterval`. Non-root stake ops must not write this map. #[pallet::storage] pub type LastColdkeyHotkeyStakeBlock = StorageDoubleMap< _, Twox64Concat, T::AccountId, Twox64Concat, T::AccountId, u64, OptionQuery, >; /// Minimum number of blocks root (netuid 0) stake must be held before it can be /// removed from root (via `remove_stake`, move/swap/transfer off root, etc.), /// keyed off `LastColdkeyHotkeyStakeBlock`. `0` disables the hold (default), /// preserving legacy behaviour. When set >= one tempo it neutralises epoch-boundary /// "just-in-time" dividend sniping: root stake is 1:1 TAO with no AMM slippage, so /// without this friction a sniper can stake right before a boundary, capture a full /// tempo's root dividend pro-rata to instantaneous stake, and exit immediately. #[pallet::storage] pub type RootStakeUnlockInterval = StorageValue<_, u64, ValueQuery>; /// Master switch for `swap_basket` (validator-directed basket rebalancing). Defaults to /// OFF. Flipped on via `AdminUtils::sudo_set_basket_trading_enabled`. Gates only the /// trade path: deposits, claims, dividend accrual, and all read paths are unaffected. #[pallet::storage] pub type BasketTradingEnabled = StorageValue<_, bool, ValueQuery>; /// --- SET ( validator_hotkey ) --> basket trading frozen for this fund. /// /// Per-fund kill switch set by governance (`AdminUtils::sudo_set_basket_trading_frozen`), /// e.g. after a suspected key compromise. A frozen fund still accepts deposits and pays /// claims; only `swap_basket` is refused. Follows the fund on hotkey swap. #[pallet::storage] pub type BasketTradingFrozen = StorageMap<_, Blake2_128Concat, T::AccountId, (), OptionQuery>; #[pallet::type_value] /// Default daily turnover budget for basket trading: a bucket of 10% of fund NAV that /// refills over one day (u16-normalized; 6553/65535). pub fn DefaultBasketDailyTurnoverCap() -> u16 { crate::DEFAULT_BASKET_DAILY_TURNOVER_CAP } /// --- ITEM --> capacity of a fund's `swap_basket` turnover bucket as a u16-normalized /// share of the fund's NAV (`u16::MAX` = 100%). The bucket refills continuously over /// [`BasketTradeRefillBlocks`], so at most one capacity can be pushed through the fund /// at any instant. Each leg is also bounded by [`BasketTradeMaxSlippageBps`] around the /// reference selected by [`BasketTradePriceReferenceMode`]. Set via /// `AdminUtils::sudo_set_basket_daily_turnover_cap`. #[pallet::storage] pub type BasketDailyTurnoverCap = StorageValue<_, u16, ValueQuery, DefaultBasketDailyTurnoverCap>; #[pallet::type_value] /// Default maximum deviation of a basket trade leg from its price reference: 2%. pub fn DefaultBasketTradeMaxSlippageBps() -> u16 { crate::DEFAULT_BASKET_TRADE_MAX_SLIPPAGE_BPS } /// Maximum `swap_basket` leg price deviation from its selected reference, in basis /// points (`10_000` = 100%). Defaults to 2% around the strictest EMA/spot reference. /// Set via `AdminUtils::sudo_set_basket_trade_max_slippage_bps`. #[pallet::storage] pub type BasketTradeMaxSlippageBps = StorageValue<_, u16, ValueQuery, DefaultBasketTradeMaxSlippageBps>; #[pallet::type_value] /// Default full turnover-bucket refill period: 7200 blocks. pub fn DefaultBasketTradeRefillBlocks() -> u64 { crate::DEFAULT_BASKET_TRADE_REFILL_BLOCKS } /// Blocks for an empty `swap_basket` turnover bucket to refill completely and for /// destination-pool flow usage to decay to zero. Defaults to 7200 blocks. Set via /// `AdminUtils::sudo_set_basket_trade_refill_blocks`; zero is rejected. #[pallet::storage] pub type BasketTradeRefillBlocks = StorageValue<_, u64, ValueQuery, DefaultBasketTradeRefillBlocks>; #[pallet::type_value] /// Default basket trade price reference: preserve the strictest EMA/spot behavior. pub fn DefaultBasketTradePriceReference() -> BasketTradePriceReference { BasketTradePriceReference::StrictestEmaAndSpot } /// Price reference for `swap_basket` leg bounds. Defaults to the strictest of slow EMA, /// fast EMA, and spot. Governance can select `SpotOnly` through /// `AdminUtils::sudo_set_basket_trade_price_reference`. #[pallet::storage] pub type BasketTradePriceReferenceMode = StorageValue<_, BasketTradePriceReference, ValueQuery, DefaultBasketTradePriceReference>; #[pallet::type_value] /// Default minimum basket trade value: 0.5 TAO, in rao. pub fn DefaultBasketMinTradeTao() -> u64 { crate::MIN_BASKET_TRADE_TAO } /// Minimum TAO value, in rao, through the middle of each basket trade leg. /// Defaults to 0.5 TAO. Set via `AdminUtils::sudo_set_basket_min_trade_tao`. /// The effective minimum is also bounded below by `DefaultMinStake`. #[pallet::storage] pub type BasketMinTradeTao = StorageValue<_, u64, ValueQuery, DefaultBasketMinTradeTao>; #[pallet::type_value] /// Default liquidity cap for basket trading: a holding may not exceed 10% of the /// destination pool's alpha reserve (u16-normalized; 6553/65535). pub fn DefaultBasketLiquidityCap() -> u16 { crate::DEFAULT_BASKET_LIQUIDITY_CAP } /// --- ITEM --> max share of a subnet's alpha reserve (`SubnetAlphaIn`) a fund may hold /// on that subnet after a `swap_basket` buy (u16-normalized, `u16::MAX` = 100%). /// /// The concentration cap ([`BasketConcentrationCap`]) marks holdings at realizable value, which /// is bounded by the pool's TAO reserve, so on a thin pool a fund could keep buying while /// counterparties sell back into its own price support and the realizable share never /// grows. This cap bounds the fund's exposure to any one pool's liquidity instead: with /// cap `L` the value at risk on a pool with TAO reserve `R` is about `R × L² / (1 + L)` /// (≈ 1% of `R` at 10%). Set via `AdminUtils::sudo_set_basket_liquidity_cap`. #[pallet::storage] pub type BasketLiquidityCap = StorageValue<_, u16, ValueQuery, DefaultBasketLiquidityCap>; #[pallet::type_value] /// Default cap of the row-dust floor for root claims: 1 TAO (in rao). pub fn DefaultBasketClaimRowDustCapTao() -> u64 { crate::DEFAULT_BASKET_CLAIM_ROW_DUST_CAP_TAO } /// --- ITEM --> cap, in rao, of the row-dust floor of a root claim. A claim skips a fund /// row entirely when the fund's whole holding on that subnet is worth less than /// `min(this cap, BasketClaimRowDustBps × anchored NAV)` at the anchored mark: the row is /// neither sold nor paid, and the claimant's slice of it (below the floor by /// construction) stays in the fund for the remaining holders. `0` disables the row skip. /// Set via `AdminUtils::sudo_set_basket_claim_dust`. #[pallet::storage] pub type BasketClaimRowDustCapTao = StorageValue<_, u64, ValueQuery, DefaultBasketClaimRowDustCapTao>; #[pallet::type_value] /// Default relative row-dust floor for root claims: 10 bps (0.1%) of guarded NAV. pub fn DefaultBasketClaimRowDustBps() -> u16 { crate::DEFAULT_BASKET_CLAIM_ROW_DUST_BPS } /// --- ITEM --> relative part of the row-dust floor, in basis points of the fund's /// anchored NAV (see [`BasketClaimRowDustCapTao`]). Keeps the floor proportionate for /// small funds. `0` disables the row skip. Set via `AdminUtils::sudo_set_basket_claim_dust`. #[pallet::storage] pub type BasketClaimRowDustBps = StorageValue<_, u16, ValueQuery, DefaultBasketClaimRowDustBps>; #[pallet::type_value] /// Default slice-dust floor for root claims: 0.0001 TAO (in rao). pub fn DefaultBasketClaimSliceDustTao() -> u64 { crate::DEFAULT_BASKET_CLAIM_SLICE_DUST_TAO } /// --- ITEM --> rao value below which a root claim skips a fund row for this claimant: /// when the claimant's pro-rata slice of the row is worth less than this at the anchored /// mark, the row is neither sold nor paid and the slice stays in the fund for the /// remaining holders. `0` disables the skip. Set via /// `AdminUtils::sudo_set_basket_claim_dust`. #[pallet::storage] pub type BasketClaimSliceDustTao = StorageValue<_, u64, ValueQuery, DefaultBasketClaimSliceDustTao>; #[pallet::type_value] /// Default forfeit cap for root-claim dust skips: 0.01 TAO (in rao). pub fn DefaultBasketClaimForfeitCapTao() -> u64 { crate::DEFAULT_BASKET_CLAIM_FORFEIT_CAP_TAO } /// --- ITEM --> rao value a claimant's slice of a row may be worth, at the anchored /// mark, and still be skipped by either dust rule. A row the rules mark as dust whose /// slice for this claimant is worth more than this is sold as before, so no single /// skipped slice ever leaves more than this in the fund. `0` turns every skip off (a /// slice can only be skipped if it is worth nothing). Set via /// `AdminUtils::sudo_set_basket_claim_dust`. #[pallet::storage] pub type BasketClaimForfeitCapTao = StorageValue<_, u64, ValueQuery, DefaultBasketClaimForfeitCapTao>; /// --- MAP ( validator_hotkey ) --> `(tao_available, last_refill_block)` of the fund's /// `swap_basket` turnover bucket. A missing row is a full bucket (a new fund starts full). /// On each trade the bucket is refilled for the blocks elapsed since `last_refill_block` /// at `budget / BasketTradeRefillBlocks` per block, clamped to one budget (NAV at /// that moment), then the TAO through the middle of the swap is taken out. Follows the /// fund on hotkey swap (lower level, later refill block). #[pallet::storage] pub type BasketTradeBucket = StorageMap<_, Blake2_128Concat, T::AccountId, (u64, u64), OptionQuery>; /// --- MAP ( validator_hotkey ) --> `(block, extrinsic_index)` of the last transaction /// in which the fund got a row that its single-hotkey claim weight had not counted: by /// a `swap_basket` buy, a hotkey swap, or a coldkey swap into the escrow account. /// `claim_root_with_hotkey` declares its weight from the fund's rows before the /// transaction runs, so a claim later in that same transaction is refused /// (`RootClaimTooHeavy`). A hotkey swap removes the record of the old hotkey. #[pallet::storage] pub type BasketRowsOpenedAt = StorageMap<_, Blake2_128Concat, T::AccountId, (u64, u32), OptionQuery>; /// --- MAP ( validator_hotkey ) --> `(block, extrinsic_index, count)`: the rows and the /// queued dividend credits of the fund, as the transaction `(block, extrinsic_index)` /// counted them for the weight of `claim_root_with_hotkey`. `count` is `None` for a /// fund above the limit of one claim. The weight of that call is computed several /// times in one transaction: by the block executive, by the fee logic, and by each /// batch or proxy that holds the call. The first of them counts the fund and writes /// this record. The others, and the claim, read it. A record of an earlier /// transaction has no effect. Only a hotkey whose fund has a row or a queued credit /// gets a record, and a hotkey swap removes it: at most one entry for each fund. #[pallet::storage] pub type BasketRowsCountedAt = StorageMap< _, Blake2_128Concat, T::AccountId, (u64, u32, Option), OptionQuery, >; /// --- MAP ( validator_hotkey, netuid ) --> `(alpha_bought, last_block)` of /// destination-pool flow used by `swap_basket` in the current refill window. /// /// The standing-position liquidity cap resets when the fund sells the holding /// back to zero. This map does not: it accumulates alpha bought into `netuid` /// and decays to zero over [`BasketTradeRefillBlocks`], so /// accumulate/unwind cycles cannot spend the turnover budget as band slack. /// Follows the fund on hotkey swap (higher used, later block). #[pallet::storage] pub type BasketLiquidityUsed = StorageDoubleMap< _, Blake2_128Concat, T::AccountId, Identity, NetUid, (u64, u64), OptionQuery, >; #[pallet::type_value] /// Default concentration cap for a single basket holding: 1/16 of fund NAV /// (u16-normalized; 4096/65535 admits exactly 16 equal holdings). pub fn DefaultBasketConcentrationCap() -> u16 { crate::DEFAULT_BASKET_CONCENTRATION_CAP } /// --- ITEM --> max share of a fund's NAV one holding may reach through a `swap_basket` /// buy, u16-normalized (`u16::MAX` = 100%). Holdings are marked at realizable value. A /// cap of 1/16 forces a traded fund to spread across at least 16 holdings, so trading /// cannot recreate single-subnet concentration. Only buys are checked: a holding that /// grows past the cap through price appreciation or in-place dividends is left alone /// (it can be sold down, not topped up). Skipped at check time while fewer subnets /// exist than the cap demands (young chains, tests). Set via /// `AdminUtils::sudo_set_basket_concentration_cap`. #[pallet::storage] pub type BasketConcentrationCap = StorageValue<_, u16, ValueQuery, DefaultBasketConcentrationCap>; #[pallet::storage] // --- MAP(netuid ) --> Root claim threshold /// Basket redemption is fund-level (not per-subnet), so only the `NetUid::ROOT` entry is /// consulted: a claim below `RootClaimableThreshold[ROOT]` TAO is skipped as dust. Other /// entries are inert. pub type RootClaimableThreshold = StorageMap<_, Blake2_128Concat, NetUid, I96F32, ValueQuery, DefaultMinRootClaimAmount>; /// --- MAP ( hot ) --> MAP(netuid ) --> claimable_dividends | LEGACY per-subnet root /// claimable rates. Superseded by the unified [`BasketRate`]; only read (and drained) by /// `migrate_seed_beta_basket`. Do not use in runtime logic. #[pallet::storage] pub type RootClaimable = StorageMap< _, Blake2_128Concat, T::AccountId, BTreeMap, ValueQuery, DefaultRootClaimable, >; /// LEGACY per-subnet claimed watermarks. Superseded by the unified [`BasketClaimed`]; only /// read (and drained) by `migrate_seed_beta_basket`. Do not use in runtime logic. #[pallet::storage] pub type RootClaimed = StorageNMap< _, ( NMapKey, // subnet NMapKey, // hot NMapKey, // cold ), u128, ValueQuery, >; /// --- MAP ( validator_hotkey ) --> total outstanding basket fund shares `P`. /// /// A validator's beta basket is a single fund: its holdings are the escrow stake positions /// `(hotkey, escrow, netuid)` across subnets (the root slot is the fund's TAO/cash position), /// and its net asset value `N` is the realizable (slippage-aware) TAO value of those /// holdings. Stakers' entitlements are denominated in *fund shares*, never in any particular /// subnet's alpha: dividend deposits mint `value_added * P / N` shares, where `value_added` /// is the realizable NAV the deposit actually added, and redemption pays the staker's owed /// share fraction `owed / P` of every holding, sold pro-rata. Direct `stake_into_basket` /// deposits additionally cap that NAV-priced mint by the fraction of every existing holding /// actually acquired, so their proportional redemption cannot sell more units than they /// bought. Their shares are credited through the signed [`BasketClaimed`] watermark. Because /// entitlement is decoupled from composition, holdings can be rebalanced (validator-directed /// trading, dissolution conversions) without touching any staker's claim. #[pallet::storage] pub type BasketShares = StorageMap<_, Blake2_128Concat, T::AccountId, u64, ValueQuery, DefaultZeroU64>; /// --- MAP ( validator_hotkey ) --> cumulative fund-shares-per-root-stake accumulator. /// /// Each dividend deposit increments this by `minted_shares / total_root_stake`. A staker's /// gross entitlement is `BasketRate * root_stake`; net owed subtracts their /// [`BasketClaimed`] watermark. Stake additions/removals rebase the watermark by /// `rate * delta` so changing root stake never retroactively grants or removes accrued /// claimable. #[pallet::storage] pub type BasketRate = StorageMap<_, Blake2_128Concat, T::AccountId, I96F32, ValueQuery, DefaultZeroI96F32>; /// --- MAP ( validator_hotkey ) --> the fund's frozen display baseline (see /// [`BetaBaselineOf`]). /// /// Stamped once at the fund's first share mint (or seeded from the frozen SDK table by /// `migrate_stamp_beta_baselines` for funds that predate on-chain stamping) and never /// rewritten, so the spliced display/stake prices stay continuous for the fund's whole /// life. Scoped to one fund *life*: follows the fund on hotkey swap, and is retired /// when the last share is claimed or a dust revival starts a new life (see /// `retire_beta_display_state`), so an entry exists only while the fund has /// outstanding shares. Also absent for funds born before this storage existed that /// have not minted since; such funds price provisionally at the live index level /// until their next mint stamps them. #[pallet::storage] pub type BetaBaseline = StorageMap<_, Blake2_128Concat, T::AccountId, BetaBaselineOf, OptionQuery>; /// --- MAP ( validator_hotkey ) --> the fund's staker total-return accumulator. /// /// The one canonical root-staker return series. Starts at 1.0 and multiplies by /// `1 + stakers_value / total_root_stake` on every dividend share mint — the value that /// deposit actually added per rao of claimant root stake, locked in at the deposit's own /// (realizable) pricing. Flows never move it; only dividends do. The staker return of /// τ1 staked over any window (claim-and-restake convention) is `Twr(t1) / Twr(t0) - 1`, /// so any two archive samples agree for every consumer. Everything staker-facing /// derives from it: `stake_price` is this accumulator spliced onto the stake index /// (`tr_splice × Twr`), and the index chains its relatives. The rate-delta figure /// `(BasketRate - rate0) * price` is *not* an alternative return series — it is the /// pending-entitlement mark (`staker_yield`), which re-values all accrued β at today's /// price. Accumulates from the upgrade that introduced it; earlier history lives in the /// seeded `tr_splice` (see `migrate_stamp_beta_baselines`). Like [`BetaBaseline`], /// scoped to one fund life: moves on hotkey swap and is retired when the fund drains or /// a dust revival starts a new life. #[pallet::storage] pub type BasketTwr = StorageMap<_, Blake2_128Concat, T::AccountId, U64F64, ValueQuery, DefaultOneU64F64>; /// --- ITEM --> the latest published beta-index snapshot (see [`BetaIndexSnapshotOf`]). /// /// Refreshed by the paged background sweep in block processing; read by baseline stamps /// so no state-changing path ever sweeps every fund inline. Absent until the first /// pass after genesis (or the runtime upgrade that introduced it) completes; stamps /// simply wait for the next mint while it is absent. #[pallet::storage] pub type BetaIndexSnapshot = StorageValue<_, BetaIndexSnapshotOf, OptionQuery>; /// --- ITEM --> in-progress paged beta-index sweep (see [`BetaIndexSweepOf`]). /// /// Present only mid-pass. `advance_beta_index_sweep` processes one strictly bounded /// page per block and clears this on completion. #[pallet::storage] pub type BetaIndexSweep = StorageValue<_, BetaIndexSweepOf, OptionQuery>; /// --- MAP ( validator_hotkey ) --> the fund's last completed index-sweep sample /// (see [`BetaIndexFundSampleOf`]). /// /// Written by the sweep as it visits each fund (the current pass's sample replaces the /// previous pass's in the same visit) and consumed as the start-of-period state of the /// next pass's price relative. Removed when the fund becomes unpriceable, retires, or /// starts a new life, so no relative ever chains across a gap in the fund's history. #[pallet::storage] pub type BetaIndexFundSample = StorageMap<_, Blake2_128Concat, T::AccountId, BetaIndexFundSampleOf, OptionQuery>; /// --- DMAP ( validator_hotkey, staker_coldkey ) --> fund shares already claimed (watermark). /// /// Signed on purpose, for two reasons. First, stake-change rebasing /// (`claimed ± rate * delta`) must be exact in both directions: with an unsigned floor, /// unstaking root before claiming would clip the rebase at zero, silently forfeiting the /// staker's accrued entitlement and permanently stranding the matching shares (and their /// escrow value) in the fund. Second, this map doubles as the grant ledger for direct /// deposits: `stake_into_basket` credits its minted shares by *decrementing* the watermark /// (`owed = rate * root_stake - claimed`), so a persistent negative value is an intentional /// unconditional share grant, not a rebasing artifact. #[pallet::storage] pub type BasketClaimed = StorageDoubleMap< _, Blake2_128Concat, T::AccountId, Blake2_128Concat, T::AccountId, i128, ValueQuery, >; /// --- MAP ( validator_hotkey ) --> lifetime realizable TAO value deposited into the basket. /// /// Cumulative sum of every deposit's `value_added`: the realizable NAV the deposit actually /// added (net of buy slippage and fees), deliberately less than the raw TAO deployed. Both /// dividend deposits and direct `stake_into_basket` deposits accumulate here, and dividend /// deposits add their full `value_added` even though only the stakers' attribution fraction /// mints shares. Together with [`BasketRedeemedTao`] this makes lifetime fund performance /// (`(NAV + redeemed) / deposited`) and deposit-rate metrics computable from two storage /// reads, with no event indexing. Follows the fund across hotkey swaps. #[pallet::storage] pub type BasketDepositedTao = StorageMap<_, Blake2_128Concat, T::AccountId, TaoBalance, ValueQuery>; /// --- MAP ( validator_hotkey ) --> lifetime TAO redeemed (claimed) out of the basket. /// /// Cumulative sum of every claim's realized payout. See [`BasketDepositedTao`]. #[pallet::storage] pub type BasketRedeemedTao = StorageMap<_, Blake2_128Concat, T::AccountId, TaoBalance, ValueQuery>; #[pallet::storage] // --- MAP ( u64 ) --> coldkey | Maps coldkeys that have stake to an index pub type StakingColdkeysByIndex = StorageMap<_, Identity, u64, T::AccountId, OptionQuery>; #[pallet::storage] // --- MAP ( coldkey ) --> index | Maps index that have stake to a coldkey pub type StakingColdkeys = StorageMap<_, Identity, T::AccountId, u64, OptionQuery>; #[pallet::storage] // --- Value --> num_staking_coldkeys pub type NumStakingColdkeys = StorageValue<_, u64, ValueQuery, DefaultZeroU64>; // EVM related storage /// DMAP (netuid, uid) --> (H160, last_block_where_ownership_was_proven) #[pallet::storage] pub type AssociatedEvmAddress = StorageDoubleMap<_, Twox64Concat, NetUid, Twox64Concat, u16, (H160, u64), OptionQuery>; /// DMAP (netuid, H160) --> associated UIDs and last block where ownership was proven. #[pallet::storage] pub type AssociatedUidsByEvmAddress = StorageDoubleMap< _, Twox64Concat, NetUid, Twox64Concat, H160, BoundedVec<(u16, u64), ConstU32>, ValueQuery, >; // Subnet Leasing /// MAP ( lease_id ) --> subnet lease | The subnet lease for a given lease id. #[pallet::storage] pub type SubnetLeases = StorageMap<_, Twox64Concat, LeaseId, SubnetLeaseOf, OptionQuery>; /// Internal settlement marker: a formally terminated lease's residual payout hotkey. /// Kept only while a contributor debt or residual stake remains; the frozen lease layout is unchanged. #[pallet::storage] pub type SubnetLeaseTerminationHotkey = StorageMap<_, Twox64Concat, LeaseId, T::AccountId, OptionQuery>; /// DMAP ( lease_id, contributor ) --> shares | The shares of a contributor for a given lease. #[pallet::storage] pub type SubnetLeaseShares = StorageDoubleMap<_, Twox64Concat, LeaseId, Identity, T::AccountId, U64F64, ValueQuery>; /// MAP ( netuid ) --> lease_id | The lease id for a given netuid. #[pallet::storage] pub type SubnetUidToLeaseId = StorageMap<_, Twox64Concat, NetUid, LeaseId, OptionQuery>; /// ITEM ( next_lease_id ) | The next lease id. #[pallet::storage] pub type NextSubnetLeaseId = StorageValue<_, LeaseId, ValueQuery, ConstU32<0>>; /// MAP ( lease_id ) --> accumulated_dividends | The accumulated dividends for a given lease that needs to be distributed. #[pallet::storage] pub type AccumulatedLeaseDividends = StorageMap<_, Twox64Concat, LeaseId, AlphaBalance, ValueQuery, DefaultZeroAlpha>; /// DMAP ( lease_id, contributor ) --> alpha | A contributor's dividend slices that could not /// be transferred yet. The alpha stays in the lease position and is retried, for that /// contributor only, at the next distribution. #[pallet::storage] pub type SubnetLeaseUnpaidDividends = StorageDoubleMap< _, Twox64Concat, LeaseId, Identity, T::AccountId, AlphaBalance, ValueQuery, DefaultZeroAlpha, >; /// ITEM ( CommitRevealWeightsVersion ) #[pallet::storage] pub type CommitRevealWeightsVersion = StorageValue<_, u16, ValueQuery, DefaultCommitRevealWeightsVersion>; /// ITEM( NetworkRegistrationStartBlock ) #[pallet::storage] pub type NetworkRegistrationStartBlock = StorageValue<_, u64, ValueQuery, DefaultNetworkRegistrationStartBlock>; /// ITEM( TaoInRefundDeploymentBlock ) #[pallet::storage] pub type TaoInRefundDeploymentBlock = StorageValue<_, u64, ValueQuery, DefaultTaoInRefundDeploymentBlock>; /// MAP ( netuid ) --> minimum required number of non-immortal & non-immune UIDs #[pallet::storage] pub type MinNonImmuneUids = StorageMap<_, Identity, NetUid, u16, ValueQuery, DefaultMinNonImmuneUids>; // Subnet Mechanisms /// ITEM (Default number of sub-subnets) #[pallet::type_value] pub fn DefaultMechanismCount() -> MechId { MechId::from(1) } /// ITEM (Maximum number of mechanisms) #[pallet::type_value] pub fn DefaultMaxMechanismCount() -> MechId { MechId::from(2) } /// ITEM( max_mechanism_count ) #[pallet::storage] pub type MaxMechanismCount = StorageValue<_, MechId, ValueQuery, DefaultMaxMechanismCount>; /// ITEM (Rate limit for mechanism count updates) #[pallet::type_value] pub fn MechanismCountSetRateLimit() -> u64 { prod_or_fast!(7_200, 1) } /// ITEM (Rate limit for mechanism emission distribution updates) #[pallet::type_value] pub fn MechanismEmissionRateLimit() -> u64 { prod_or_fast!(7_200, 1) } /// ITEM (Rate limit for subnet emission weight vector updates: once per default /// 360-block tempo, keyed per subnet. Root is exempt; a subnet's first call is always /// allowed, and dissolution clears the key so a reused netuid starts fresh.) #[pallet::type_value] pub fn DefaultSubnetEmissionWeightsRateLimit() -> u64 { prod_or_fast!(360, 1) } /// Blocks an owner must wait between subnet emission weight vector updates. /// Set network-wide through `AdminUtils::sudo_set_subnet_emission_weights_rate_limit`. #[pallet::storage] pub type SubnetEmissionWeightsRateLimit = StorageValue<_, u64, ValueQuery, DefaultSubnetEmissionWeightsRateLimit>; /// MAP ( netuid ) --> Current number of subnet mechanisms #[pallet::storage] pub type MechanismCountCurrent = StorageMap<_, Twox64Concat, NetUid, MechId, ValueQuery, DefaultMechanismCount>; /// MAP ( netuid ) --> Normalized vector of emission split proportion between subnet mechanisms #[pallet::storage] pub type MechanismEmissionSplit = StorageMap<_, Twox64Concat, NetUid, Vec, OptionQuery>; /// MAP ( netuid ) --> BurnHalfLife (blocks) #[pallet::storage] pub type BurnHalfLife = StorageMap<_, Identity, NetUid, u16, ValueQuery, DefaultBurnHalfLife>; /// MAP ( netuid ) --> BurnIncreaseMult #[pallet::storage] pub type BurnIncreaseMult = StorageMap<_, Identity, NetUid, U64F64, ValueQuery, DefaultBurnIncreaseMult>; /// MAP ( netuid ) --> CollateralLockShare (p) /// /// Share of the registration price locked as miner collateral instead of /// burned, normalized so `u16::MAX` = 100%. 0 (the default) disables /// collateral: the whole registration price is burned as before. #[pallet::storage] pub type CollateralLockShare = StorageMap<_, Identity, NetUid, u16, ValueQuery, DefaultCollateralLockShare>; /// MAP ( netuid ) --> CollateralDrainRatio (k) /// /// Alpha of locked collateral released per alpha of hotkey emission /// earned (miner incentive and validator dividends). Snapshot into /// `MinerCollateral` at each registration. #[pallet::storage] pub type CollateralDrainRatio = StorageMap<_, Identity, NetUid, U64F64, ValueQuery, DefaultCollateralDrainRatio>; /// NMAP ( netuid, hotkey, coldkey ) --> MinerCollateralState /// /// Standing registration collateral of a `(hotkey, coldkey)` stake /// position on a subnet. Keyed by coldkey so nominators on the same /// hotkey are never charged for the owner's bond. The entry persists /// across deregistration and is only removed when fully drained through /// earned emission. #[pallet::storage] pub type MinerCollateral = StorageNMap< _, ( NMapKey, // subnet NMapKey, // hot NMapKey, // cold ), MinerCollateralState, OptionQuery, >; /// MAP ( netuid, coldkey ) --> total locked miner collateral /// /// O(1) aggregate of `MinerCollateral.locked` across that coldkey's hotkeys /// on the subnet. Kept in sync by collateral credit / settle paths so /// unstake availability checks do not scan `OwnedHotkeys`. #[pallet::storage] pub type ColdkeyMinerCollateral = StorageDoubleMap< _, Identity, NetUid, Blake2_128Concat, T::AccountId, AlphaBalance, ValueQuery, >; /// DMAP ( netuid, coldkey ) --> BoundedVec of hotkeys /// /// Hotkeys with a standing [`MinerCollateral`] row for this coldkey on the /// subnet. Kept in sync by collateral create / remove / swap paths so /// coldkey swaps migrate bonds with a bounded indexed walk (see /// [`MAX_COLDKEY_COLLATERAL_HOTKEYS`]) instead of scanning unbounded /// association vectors. #[pallet::storage] pub type ColdkeyCollateralHotkeys = StorageDoubleMap< _, Identity, NetUid, Blake2_128Concat, T::AccountId, BoundedVec>, ValueQuery, >; /// The account authorized to submit weights for a validator on one mechanism. /// The tuple key is the mechanism storage index and the validator hotkey. #[pallet::storage] pub type MechWeightDelegate = StorageNMap< _, ( NMapKey, NMapKey, ), T::AccountId, OptionQuery, >; /// Mechanisms granted by one validator. Per-grant rows avoid rewriting a set. #[pallet::storage] pub type MechWeightDelegateTargets = StorageNMap< _, ( NMapKey, NMapKey, NMapKey, ), (), OptionQuery, >; /// Invalidated validator hotkeys awaiting bounded removal of their grants. #[pallet::storage] pub type MechWeightDelegatePurgeQueue = StorageDoubleMap< _, Identity, NetUid, Blake2_128Concat, T::AccountId, Option, OptionQuery, >; /// A grant being moved with its original UID to a new validator hotkey. #[derive(Clone, PartialEq, Eq, Encode, Decode, TypeInfo, MaxEncodedLen, Debug)] #[scale_info(skip_type_params(T))] pub struct PendingMechWeightDelegateMove { /// UID originally moved from the source hotkey. pub uid: u16, /// Hotkey that must still own this UID when the move drains. pub destination: T::AccountId, /// Authorized delegate to install, or no delegate for a revoked grant. pub delegate: Option, } #[pallet::storage] pub type MechWeightDelegateMoveQueue = StorageNMap< _, ( NMapKey, NMapKey, NMapKey, ), PendingMechWeightDelegateMove, OptionQuery, >; /// Incoming rename edges for a validator hotkey. These must be removed on deregistration. #[pallet::storage] pub type MechWeightDelegateMoveOrigins = StorageNMap< _, ( NMapKey, NMapKey, NMapKey, NMapKey, ), (), OptionQuery, >; /// Pending moves indexed by mechanism and origin hotkey. #[pallet::storage] pub type MechWeightDelegateMechanismMoves = StorageNMap< _, ( NMapKey, NMapKey, NMapKey, ), (), OptionQuery, >; /// Retired mechanisms whose grants must be removed before another count change. #[pallet::storage] pub type MechWeightDelegateRetirementQueue = StorageDoubleMap<_, Identity, NetUid, Identity, MechId, (), OptionQuery>; /// ITEM ( enabled ) | Whether gamma can be minted at all; a subnet also needs /// [`SubnetGammaEnabled`]. #[pallet::storage] pub type GammaEnabled = StorageValue<_, bool, ValueQuery>; /// MAP ( netuid ) --> enabled | Whether gamma can be minted on the subnet. #[pallet::storage] pub type SubnetGammaEnabled = StorageMap<_, Identity, NetUid, bool, ValueQuery>; /// DMAP ( netuid, hotkey ) --> deposit | The gamma held at a hotkey on the subnet. #[pallet::storage] pub type GammaDeposits = StorageDoubleMap< _, Identity, NetUid, Blake2_128Concat, T::AccountId, GammaDeposit, OptionQuery, >; /// DMAP ( netuid, coldkey ) --> hotkeys | The hotkeys holding the coldkey's gamma /// deposits on the subnet. #[pallet::storage] pub type ColdkeyGammaHotkeys = StorageDoubleMap< _, Identity, NetUid, Blake2_128Concat, T::AccountId, BoundedVec>, ValueQuery, >; /// NMAP ( netuid, service, hotkey ) --> gamma | The gamma the hotkey has spent at the /// service on the subnet. #[pallet::storage] pub type GammaSpent = StorageNMap< _, ( NMapKey, NMapKey, NMapKey, ), GammaBalance, ValueQuery, >; /// DMAP ( netuid, coldkey ) --> gamma | The coldkey's gamma on the subnet held at no hotkey. #[pallet::storage] pub type GammaBalances = StorageDoubleMap< _, Identity, NetUid, Blake2_128Concat, T::AccountId, GammaBalance, ValueQuery, >; /// MAP ( netuid ) --> gamma_price | The highest price a subnet's alpha mints gamma at: set to the /// median subnet alpha price at registration, each block it falls to the spot price at once /// and rises toward it by [`SubnetFastMovingPrice`]'s weight of the gap, at most of itself. #[pallet::storage] pub type SubnetGammaPrice = StorageMap<_, Identity, NetUid, U64F64, ValueQuery>; /// MAP ( netuid ) --> gamma shares | The subnet's shares of its alpha emission to other /// subnets' gamma, in `u64::MAX` parts, in ascending target order. #[pallet::storage] pub type SubnetGammaEmission = StorageMap<_, Identity, NetUid, GammaEmission, ValueQuery>; /// MAP ( netuid ) --> alpha | The subnet's emission accrued to its gamma shares since they /// were last allotted it. #[pallet::storage] pub type PendingGammaEmission = StorageMap<_, Identity, NetUid, AlphaBalance, ValueQuery, DefaultZeroAlpha>; /// DMAP ( netuid, target ) --> alpha | Alpha allotted to the subnet's gamma share of the /// target and not yet converted. #[pallet::storage] pub type UnconvertedGammaEmission = StorageDoubleMap< _, Identity, NetUid, Identity, NetUid, AlphaBalance, ValueQuery, DefaultZeroAlpha, >; /// MAP ( netuid ) --> whitelisted | Whether subnets may give the subnet gamma shares. #[pallet::storage] pub type SubnetGammaEmissionWhitelisted = StorageMap<_, Identity, NetUid, bool, ValueQuery>; /// ITEM ( oracle ) | The account that feeds the TAO/USD price. #[pallet::storage] pub type TaoUsdPriceOracle = StorageValue<_, T::AccountId, OptionQuery>; /// ITEM ( state ) | The TAO/USD price, once fed. #[pallet::storage] pub type TaoUsdPrice = StorageValue<_, TaoUsdPriceState, OptionQuery>; /// MAP ( hotkey ) --> parent_delegation_enabled /// /// When `true`, this root validator allows auto parent delegation: /// new subnets childkey existing root validators to the new owner, /// and a new root validator childkeys to all current subnet owners. /// Defaults to `true`; validators can opt out at any time /// by calling `set_auto_parent_delegation_enabled(false)`. #[pallet::storage] pub type AutoParentDelegationEnabled = StorageMap< _, Blake2_128Concat, T::AccountId, bool, ValueQuery, DefaultAutoParentDelegationEnabled, // default = true >; // Genesis /// Storage for migration run status #[pallet::storage] pub type HasMigrationRun = StorageMap<_, Identity, Vec, bool, ValueQuery>; /// Default value for pending childkey cooldown (settable by root). /// Uses the same value as DefaultPendingCooldown for consistency. #[pallet::type_value] pub fn DefaultPendingChildKeyCooldown() -> u64 { DefaultPendingCooldown::::get() } /// Storage value for pending childkey cooldown, settable by root. #[pallet::storage] pub type PendingChildKeyCooldown = StorageValue<_, u64, ValueQuery, DefaultPendingChildKeyCooldown>; /// V2 announcement-time decision for ignoring unsolicited destination balance /// when deciding whether to import the source auto-stake policy. The privilege /// is honored only while the matching destination reservation remains live. /// Legacy hash-only announcements have no entry. #[pallet::storage] pub type ColdkeySwapV2PolicySnapshots = StorageMap<_, Twox64Concat, T::AccountId, bool, OptionQuery>; /// MAP ( hotkey ) --> block_number | Last block at which `hotkey` was disassociated /// from its coldkey. Used at pending-child activation to invalidate any incoming /// `PendingChildKeys` entry scheduled before the release. #[pallet::storage] pub type HotkeyDisassociatedAt = StorageMap<_, Blake2_128Concat, T::AccountId, u64, OptionQuery>; #[pallet::genesis_config] pub struct GenesisConfig { /// Stakes record in genesis. pub stakes: Vec<(T::AccountId, Vec<(T::AccountId, (u64, u16))>)>, /// The total issued balance in genesis pub balances_issuance: TaoBalance, /// The delay before a subnet can call start pub start_call_delay: Option, } impl Default for GenesisConfig { fn default() -> Self { Self { stakes: Default::default(), balances_issuance: TaoBalance::ZERO, start_call_delay: None, } } } // ---- Subtensor helper functions. impl Pallet { /// Is the caller allowed to set weights pub fn check_weights_min_stake(hotkey: &T::AccountId, netuid: NetUid) -> bool { // Allow the subnet owner hotkey to set weights regardless of stake. if let Some(owner_uid) = Self::get_owner_uid(netuid) && Uids::::get(netuid, hotkey) == Some(owner_uid) { return true; } // Blacklist weights transactions for low stake peers. let (total_stake, _, _) = Self::get_stake_weights_for_hotkey_on_subnet(hotkey, netuid); total_stake >= Self::get_stake_threshold() } /// Helper function to check if register is allowed pub fn checked_allowed_register(netuid: NetUid) -> bool { if netuid.is_root() { return false; } if !Self::if_subnet_exist(netuid) { return false; } if !Self::get_network_registration_allowed(netuid) { return false; } if Self::get_registrations_this_block(netuid) >= Self::get_max_registrations_per_block(netuid) { return false; } if Self::get_registrations_this_interval(netuid) >= Self::get_target_registrations_per_interval(netuid).saturating_mul(3) { return false; } true } /// Ensure subtoken enalbed pub fn ensure_subtoken_enabled(subnet: NetUid) -> Result<(), Error> { ensure!( SubtokenEnabled::::get(subnet), Error::::SubtokenDisabled ); Ok(()) } } } use sp_std::vec; // TODO: unravel this rats nest, for some reason rustc thinks this is unused even though it's // used not 25 lines below #[allow(unused)] use sp_std::vec::Vec; use subtensor_macros::freeze_struct; #[derive(Clone)] pub struct TaoBalanceReserve(PhantomData); impl TokenReserve for TaoBalanceReserve { #![deny(clippy::expect_used)] fn reserve(netuid: NetUid) -> TaoBalance { SubnetTAO::::get(netuid) } fn increase_provided(netuid: NetUid, tao: TaoBalance) { Pallet::::increase_provided_tao_reserve(netuid, tao); } fn decrease_provided(netuid: NetUid, tao: TaoBalance) { Pallet::::decrease_provided_tao_reserve(netuid, tao); } } #[derive(Clone)] pub struct AlphaBalanceReserve(PhantomData); impl TokenReserve for AlphaBalanceReserve { #![deny(clippy::expect_used)] fn reserve(netuid: NetUid) -> AlphaBalance { SubnetAlphaIn::::get(netuid) } fn increase_provided(netuid: NetUid, alpha: AlphaBalance) { Pallet::::increase_provided_alpha_reserve(netuid, alpha); } fn decrease_provided(netuid: NetUid, alpha: AlphaBalance) { Pallet::::decrease_provided_alpha_reserve(netuid, alpha); } } pub type GetAlphaForTao = subtensor_swap_interface::GetAlphaForTao, AlphaBalanceReserve>; pub type GetTaoForAlpha = subtensor_swap_interface::GetTaoForAlpha, TaoBalanceReserve>; impl> subtensor_runtime_common::SubnetInfo for Pallet { #![deny(clippy::expect_used)] fn exists(netuid: NetUid) -> bool { Self::if_subnet_exist(netuid) } fn mechanism(netuid: NetUid) -> u16 { SubnetMechanism::::get(netuid) } fn is_owner(account_id: &T::AccountId, netuid: NetUid) -> bool { SubnetOwner::::get(netuid) == *account_id } fn is_subtoken_enabled(netuid: NetUid) -> bool { SubtokenEnabled::::get(netuid) } fn get_validator_trust(netuid: NetUid) -> Vec { ValidatorTrust::::get(netuid) .into_iter() .map(PerU16::deconstruct) .collect() } fn get_validator_permit(netuid: NetUid) -> Vec { ValidatorPermit::::get(netuid) } fn hotkey_of_uid(netuid: NetUid, uid: u16) -> Option { Keys::::try_get(netuid, uid).ok() } } impl> subtensor_runtime_common::BalanceOps for Pallet { #![deny(clippy::expect_used)] fn tao_balance(account_id: &T::AccountId) -> TaoBalance { pallet_balances::Pallet::::free_balance(account_id).into() } fn alpha_balance( netuid: NetUid, coldkey: &T::AccountId, hotkey: &T::AccountId, ) -> AlphaBalance { Self::get_stake_for_hotkey_and_coldkey_on_subnet(hotkey, coldkey, netuid) } fn increase_stake( coldkey: &T::AccountId, hotkey: &T::AccountId, netuid: NetUid, alpha: AlphaBalance, ) -> Result<(), DispatchError> { ensure!( Self::hotkey_account_exists(hotkey), Error::::HotKeyAccountNotExists ); // Increse alpha out counter Self::ensure_staking_hotkeys_can_grow(coldkey, hotkey)?; SubnetAlphaOut::::mutate(netuid, |total| { *total = total.saturating_add(alpha); }); Self::increase_stake_for_hotkey_and_coldkey_on_subnet(hotkey, coldkey, netuid, alpha); Ok(()) } fn decrease_stake( coldkey: &T::AccountId, hotkey: &T::AccountId, netuid: NetUid, alpha: AlphaBalance, ) -> Result<(), DispatchError> { ensure!( Self::hotkey_account_exists(hotkey), Error::::HotKeyAccountNotExists ); ensure!( Self::get_stake_for_hotkey_and_coldkey_on_subnet(hotkey, coldkey, netuid) >= alpha, Error::::InsufficientAlphaBalance ); // Decrese alpha out counter SubnetAlphaOut::::mutate(netuid, |total| { *total = total.saturating_sub(alpha); }); Self::decrease_stake_for_hotkey_and_coldkey_on_subnet(hotkey, coldkey, netuid, alpha); Ok(()) } } /// Enum that defines types of rate limited operations for /// storing last block when this operation occured #[derive(Encode, Decode, Clone, PartialEq, Eq, Debug, TypeInfo)] pub enum RateLimitKey { // The setting sn owner hotkey operation is rate limited per netuid #[codec(index = 0)] SetSNOwnerHotkey(NetUid), // Generic rate limit for subnet-owner hyperparameter updates (per netuid) #[codec(index = 1)] OwnerHyperparamUpdate(NetUid, Hyperparameter), // Subnet registration rate limit #[codec(index = 2)] NetworkLastRegistered, // Last tx block limit per account ID #[codec(index = 3)] LastTxBlock(AccountId), // Last tx block child key limit per account ID #[codec(index = 4)] LastTxBlockChildKeyTake(AccountId), // Last tx block delegate key limit per account ID #[codec(index = 5)] LastTxBlockDelegateTake(AccountId), // "Add stake and burn" rate limit #[codec(index = 6)] AddStakeBurn(NetUid), } pub trait ProxyInterface { fn add_lease_beneficiary_proxy(beneficiary: &AccountId, lease: &AccountId) -> DispatchResult; fn remove_lease_beneficiary_proxy(beneficiary: &AccountId, lease: &AccountId) -> DispatchResult; /// Whether `delegator` already holds any proxy grants (including reserved deposit). fn has_delegator_proxies(delegator: &AccountId) -> bool; /// Whether the exact zero-delay lease-beneficiary grant is still installed. fn has_lease_beneficiary_proxy(lease: &AccountId, beneficiary: &AccountId) -> bool; } impl ProxyInterface for () { fn add_lease_beneficiary_proxy(_: &T, _: &T) -> DispatchResult { Ok(()) } fn remove_lease_beneficiary_proxy(_: &T, _: &T) -> DispatchResult { Ok(()) } fn has_lease_beneficiary_proxy(_: &T, _: &T) -> bool { // No-op backends accept grants without storing them; the explicit marker tracks termination. true } fn has_delegator_proxies(_: &T) -> bool { false } } /// Interface for purging commitment state when subnets or neurons are removed. pub trait CommitmentsInterface { fn purge_netuid(netuid: NetUid, weight_meter: &mut WeightMeter) -> bool; fn purge_neuron(netuid: NetUid, account: &AccountId); fn swap_neuron(netuid: NetUid, old_hotkey: &AccountId, new_hotkey: &AccountId); } /// Default minimum TAO value through the middle of a `swap_basket` trade. The call costs /// about 0.006 TAO at current fee calibration, so admitting every few blocks' worth of a /// refilling turnover bucket can spend more on transaction fees than it rebalances. Half a TAO /// keeps the trade well above its fee while still allowing modest funds to rebalance incrementally. pub const MIN_BASKET_TRADE_TAO: u64 = 500_000_000;