#![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};
use sp_std::marker::PhantomData;
use subtensor_runtime_common::{AlphaBalance, NetUid, TaoBalance, Token, TokenReserve};
// ============================
// ==== Benchmark Imports =====
// ============================
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::*;
#[cfg(test)]
pub(crate) mod tests;
// apparently this is stabilized since rust 1.36
extern crate alloc;
pub type OriginFor = ::RuntimeOrigin;
pub const MAX_CRV3_COMMIT_SIZE_BYTES: u32 = 5000;
pub const ALPHA_MAP_BATCH_SIZE: usize = 30;
pub const MAX_NUM_ROOT_CLAIMS: u64 = 50;
pub const MAX_SUBNET_CLAIMS: usize = 5;
pub const MAX_ROOT_CLAIM_THRESHOLD: u64 = 10_000_000;
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;
/// Account flag bit that opts into receiving locked alpha transfers.
pub const ACCOUNT_FLAGS_ACCEPT_LOCKED_ALPHA: u128 = 1u128 << 0;
#[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::leasing::{LeaseId, SubnetLeaseOf};
use crate::subnets::subnet::NetworkRegistrationInfo;
use crate::weights::WeightInfo;
use crate::{MAX_ASSOCIATED_UIDS_PER_EVM_ADDRESS, 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,
};
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, 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,
}
/// 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,
}
/// 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,
}
// Staking + Accounts
#[derive(
Encode, Decode, Default, TypeInfo, Clone, PartialEq, Eq, Debug, DecodeWithMemTracking,
)]
/// Enum for the per-coldkey root claim setting.
pub enum RootClaimTypeEnum {
/// Swap any alpha emission for TAO.
#[default]
Swap,
/// Keep all alpha emission.
Keep,
/// Keep all alpha emission for specified subnets.
KeepSubnets {
/// Subnets to keep alpha emissions (swap everything else).
subnets: BTreeSet,
},
}
/// 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 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 root claim type.
/// This is the type of root claim that will be made.
/// This is set by the user. Either swap to TAO or keep as alpha.
#[pallet::type_value]
pub fn DefaultRootClaimType() -> RootClaimTypeEnum {
RootClaimTypeEnum::default()
}
/// Default number of root claims per claim call.
/// Ideally this is calculated using the number of staking coldkey
/// and the block time.
#[pallet::type_value]
pub fn DefaultNumRootClaim() -> u64 {
// once per week (+ spare keys for skipped tries)
5
}
/// 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 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 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 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 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,
>;
/// 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>;
/// 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,
>;
/// 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,
>;
// 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 ) --> 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