From de759d20baf0b93e067d362e06fb136564a94d04 Mon Sep 17 00:00:00 2001 From: Aliaksandr Tsurko Date: Thu, 12 Jun 2025 18:24:51 +0200 Subject: [PATCH 1/7] Add Alpha currency type --- common/src/currency.rs | 65 ++++++++++++++++++++++++++++++++++++++++++ common/src/lib.rs | 2 ++ 2 files changed, 67 insertions(+) create mode 100644 common/src/currency.rs diff --git a/common/src/currency.rs b/common/src/currency.rs new file mode 100644 index 0000000000..9eced55838 --- /dev/null +++ b/common/src/currency.rs @@ -0,0 +1,65 @@ +use core::fmt::{self, Display, Formatter}; + +use codec::{Compact, CompactAs, Decode, Encode, Error as CodecError, MaxEncodedLen}; +use frame_support::pallet_prelude::*; +use scale_info::TypeInfo; +use serde::{Deserialize, Serialize}; +use subtensor_macros::freeze_struct; + +#[freeze_struct("e12e377d201c5e2c")] +#[repr(transparent)] +#[derive( + Deserialize, + Serialize, + Clone, + Copy, + Decode, + Default, + Encode, + Eq, + Hash, + MaxEncodedLen, + Ord, + PartialEq, + PartialOrd, + RuntimeDebug, + TypeInfo, +)] +pub struct Alpha(u64); + +impl Display for Alpha { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + Display::fmt(&self.0, f) + } +} + +impl CompactAs for Alpha { + type As = u64; + + fn encode_as(&self) -> &Self::As { + &self.0 + } + + fn decode_from(v: Self::As) -> Result { + Ok(Self(v)) + } +} + +impl From> for Alpha { + fn from(c: Compact) -> Self { + c.0 + } +} + +impl From for u64 { + fn from(val: Alpha) -> Self { + val.0 + } +} + +impl From for Alpha { + fn from(value: u64) -> Self { + Self(value) + } +} + diff --git a/common/src/lib.rs b/common/src/lib.rs index 1e040ffad5..92759608af 100644 --- a/common/src/lib.rs +++ b/common/src/lib.rs @@ -11,6 +11,8 @@ use sp_runtime::{ }; use subtensor_macros::freeze_struct; +mod currency; + /// Balance of an account. pub type Balance = u64; From 4e75683fb52e5d6cf435d218fbab6c1fa041004c Mon Sep 17 00:00:00 2001 From: Aliaksandr Tsurko Date: Tue, 17 Jun 2025 20:58:28 +0300 Subject: [PATCH 2/7] Replace u64 with Alpha --- common/src/currency.rs | 10 ++++++++-- common/src/lib.rs | 2 ++ pallets/subtensor/src/lib.rs | 16 ++++++++-------- 3 files changed, 18 insertions(+), 10 deletions(-) diff --git a/common/src/currency.rs b/common/src/currency.rs index 9eced55838..e7e6c03f38 100644 --- a/common/src/currency.rs +++ b/common/src/currency.rs @@ -6,7 +6,7 @@ use scale_info::TypeInfo; use serde::{Deserialize, Serialize}; use subtensor_macros::freeze_struct; -#[freeze_struct("e12e377d201c5e2c")] +#[freeze_struct("597e376f01cf675a")] #[repr(transparent)] #[derive( Deserialize, @@ -23,10 +23,16 @@ use subtensor_macros::freeze_struct; PartialEq, PartialOrd, RuntimeDebug, - TypeInfo, )] pub struct Alpha(u64); +impl TypeInfo for Alpha { + type Identity = ::Identity; + fn type_info() -> scale_info::Type { + ::type_info() + } +} + impl Display for Alpha { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { Display::fmt(&self.0, f) diff --git a/common/src/lib.rs b/common/src/lib.rs index 4c20b121d4..ab1253459e 100644 --- a/common/src/lib.rs +++ b/common/src/lib.rs @@ -11,6 +11,8 @@ use sp_runtime::{ }; use subtensor_macros::freeze_struct; +pub use currency::*; + mod currency; /// Balance of an account. diff --git a/pallets/subtensor/src/lib.rs b/pallets/subtensor/src/lib.rs index ea252ccb37..f4fd86b627 100644 --- a/pallets/subtensor/src/lib.rs +++ b/pallets/subtensor/src/lib.rs @@ -28,7 +28,7 @@ use sp_runtime::{ transaction_validity::{TransactionValidity, TransactionValidityError}, }; use sp_std::marker::PhantomData; -use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::{NetUid, Alpha as AlphaCurrency}; // ============================ // ==== Benchmark Imports ===== @@ -988,7 +988,7 @@ pub mod pallet { NetUid, Blake2_128Concat, T::AccountId, - u64, + AlphaCurrency, ValueQuery, DefaultZeroU64, >; @@ -1018,7 +1018,7 @@ pub mod pallet { T::AccountId, Identity, NetUid, - u64, + AlphaCurrency, ValueQuery, DefaultZeroU64, >; @@ -1055,16 +1055,16 @@ pub mod pallet { StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultZeroU64>; #[pallet::storage] // --- MAP ( netuid ) --> alpha_out_emission | Returns the amount of alpha out emission into the network per block. pub type SubnetAlphaOutEmission = - StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultZeroU64>; + StorageMap<_, Identity, NetUid, AlphaCurrency, ValueQuery, DefaultZeroU64>; #[pallet::storage] // --- MAP ( netuid ) --> tao_in_emission | Returns the amount of tao emitted into this subent on the last block. pub type SubnetTaoInEmission = StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultZeroU64>; #[pallet::storage] // --- MAP ( netuid ) --> alpha_supply_in_pool | Returns the amount of alpha in the pool. pub type SubnetAlphaIn = - StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultZeroU64>; + StorageMap<_, Identity, NetUid, AlphaCurrency, ValueQuery, DefaultZeroU64>; #[pallet::storage] // --- MAP ( netuid ) --> alpha_supply_in_subnet | Returns the amount of alpha in the subnet. pub type SubnetAlphaOut = - StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultZeroU64>; + StorageMap<_, Identity, NetUid, AlphaCurrency, ValueQuery, DefaultZeroU64>; #[pallet::storage] // --- MAP ( cold ) --> Vec | Maps coldkey to hotkeys that stake to it pub type StakingHotkeys = StorageMap<_, Blake2_128Concat, T::AccountId, Vec, ValueQuery>; @@ -1089,7 +1089,7 @@ pub mod pallet { T::AccountId, Identity, NetUid, - u64, + AlphaCurrency, ValueQuery, DefaultZeroU64, >; @@ -1100,7 +1100,7 @@ pub mod pallet { T::AccountId, Identity, NetUid, - u64, + AlphaCurrency, ValueQuery, DefaultZeroU64, >; From d92b3b1de1668658a78a4caf9d34234c7228983f Mon Sep 17 00:00:00 2001 From: Aliaksandr Tsurko Date: Tue, 24 Jun 2025 20:00:31 +0300 Subject: [PATCH 3/7] Make code compilable with alpha wrapper --- Cargo.lock | 2 + common/Cargo.toml | 5 + common/src/currency.rs | 150 +++++ common/src/lib.rs | 14 +- pallets/admin-utils/src/lib.rs | 3 +- pallets/admin-utils/src/tests/mod.rs | 30 +- pallets/subtensor/Cargo.toml | 2 +- pallets/subtensor/runtime-api/src/lib.rs | 4 +- pallets/subtensor/src/benchmarks.rs | 49 +- pallets/subtensor/src/coinbase/root.rs | 4 +- .../subtensor/src/coinbase/run_coinbase.rs | 131 ++-- pallets/subtensor/src/epoch/run_epoch.rs | 42 +- pallets/subtensor/src/lib.rs | 73 +- pallets/subtensor/src/macros/dispatches.rs | 17 +- pallets/subtensor/src/macros/events.rs | 6 +- pallets/subtensor/src/macros/genesis.rs | 12 +- .../src/migrations/migrate_delete_subnet_3.rs | 1 + .../subtensor/src/migrations/migrate_rao.rs | 7 +- .../migrate_remove_zero_total_hotkey_alpha.rs | 2 +- .../src/migrations/migrate_set_min_burn.rs | 1 + .../migrations/migrate_set_min_difficulty.rs | 1 + .../migrate_to_v1_separate_emission.rs | 1 + ...igrate_transfer_ownership_to_foundation.rs | 1 + .../subtensor/src/rpc_info/delegate_info.rs | 22 +- .../subtensor/src/rpc_info/dynamic_info.rs | 14 +- pallets/subtensor/src/rpc_info/metagraph.rs | 50 +- pallets/subtensor/src/rpc_info/neuron_info.rs | 18 +- pallets/subtensor/src/rpc_info/show_subnet.rs | 20 +- pallets/subtensor/src/rpc_info/stake_info.rs | 18 +- pallets/subtensor/src/staking/helpers.rs | 27 +- pallets/subtensor/src/staking/move_stake.rs | 27 +- .../subtensor/src/staking/recycle_alpha.rs | 6 +- pallets/subtensor/src/staking/remove_stake.rs | 25 +- pallets/subtensor/src/staking/stake_utils.rs | 125 ++-- pallets/subtensor/src/subnets/registration.rs | 8 +- pallets/subtensor/src/subnets/subnet.rs | 3 +- pallets/subtensor/src/subnets/uids.rs | 8 +- pallets/subtensor/src/swap/swap_hotkey.rs | 2 + pallets/subtensor/src/tests/children.rs | 321 +++++---- pallets/subtensor/src/tests/coinbase.rs | 624 ++++++++++++------ pallets/subtensor/src/tests/consensus.rs | 8 +- pallets/subtensor/src/tests/delegate_info.rs | 4 +- pallets/subtensor/src/tests/epoch.rs | 213 +++--- pallets/subtensor/src/tests/migration.rs | 10 +- pallets/subtensor/src/tests/mock.rs | 14 +- pallets/subtensor/src/tests/move_stake.rs | 156 +++-- pallets/subtensor/src/tests/networks.rs | 6 +- pallets/subtensor/src/tests/recycle_alpha.rs | 55 +- pallets/subtensor/src/tests/registration.rs | 20 +- pallets/subtensor/src/tests/senate.rs | 72 +- pallets/subtensor/src/tests/staking.rs | 506 +++++++------- pallets/subtensor/src/tests/staking2.rs | 158 +++-- pallets/subtensor/src/tests/subnet.rs | 39 +- pallets/subtensor/src/tests/swap_coldkey.rs | 86 +-- pallets/subtensor/src/tests/swap_hotkey.rs | 50 +- .../src/tests/swap_hotkey_with_subnet.rs | 40 +- pallets/subtensor/src/tests/uids.rs | 8 +- pallets/subtensor/src/tests/weights.rs | 82 +-- pallets/subtensor/src/utils/misc.rs | 14 +- pallets/swap-interface/src/lib.rs | 6 +- pallets/swap/src/mock.rs | 23 +- pallets/swap/src/pallet/impls.rs | 33 +- pallets/swap/src/pallet/mod.rs | 11 +- pallets/swap/src/pallet/tests.rs | 34 +- precompiles/src/alpha.rs | 12 +- precompiles/src/metagraph.rs | 5 +- precompiles/src/staking.rs | 24 +- runtime/src/lib.rs | 6 +- 68 files changed, 2115 insertions(+), 1456 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5c7b02714e..1b0bc88011 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -13173,12 +13173,14 @@ dependencies = [ name = "subtensor-runtime-common" version = "0.1.0" dependencies = [ + "approx", "frame-support", "parity-scale-codec", "scale-info", "serde", "sp-core", "sp-runtime", + "substrate-fixed", "subtensor-macros", ] diff --git a/common/Cargo.toml b/common/Cargo.toml index b46a4de4a9..c0de294180 100644 --- a/common/Cargo.toml +++ b/common/Cargo.toml @@ -17,13 +17,17 @@ scale-info = { workspace = true } serde = { workspace = true } sp-core = { workspace = true } sp-runtime = { workspace = true } +substrate-fixed = { workspace = true } subtensor-macros = { workspace = true } +approx = {workspace = true, optional = true} + [lints] workspace = true [features] default = ["std"] +approx = ["dep:approx"] fast-blocks = [] std = [ "codec/std", @@ -32,4 +36,5 @@ std = [ "serde/std", "sp-core/std", "sp-runtime/std", + "substrate-fixed/std", ] diff --git a/common/src/currency.rs b/common/src/currency.rs index e7e6c03f38..9f7f1e5be6 100644 --- a/common/src/currency.rs +++ b/common/src/currency.rs @@ -1,9 +1,13 @@ use core::fmt::{self, Display, Formatter}; +use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign}; +#[cfg(feature = "approx")] +use approx::AbsDiffEq; use codec::{Compact, CompactAs, Decode, Encode, Error as CodecError, MaxEncodedLen}; use frame_support::pallet_prelude::*; use scale_info::TypeInfo; use serde::{Deserialize, Serialize}; +use substrate_fixed::traits::{Fixed, ToFixed}; use subtensor_macros::freeze_struct; #[freeze_struct("597e376f01cf675a")] @@ -69,3 +73,149 @@ impl From for Alpha { } } +impl ToFixed for Alpha { + fn to_fixed(self) -> F { + self.0.to_fixed() + } + + fn checked_to_fixed(self) -> Option { + self.0.checked_to_fixed() + } + + fn saturating_to_fixed(self) -> F { + self.0.saturating_to_fixed() + } + fn wrapping_to_fixed(self) -> F { + self.0.wrapping_to_fixed() + } + + fn overflowing_to_fixed(self) -> (F, bool) { + self.0.overflowing_to_fixed() + } +} + +impl Currency for Alpha { + const MAX: Self = Self(u64::MAX); + const ZERO: Self = Self(0); +} + +pub trait Currency: ToFixed + Into + From + Clone + Copy { + const MAX: Self; + const ZERO: Self; + + fn is_zero(&self) -> bool { + Into::::into(*self) == 0 + } + + fn to_u64(&self) -> u64 { + (*self).into() + } + + fn saturating_add(&self, rhv: Self) -> Self { + Into::::into(*self).saturating_add(rhv.into()).into() + } + + fn saturating_div(&self, rhv: Self) -> Self { + Into::::into(*self).saturating_div(rhv.into()).into() + } + + fn saturating_sub(&self, rhv: Self) -> Self { + Into::::into(*self).saturating_sub(rhv.into()).into() + } + + fn saturating_mul(&self, rhv: Self) -> Self { + Into::::into(*self).saturating_mul(rhv.into()).into() + } +} + +macro_rules! impl_arithmetic_operators { + ($currency_type:ident) => { + impl Add for $currency_type { + type Output = Self; + + fn add(self, rhs: Self) -> Self::Output { + let lhs_u64: u64 = self.into(); + let rhs_u64: u64 = rhs.into(); + (lhs_u64 + rhs_u64).into() + } + } + + impl Sub for $currency_type { + type Output = Self; + + fn sub(self, rhs: Self) -> Self::Output { + let lhs_u64: u64 = self.into(); + let rhs_u64: u64 = rhs.into(); + (lhs_u64 - rhs_u64).into() + } + } + + impl Mul for $currency_type { + type Output = Self; + + fn mul(self, rhs: Self) -> Self::Output { + let lhs_u64: u64 = self.into(); + let rhs_u64: u64 = rhs.into(); + (lhs_u64 * rhs_u64).into() + } + } + + impl Div for $currency_type { + type Output = Self; + + fn div(self, rhs: Self) -> Self::Output { + let lhs_u64: u64 = self.into(); + let rhs_u64: u64 = rhs.into(); + (lhs_u64 / rhs_u64).into() + } + } + + impl AddAssign for $currency_type { + fn add_assign(&mut self, rhs: Self) { + *self = *self + rhs; + } + } + + impl SubAssign for $currency_type { + fn sub_assign(&mut self, rhs: Self) { + *self = *self - rhs; + } + } + + impl MulAssign for $currency_type { + fn mul_assign(&mut self, rhs: Self) { + *self = *self * rhs; + } + } + + impl DivAssign for $currency_type { + fn div_assign(&mut self, rhs: Self) { + *self = *self / rhs; + } + } + }; +} + +impl_arithmetic_operators!(Alpha); + +macro_rules! impl_approx { + ($currency_type:ident) => { + #[cfg(feature = "approx")] + impl AbsDiffEq for $currency_type { + type Epsilon = Self; + + fn default_epsilon() -> Self::Epsilon { + u64::default_epsilon().into() + } + fn abs_diff_eq(&self, other: &Self, epsilon: Self::Epsilon) -> bool { + u64::abs_diff_eq(&u64::from(*self), &u64::from(*other), epsilon.into()) + } + + fn abs_diff_ne(&self, other: &Self, epsilon: Self::Epsilon) -> bool { + u64::abs_diff_ne(&u64::from(*self), &u64::from(*other), epsilon.into()) + } + } + }; +} + +impl_approx!(Alpha); diff --git a/common/src/lib.rs b/common/src/lib.rs index 9cde59cd42..8eccff4731 100644 --- a/common/src/lib.rs +++ b/common/src/lib.rs @@ -154,7 +154,7 @@ impl Default for ProxyType { pub trait SubnetInfo { fn tao_reserve(netuid: NetUid) -> u64; - fn alpha_reserve(netuid: NetUid) -> u64; + fn alpha_reserve(netuid: NetUid) -> Alpha; fn exists(netuid: NetUid) -> bool; fn mechanism(netuid: NetUid) -> u16; fn is_owner(account_id: &AccountId, netuid: NetUid) -> bool; @@ -162,25 +162,25 @@ pub trait SubnetInfo { pub trait BalanceOps { fn tao_balance(account_id: &AccountId) -> u64; - fn alpha_balance(netuid: NetUid, coldkey: &AccountId, hotkey: &AccountId) -> u64; + fn alpha_balance(netuid: NetUid, coldkey: &AccountId, hotkey: &AccountId) -> Alpha; fn increase_balance(coldkey: &AccountId, tao: u64); fn decrease_balance(coldkey: &AccountId, tao: u64) -> Result; fn increase_stake( coldkey: &AccountId, hotkey: &AccountId, netuid: NetUid, - alpha: u64, + alpha: Alpha, ) -> Result<(), DispatchError>; fn decrease_stake( coldkey: &AccountId, hotkey: &AccountId, netuid: NetUid, - alpha: u64, - ) -> Result; + alpha: Alpha, + ) -> Result; fn increase_provided_tao_reserve(netuid: NetUid, tao: u64); fn decrease_provided_tao_reserve(netuid: NetUid, tao: u64); - fn increase_provided_alpha_reserve(netuid: NetUid, alpha: u64); - fn decrease_provided_alpha_reserve(netuid: NetUid, alpha: u64); + fn increase_provided_alpha_reserve(netuid: NetUid, alpha: Alpha); + fn decrease_provided_alpha_reserve(netuid: NetUid, alpha: Alpha); } pub mod time { diff --git a/pallets/admin-utils/src/lib.rs b/pallets/admin-utils/src/lib.rs index b8859e66a9..c8b956f48d 100644 --- a/pallets/admin-utils/src/lib.rs +++ b/pallets/admin-utils/src/lib.rs @@ -10,6 +10,7 @@ pub use pallet::*; // no sense for this as GRANDPA's `AuthorityId` is not a parameter -- it's always the same use sp_consensus_grandpa::AuthorityList; use sp_runtime::{DispatchResult, RuntimeAppPublic, traits::Member}; +use subtensor_runtime_common::Alpha as AlphaCurrency; mod benchmarking; @@ -1081,7 +1082,7 @@ pub mod pallet { pub fn sudo_set_nominator_min_required_stake( origin: OriginFor, // The minimum stake required for nominators. - min_stake: u64, + min_stake: AlphaCurrency, ) -> DispatchResult { ensure_root(origin)?; let prev_min_stake = pallet_subtensor::Pallet::::get_nominator_min_required_stake(); diff --git a/pallets/admin-utils/src/tests/mod.rs b/pallets/admin-utils/src/tests/mod.rs index 260dc9f7c3..b2ceaa0716 100644 --- a/pallets/admin-utils/src/tests/mod.rs +++ b/pallets/admin-utils/src/tests/mod.rs @@ -1014,7 +1014,7 @@ mod sudo_set_nominator_min_required_stake { #[test] fn can_only_be_called_by_admin() { new_test_ext().execute_with(|| { - let to_be_set: u64 = SubtensorModule::get_nominator_min_required_stake() + 5_u64; + let to_be_set = SubtensorModule::get_nominator_min_required_stake() + 5.into(); assert_eq!( AdminUtils::sudo_set_nominator_min_required_stake( <::RuntimeOrigin>::signed(U256::from(0)), @@ -1030,22 +1030,28 @@ mod sudo_set_nominator_min_required_stake { new_test_ext().execute_with(|| { assert_ok!(AdminUtils::sudo_set_nominator_min_required_stake( <::RuntimeOrigin>::root(), - 10u64 + 10.into() )); - assert_eq!(SubtensorModule::get_nominator_min_required_stake(), 10u64); + assert_eq!( + SubtensorModule::get_nominator_min_required_stake(), + 10.into() + ); assert_ok!(AdminUtils::sudo_set_nominator_min_required_stake( <::RuntimeOrigin>::root(), - 5u64 + 5.into() )); - assert_eq!(SubtensorModule::get_nominator_min_required_stake(), 5u64); + assert_eq!( + SubtensorModule::get_nominator_min_required_stake(), + 5.into() + ); }); } #[test] fn sets_a_higher_value() { new_test_ext().execute_with(|| { - let to_be_set: u64 = SubtensorModule::get_nominator_min_required_stake() + 5_u64; + let to_be_set = SubtensorModule::get_nominator_min_required_stake() + 5.into(); assert_ok!(AdminUtils::sudo_set_nominator_min_required_stake( <::RuntimeOrigin>::root(), to_be_set @@ -1611,14 +1617,14 @@ fn test_sets_a_lower_value_clears_small_nominations() { let owner_coldkey: U256 = U256::from(1); let staker_coldkey: U256 = U256::from(2); - let initial_nominator_min_required_stake = 10u64; - let nominator_min_required_stake_0 = 5u64; - let nominator_min_required_stake_1 = 20u64; + let initial_nominator_min_required_stake = 10.into(); + let nominator_min_required_stake_0 = 5.into(); + let nominator_min_required_stake_1 = 20.into(); assert!(nominator_min_required_stake_0 < nominator_min_required_stake_1); assert!(nominator_min_required_stake_0 < initial_nominator_min_required_stake); - let to_stake = initial_nominator_min_required_stake + 1; + let to_stake = initial_nominator_min_required_stake + 1.into(); assert!(to_stake > initial_nominator_min_required_stake); assert!(to_stake > nominator_min_required_stake_0); // Should stay when set @@ -1663,7 +1669,7 @@ fn test_sets_a_lower_value_clears_small_nominations() { &hotkey, &staker_coldkey, netuid - ) > 0 + ) > 0.into() ); assert_ok!(AdminUtils::sudo_set_nominator_min_required_stake( @@ -1682,7 +1688,7 @@ fn test_sets_a_lower_value_clears_small_nominations() { &staker_coldkey, netuid ), - 0 + 0.into() ); }); } diff --git a/pallets/subtensor/Cargo.toml b/pallets/subtensor/Cargo.toml index 93f88139ef..5617ca8c66 100644 --- a/pallets/subtensor/Cargo.toml +++ b/pallets/subtensor/Cargo.toml @@ -45,7 +45,7 @@ share-pool = { default-features = false, path = "../../primitives/share-pool" } safe-math = { default-features = false, path = "../../primitives/safe-math" } approx = { workspace = true } subtensor-swap-interface = { workspace = true } -subtensor-runtime-common = { workspace = true } +subtensor-runtime-common = { workspace = true, features = ["approx"] } pallet-collective = { version = "4.0.0-dev", default-features = false, path = "../collective" } pallet-drand = { path = "../drand", default-features = false } diff --git a/pallets/subtensor/runtime-api/src/lib.rs b/pallets/subtensor/runtime-api/src/lib.rs index e482a01251..42ac17dec8 100644 --- a/pallets/subtensor/runtime-api/src/lib.rs +++ b/pallets/subtensor/runtime-api/src/lib.rs @@ -12,7 +12,7 @@ use pallet_subtensor::rpc_info::{ subnet_info::{SubnetHyperparams, SubnetHyperparamsV2, SubnetInfo, SubnetInfov2}, }; use sp_runtime::AccountId32; -use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::{Alpha as AlphaCurrency, NetUid}; // Here we declare the runtime API. It is implemented it the `impl` block in // src/neuron_info.rs, src/subnet_info.rs, and src/delegate_info.rs @@ -20,7 +20,7 @@ sp_api::decl_runtime_apis! { pub trait DelegateInfoRuntimeApi { fn get_delegates() -> Vec>; fn get_delegate( delegate_account: AccountId32 ) -> Option>; - fn get_delegated( delegatee_account: AccountId32 ) -> Vec<(DelegateInfo, (Compact, Compact))>; + fn get_delegated( delegatee_account: AccountId32 ) -> Vec<(DelegateInfo, (Compact, Compact))>; } pub trait NeuronInfoRuntimeApi { diff --git a/pallets/subtensor/src/benchmarks.rs b/pallets/subtensor/src/benchmarks.rs index c62d1dcecc..1ef54001e9 100644 --- a/pallets/subtensor/src/benchmarks.rs +++ b/pallets/subtensor/src/benchmarks.rs @@ -15,6 +15,7 @@ use sp_runtime::{ traits::{BlakeTwo256, Hash}, }; use sp_std::vec; +use subtensor_runtime_common::{Alpha as AlphaCurrency, NetUid}; #[frame_benchmarking::v2::benchmarks] mod pallet_benchmarks { @@ -582,8 +583,8 @@ mod pallet_benchmarks { hotkey.clone() )); - let alpha_amount: u64 = 1_000_000; - SubnetAlphaOut::::insert(netuid, alpha_amount * 2); + let alpha_amount = AlphaCurrency::from(1_000_000); + SubnetAlphaOut::::insert(netuid, alpha_amount * 2.into()); Subtensor::::increase_stake_for_hotkey_and_coldkey_on_subnet( &hotkey, @@ -592,7 +593,10 @@ mod pallet_benchmarks { alpha_amount, ); - assert_eq!(TotalHotkeyAlpha::::get(&hotkey, netuid), alpha_amount); + assert_eq!( + TotalHotkeyAlpha::::get(&hotkey, netuid), + alpha_amount.into() + ); #[extrinsic_call] _( @@ -622,21 +626,24 @@ mod pallet_benchmarks { hotkey.clone() )); - let alpha_amount: u64 = 1_000_000; - SubnetAlphaOut::::insert(netuid, alpha_amount * 2); + let alpha_amount = 1_000_000; + SubnetAlphaOut::::insert(netuid, AlphaCurrency::from(alpha_amount * 2)); Subtensor::::increase_stake_for_hotkey_and_coldkey_on_subnet( &hotkey, &coldkey, netuid, - alpha_amount, + alpha_amount.into(), + ); + assert_eq!( + TotalHotkeyAlpha::::get(&hotkey, netuid), + alpha_amount.into() ); - assert_eq!(TotalHotkeyAlpha::::get(&hotkey, netuid), alpha_amount); #[extrinsic_call] _( RawOrigin::Signed(coldkey.clone()), hotkey.clone(), - alpha_amount, + alpha_amount.into(), netuid, ); } @@ -709,7 +716,7 @@ mod pallet_benchmarks { Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), amount); let tao_reserve = 150_000_000_000_u64; - let alpha_in = 100_000_000_000_u64; + let alpha_in = AlphaCurrency::from(100_000_000_000); SubnetTAO::::insert(netuid, tao_reserve); SubnetAlphaIn::::insert(netuid, alpha_in); @@ -752,7 +759,7 @@ mod pallet_benchmarks { )); SubnetTAO::::insert(netuid, deposit); - SubnetAlphaIn::::insert(netuid, deposit); + SubnetAlphaIn::::insert(netuid, AlphaCurrency::from(deposit)); TotalStake::::set(deposit); assert_ok!(Subtensor::::add_stake_limit( @@ -764,7 +771,7 @@ mod pallet_benchmarks { false )); - let alpha_to_move: u64 = + let alpha_to_move = Subtensor::::get_stake_for_hotkey_and_coldkey_on_subnet(&origin, &coldkey, netuid); Subtensor::::create_account_if_non_existent(&coldkey, &destination); @@ -802,7 +809,7 @@ mod pallet_benchmarks { let limit: u64 = 1_000_000_000; let tao_reserve = 150_000_000_000_u64; - let alpha_in = 100_000_000_000_u64; + let alpha_in = AlphaCurrency::from(100_000_000_000); SubnetTAO::::insert(netuid, tao_reserve); SubnetAlphaIn::::insert(netuid, alpha_in); @@ -825,7 +832,7 @@ mod pallet_benchmarks { u64_staked_amt )); - let amount_unstaked: u64 = 30_000_000_000; + let amount_unstaked = AlphaCurrency::from(30_000_000_000); #[extrinsic_call] _( @@ -852,7 +859,7 @@ mod pallet_benchmarks { Subtensor::::init_new_network(netuid2, 1); let tao_reserve = 150_000_000_000_u64; - let alpha_in = 100_000_000_000_u64; + let alpha_in = AlphaCurrency::from(100_000_000_000); SubnetTAO::::insert(netuid1, tao_reserve); SubnetAlphaIn::::insert(netuid1, alpha_in); SubnetTAO::::insert(netuid2, tao_reserve); @@ -863,7 +870,7 @@ mod pallet_benchmarks { let limit_stake: u64 = 6_000_000_000; let limit_swap: u64 = 1_000_000_000; let amount_to_be_staked = 440_000_000_000; - let amount_swapped: u64 = 30_000_000_000; + let amount_swapped = AlphaCurrency::from(30_000_000_000); Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), amount); assert_ok!(Subtensor::::burned_register( @@ -921,7 +928,7 @@ mod pallet_benchmarks { )); SubnetTAO::::insert(netuid, deposit); - SubnetAlphaIn::::insert(netuid, deposit); + SubnetAlphaIn::::insert(netuid, AlphaCurrency::from(deposit)); TotalStake::::set(deposit); assert_ok!(Subtensor::::add_stake_limit( @@ -933,7 +940,7 @@ mod pallet_benchmarks { false )); - let alpha_to_transfer: u64 = + let alpha_to_transfer = Subtensor::::get_stake_for_hotkey_and_coldkey_on_subnet(&hot, &coldkey, netuid); Subtensor::::create_account_if_non_existent(&dest, &hot); @@ -973,9 +980,9 @@ mod pallet_benchmarks { )); SubnetTAO::::insert(netuid1, deposit); - SubnetAlphaIn::::insert(netuid1, deposit); + SubnetAlphaIn::::insert(netuid1, AlphaCurrency::from(deposit)); SubnetTAO::::insert(netuid2, deposit); - SubnetAlphaIn::::insert(netuid2, deposit); + SubnetAlphaIn::::insert(netuid2, AlphaCurrency::from(deposit)); TotalStake::::set(deposit); assert_ok!(Subtensor::::add_stake_limit( @@ -987,7 +994,7 @@ mod pallet_benchmarks { false )); - let alpha_to_swap: u64 = + let alpha_to_swap = Subtensor::::get_stake_for_hotkey_and_coldkey_on_subnet(&hot, &coldkey, netuid1); #[extrinsic_call] @@ -1332,7 +1339,7 @@ mod pallet_benchmarks { Subtensor::::set_burn(netuid, 1); SubnetTAO::::insert(netuid, 150_000_000_000); - SubnetAlphaIn::::insert(netuid, 100_000_000_000); + SubnetAlphaIn::::insert(netuid, AlphaCurrency::from(100_000_000_000)); Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), 1000000u32.into()); diff --git a/pallets/subtensor/src/coinbase/root.rs b/pallets/subtensor/src/coinbase/root.rs index add7ae3d8f..4d6c9068ce 100644 --- a/pallets/subtensor/src/coinbase/root.rs +++ b/pallets/subtensor/src/coinbase/root.rs @@ -22,7 +22,7 @@ use frame_support::weights::Weight; use safe_math::*; use sp_core::Get; use substrate_fixed::types::I64F64; -use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::{Alpha as AlphaCurrency, Currency, NetUid}; impl Pallet { /// Fetches the total count of root network validators @@ -139,7 +139,7 @@ impl Pallet { } else { // --- 13.1.1 The network is full. Perform replacement. // Find the neuron with the lowest stake value to replace. - let mut lowest_stake: u64 = u64::MAX; + let mut lowest_stake = AlphaCurrency::MAX; let mut lowest_uid: u16 = 0; // Iterate over all keys in the root network to find the neuron with the lowest stake. diff --git a/pallets/subtensor/src/coinbase/run_coinbase.rs b/pallets/subtensor/src/coinbase/run_coinbase.rs index 1274a84a6f..be010af94f 100644 --- a/pallets/subtensor/src/coinbase/run_coinbase.rs +++ b/pallets/subtensor/src/coinbase/run_coinbase.rs @@ -2,7 +2,7 @@ use super::*; use alloc::collections::BTreeMap; use safe_math::*; use substrate_fixed::types::U96F32; -use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::{Alpha as AlphaCurrency, Currency, NetUid}; use subtensor_swap_interface::SwapHandler; use tle::stream_ciphers::AESGCMStreamCipherProvider; use tle::tlock::tld; @@ -84,7 +84,7 @@ impl Pallet { log::debug!("tao_in_i: {:?}", tao_in_i); // Get alpha_emission total let alpha_emission_i: U96F32 = asfloat!( - Self::get_block_emission_for_issuance(Self::get_alpha_issuance(*netuid_i)) + Self::get_block_emission_for_issuance(Self::get_alpha_issuance(*netuid_i).into()) .unwrap_or(0) ); log::debug!("alpha_emission_i: {:?}", alpha_emission_i); @@ -116,13 +116,15 @@ impl Pallet { // This operation changes the pool liquidity each block. for netuid_i in subnets_to_emit_to.iter() { // Inject Alpha in. - let alpha_in_i: u64 = tou64!(*alpha_in.get(netuid_i).unwrap_or(&asfloat!(0))); + let alpha_in_i: AlphaCurrency = + tou64!(*alpha_in.get(netuid_i).unwrap_or(&asfloat!(0))).into(); SubnetAlphaInEmission::::insert(*netuid_i, alpha_in_i); SubnetAlphaIn::::mutate(*netuid_i, |total| { *total = total.saturating_add(alpha_in_i); }); // Injection Alpha out. - let alpha_out_i: u64 = tou64!(*alpha_out.get(netuid_i).unwrap_or(&asfloat!(0))); + let alpha_out_i: AlphaCurrency = + tou64!(*alpha_out.get(netuid_i).unwrap_or(&asfloat!(0))).into(); SubnetAlphaOutEmission::::insert(*netuid_i, alpha_out_i); SubnetAlphaOut::::mutate(*netuid_i, |total| { *total = total.saturating_add(alpha_out_i); @@ -161,7 +163,7 @@ impl Pallet { alpha_out.insert(*netuid_i, alpha_out_i.saturating_sub(owner_cut_i)); // Accumulate the owner cut in pending. PendingOwnerCut::::mutate(*netuid_i, |total| { - *total = total.saturating_add(tou64!(owner_cut_i)); + *total = total.saturating_add(tou64!(owner_cut_i).into()); }); } @@ -197,7 +199,7 @@ impl Pallet { // Sell root emission through the pool. let swap_result = Self::swap_alpha_for_tao( *netuid_i, - tou64!(root_alpha), + tou64!(root_alpha).into(), T::SwapInterface::min_price(), ); if let Ok(ok_result) = swap_result { @@ -206,11 +208,11 @@ impl Pallet { log::debug!("root_tao: {:?}", root_tao); // Accumulate alpha emission in pending. PendingAlphaSwapped::::mutate(*netuid_i, |total| { - *total = total.saturating_add(tou64!(root_alpha)); + *total = total.saturating_add(tou64!(root_alpha).into()); }); // Accumulate alpha emission in pending. PendingEmission::::mutate(*netuid_i, |total| { - *total = total.saturating_add(tou64!(pending_alpha)); + *total = total.saturating_add(tou64!(pending_alpha).into()); }); // Accumulate root divs for subnet. PendingRootDivs::::mutate(*netuid_i, |total| { @@ -244,20 +246,20 @@ impl Pallet { LastMechansimStepBlock::::insert(netuid, current_block); // Get and drain the subnet pending emission. - let pending_alpha: u64 = PendingEmission::::get(netuid); - PendingEmission::::insert(netuid, 0); + let pending_alpha = PendingEmission::::get(netuid); + PendingEmission::::insert(netuid, AlphaCurrency::from(0)); // Get and drain the subnet pending root divs. let pending_tao: u64 = PendingRootDivs::::get(netuid); PendingRootDivs::::insert(netuid, 0); // Get this amount as alpha that was swapped for pending root divs. - let pending_swapped: u64 = PendingAlphaSwapped::::get(netuid); - PendingAlphaSwapped::::insert(netuid, 0); + let pending_swapped = PendingAlphaSwapped::::get(netuid); + PendingAlphaSwapped::::insert(netuid, AlphaCurrency::from(0)); // Get owner cut and drain. - let owner_cut: u64 = PendingOwnerCut::::get(netuid); - PendingOwnerCut::::insert(netuid, 0); + let owner_cut = PendingOwnerCut::::get(netuid); + PendingOwnerCut::::insert(netuid, AlphaCurrency::from(0)); // Drain pending root divs, alpha emission, and owner cut. Self::drain_pending_emission( @@ -276,10 +278,13 @@ impl Pallet { pub fn calculate_dividends_and_incentives( netuid: NetUid, - hotkey_emission: Vec<(T::AccountId, u64, u64)>, - ) -> (BTreeMap, BTreeMap) { + hotkey_emission: Vec<(T::AccountId, AlphaCurrency, AlphaCurrency)>, + ) -> ( + BTreeMap, + BTreeMap, + ) { // Accumulate emission of dividends and incentive per hotkey. - let mut incentives: BTreeMap = BTreeMap::new(); + let mut incentives: BTreeMap = BTreeMap::new(); let mut dividends: BTreeMap = BTreeMap::new(); for (hotkey, incentive, dividend) in hotkey_emission { // Accumulate incentives to miners. @@ -288,7 +293,7 @@ impl Pallet { .and_modify(|e| *e = e.saturating_add(incentive)) .or_insert(incentive); // Accumulate dividends to parents. - let div_tuples: Vec<(T::AccountId, u64)> = + let div_tuples: Vec<(T::AccountId, AlphaCurrency)> = Self::get_parent_child_dividends_distribution(&hotkey, netuid, dividend); // Accumulate dividends per hotkey. for (parent, parent_div) in div_tuples { @@ -305,10 +310,10 @@ impl Pallet { } pub fn calculate_dividend_distribution( - pending_alpha: u64, + pending_alpha: AlphaCurrency, pending_tao: u64, tao_weight: U96F32, - stake_map: BTreeMap, + stake_map: BTreeMap, dividends: BTreeMap, ) -> ( BTreeMap, @@ -330,22 +335,24 @@ impl Pallet { let mut root_dividends: BTreeMap = BTreeMap::new(); let mut alpha_dividends: BTreeMap = BTreeMap::new(); for (hotkey, dividend) in dividends { - if let Some((alpha_stake_u64, root_stake_u64)) = stake_map.get(&hotkey) { + if let Some((alpha_stake, root_stake)) = stake_map.get(&hotkey) { + let alpha_stake = alpha_stake.to_u64(); + let root_stake = root_stake.to_u64(); // Get hotkey ALPHA on subnet. - let alpha_stake: U96F32 = asfloat!(*alpha_stake_u64); + let alpha_stake = asfloat!(alpha_stake); // Get hotkey TAO on root. - let root_stake: U96F32 = asfloat!(*root_stake_u64); + let root_stake = asfloat!(root_stake); // Convert TAO to alpha with weight. - let root_alpha: U96F32 = root_stake.saturating_mul(tao_weight); + let root_alpha = root_stake.saturating_mul(tao_weight); // Get total from root and local - let total_alpha: U96F32 = alpha_stake.saturating_add(root_alpha); + let total_alpha = alpha_stake.saturating_add(root_alpha); // Compute root prop. - let root_prop: U96F32 = root_alpha.checked_div(total_alpha).unwrap_or(zero); + let root_prop = root_alpha.checked_div(total_alpha).unwrap_or(zero); // Compute root dividends - let root_divs: U96F32 = dividend.saturating_mul(root_prop); + let root_divs = dividend.saturating_mul(root_prop); // Compute alpha dividends - let alpha_divs: U96F32 = dividend.saturating_sub(root_divs); + let alpha_divs = dividend.saturating_sub(root_divs); // Record the alpha dividends. alpha_dividends .entry(hotkey.clone()) @@ -392,7 +399,7 @@ impl Pallet { log::debug!("hotkey: {:?}, alpha_share: {:?}", hotkey, alpha_share); // Compute the proportional pending_alpha to this hotkey. - let prop_alpha: U96F32 = asfloat!(pending_alpha).saturating_mul(alpha_share); + let prop_alpha = asfloat!(pending_alpha).saturating_mul(alpha_share); log::debug!("hotkey: {:?}, prop_alpha: {:?}", hotkey, prop_alpha); // Record the proportional alpha dividends. prop_alpha_dividends @@ -407,8 +414,8 @@ impl Pallet { pub fn distribute_dividends_and_incentives( netuid: NetUid, - owner_cut: u64, - incentives: BTreeMap, + owner_cut: AlphaCurrency, + incentives: BTreeMap, alpha_dividends: BTreeMap, tao_dividends: BTreeMap, ) { @@ -468,14 +475,14 @@ impl Pallet { &hotkey, &Owner::::get(&hotkey), netuid, - tou64!(alpha_take), + tou64!(alpha_take).into(), ); // Give all other nominators. log::debug!("hotkey: {:?} alpha_divs: {:?}", hotkey, alpha_divs); - Self::increase_stake_for_hotkey_on_subnet(&hotkey, netuid, tou64!(alpha_divs)); + Self::increase_stake_for_hotkey_on_subnet(&hotkey, netuid, tou64!(alpha_divs).into()); // Record dividends for this hotkey. AlphaDividendsPerSubnet::::mutate(netuid, &hotkey, |divs| { - *divs = divs.saturating_add(tou64!(alpha_divs)); + *divs = divs.saturating_add(tou64!(alpha_divs).into()); }); // Record total hotkey alpha based on which this value of AlphaDividendsPerSubnet // was calculated @@ -496,11 +503,15 @@ impl Pallet { &hotkey, &Owner::::get(hotkey.clone()), NetUid::ROOT, - tou64!(tao_take), + tou64!(tao_take).into(), ); // Give rest to nominators. log::debug!("hotkey: {:?} root_tao: {:?}", hotkey, root_tao); - Self::increase_stake_for_hotkey_on_subnet(&hotkey, NetUid::ROOT, tou64!(root_tao)); + Self::increase_stake_for_hotkey_on_subnet( + &hotkey, + NetUid::ROOT, + tou64!(root_tao).into(), + ); // Record root dividends for this validator on this subnet. TaoDividendsPerSubnet::::mutate(netuid, hotkey.clone(), |divs| { *divs = divs.saturating_add(tou64!(root_tao)); @@ -511,13 +522,13 @@ impl Pallet { pub fn get_stake_map( netuid: NetUid, hotkeys: Vec<&T::AccountId>, - ) -> BTreeMap { - let mut stake_map: BTreeMap = BTreeMap::new(); + ) -> BTreeMap { + let mut stake_map: BTreeMap = BTreeMap::new(); for hotkey in hotkeys { // Get hotkey ALPHA on subnet. - let alpha_stake: u64 = Self::get_stake_for_hotkey_on_subnet(hotkey, netuid); + let alpha_stake = Self::get_stake_for_hotkey_on_subnet(hotkey, netuid); // Get hotkey TAO on root. - let root_stake: u64 = Self::get_stake_for_hotkey_on_subnet(hotkey, NetUid::ROOT); + let root_stake = Self::get_stake_for_hotkey_on_subnet(hotkey, NetUid::ROOT); stake_map.insert(hotkey.clone(), (alpha_stake, root_stake)); } stake_map @@ -526,11 +537,11 @@ impl Pallet { pub fn calculate_dividend_and_incentive_distribution( netuid: NetUid, pending_tao: u64, - pending_validator_alpha: u64, - hotkey_emission: Vec<(T::AccountId, u64, u64)>, + pending_validator_alpha: AlphaCurrency, + hotkey_emission: Vec<(T::AccountId, AlphaCurrency, AlphaCurrency)>, tao_weight: U96F32, ) -> ( - BTreeMap, + BTreeMap, ( BTreeMap, BTreeMap, @@ -539,8 +550,7 @@ impl Pallet { let (incentives, dividends) = Self::calculate_dividends_and_incentives(netuid, hotkey_emission); - let stake_map: BTreeMap = - Self::get_stake_map(netuid, dividends.keys().collect::>()); + let stake_map = Self::get_stake_map(netuid, dividends.keys().collect::>()); let (alpha_dividends, tao_dividends) = Self::calculate_dividend_distribution( pending_validator_alpha, @@ -555,10 +565,10 @@ impl Pallet { pub fn drain_pending_emission( netuid: NetUid, - pending_alpha: u64, + pending_alpha: AlphaCurrency, pending_tao: u64, - pending_swapped: u64, - owner_cut: u64, + pending_swapped: AlphaCurrency, + owner_cut: AlphaCurrency, ) { log::debug!( "Draining pending alpha emission for netuid {:?}, pending_alpha: {:?}, pending_tao: {:?}, pending_swapped: {:?}, owner_cut: {:?}", @@ -572,7 +582,7 @@ impl Pallet { let tao_weight = Self::get_tao_weight(); // Run the epoch. - let hotkey_emission: Vec<(T::AccountId, u64, u64)> = + let hotkey_emission: Vec<(T::AccountId, AlphaCurrency, AlphaCurrency)> = Self::epoch(netuid, pending_alpha.saturating_add(pending_swapped)); log::debug!("hotkey_emission: {:?}", hotkey_emission); @@ -583,14 +593,15 @@ impl Pallet { // Important! If the incentives are 0, then Validators get 100% of the alpha. let incentive_sum = hotkey_emission .iter() - .map(|(_, incentive, _)| incentive) - .sum::(); + .fold(AlphaCurrency::default(), |acc, (_, incentive, _)| { + acc.saturating_add(*incentive) + }); log::debug!("incentive_sum: {:?}", incentive_sum); - let pending_validator_alpha: u64 = if incentive_sum != 0 { + let pending_validator_alpha = if !incentive_sum.is_zero() { pending_alpha .saturating_add(pending_swapped) - .saturating_div(2) + .saturating_div(2.into()) .saturating_sub(pending_swapped) } else { // If the incentive is 0, then Validators get 100% of the alpha. @@ -664,10 +675,10 @@ impl Pallet { pub fn get_parent_child_dividends_distribution( hotkey: &T::AccountId, netuid: NetUid, - dividends: u64, - ) -> Vec<(T::AccountId, u64)> { + dividends: AlphaCurrency, + ) -> Vec<(T::AccountId, AlphaCurrency)> { // hotkey dividends. - let mut dividend_tuples: Vec<(T::AccountId, u64)> = vec![]; + let mut dividend_tuples: Vec<(T::AccountId, AlphaCurrency)> = vec![]; // Calculate the hotkey's share of the validator emission based on its childkey take let validating_emission: U96F32 = U96F32::saturating_from_num(dividends); @@ -785,7 +796,10 @@ impl Pallet { log::debug!("remaining emission: {:?}", remaining_emission); // Add the parent's emission to the distribution list - dividend_tuples.push((parent.clone(), parent_emission.saturating_to_num::())); + dividend_tuples.push(( + parent.clone(), + parent_emission.saturating_to_num::().into(), + )); // Keep track of total emission distributed to parents to_parents = to_parents.saturating_add(parent_emission.saturating_to_num::()); @@ -803,7 +817,8 @@ impl Pallet { // This includes the take left from the parents and the self contribution. let child_emission = remaining_emission .saturating_add(total_child_emission_take) - .saturating_to_num::(); + .saturating_to_num::() + .into(); // Add the hotkey's own emission to the distribution list dividend_tuples.push((hotkey.clone(), child_emission)); diff --git a/pallets/subtensor/src/epoch/run_epoch.rs b/pallets/subtensor/src/epoch/run_epoch.rs index a636cdd9a1..4614d26752 100644 --- a/pallets/subtensor/src/epoch/run_epoch.rs +++ b/pallets/subtensor/src/epoch/run_epoch.rs @@ -4,13 +4,16 @@ use frame_support::IterableStorageDoubleMap; use safe_math::*; use sp_std::vec; use substrate_fixed::types::{I32F32, I64F64, I96F32}; -use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::{Alpha as AlphaCurrency, NetUid}; impl Pallet { /// Calculates reward consensus and returns the emissions for uids/hotkeys in a given `netuid`. /// (Dense version used only for testing purposes.) #[allow(clippy::indexing_slicing)] - pub fn epoch_dense(netuid: NetUid, rao_emission: u64) -> Vec<(T::AccountId, u64, u64)> { + pub fn epoch_dense( + netuid: NetUid, + rao_emission: AlphaCurrency, + ) -> Vec<(T::AccountId, AlphaCurrency, AlphaCurrency)> { // Get subnetwork size. let n: u16 = Self::get_subnetwork_n(netuid); log::trace!("n: {:?}", n); @@ -314,18 +317,18 @@ impl Pallet { .iter() .map(|se: &I32F32| I96F32::saturating_from_num(*se).saturating_mul(float_rao_emission)) .collect(); - let server_emission: Vec = server_emission + let server_emission: Vec = server_emission .iter() - .map(|e: &I96F32| e.saturating_to_num::()) + .map(|e: &I96F32| e.saturating_to_num::().into()) .collect(); let validator_emission: Vec = normalized_validator_emission .iter() .map(|ve: &I32F32| I96F32::saturating_from_num(*ve).saturating_mul(float_rao_emission)) .collect(); - let validator_emission: Vec = validator_emission + let validator_emission: Vec = validator_emission .iter() - .map(|e: &I96F32| e.saturating_to_num::()) + .map(|e: &I96F32| e.saturating_to_num::().into()) .collect(); // Used only to track combined emission in the storage. @@ -333,9 +336,9 @@ impl Pallet { .iter() .map(|ce: &I32F32| I96F32::saturating_from_num(*ce).saturating_mul(float_rao_emission)) .collect(); - let combined_emission: Vec = combined_emission + let combined_emission: Vec = combined_emission .iter() - .map(|e: &I96F32| e.saturating_to_num::()) + .map(|e: &I96F32| AlphaCurrency::from(e.saturating_to_num::())) .collect(); log::trace!("nSE: {:?}", &normalized_server_emission); @@ -352,7 +355,7 @@ impl Pallet { // =================== // == Value storage == // =================== - let cloned_emission: Vec = combined_emission.clone(); + let cloned_emission = combined_emission.clone(); let cloned_stake_weight: Vec = stake .iter() .map(|xi| fixed_proportion_to_u16(*xi)) @@ -439,9 +442,12 @@ impl Pallet { /// - Print debugging outputs. /// #[allow(clippy::indexing_slicing)] - pub fn epoch(netuid: NetUid, rao_emission: u64) -> Vec<(T::AccountId, u64, u64)> { + pub fn epoch( + netuid: NetUid, + rao_emission: AlphaCurrency, + ) -> Vec<(T::AccountId, AlphaCurrency, AlphaCurrency)> { // Get subnetwork size. - let n: u16 = Self::get_subnetwork_n(netuid); + let n = Self::get_subnetwork_n(netuid); log::trace!("Number of Neurons in Network: {:?}", n); // ====================== @@ -758,18 +764,18 @@ impl Pallet { .iter() .map(|se: &I32F32| I96F32::saturating_from_num(*se).saturating_mul(float_rao_emission)) .collect(); - let server_emission: Vec = server_emission + let server_emission: Vec = server_emission .iter() - .map(|e: &I96F32| e.saturating_to_num::()) + .map(|e: &I96F32| e.saturating_to_num::().into()) .collect(); let validator_emission: Vec = normalized_validator_emission .iter() .map(|ve: &I32F32| I96F32::saturating_from_num(*ve).saturating_mul(float_rao_emission)) .collect(); - let validator_emission: Vec = validator_emission + let validator_emission: Vec = validator_emission .iter() - .map(|e: &I96F32| e.saturating_to_num::()) + .map(|e: &I96F32| e.saturating_to_num::().into()) .collect(); // Only used to track emission in storage. @@ -777,9 +783,9 @@ impl Pallet { .iter() .map(|ce: &I32F32| I96F32::saturating_from_num(*ce).saturating_mul(float_rao_emission)) .collect(); - let combined_emission: Vec = combined_emission + let combined_emission: Vec = combined_emission .iter() - .map(|e: &I96F32| e.saturating_to_num::()) + .map(|e: &I96F32| AlphaCurrency::from(e.saturating_to_num::())) .collect(); log::trace!( @@ -809,7 +815,7 @@ impl Pallet { .iter() .map(|xi| fixed_proportion_to_u16(*xi)) .collect::>(); - let cloned_emission: Vec = combined_emission.clone(); + let cloned_emission = combined_emission.clone(); let cloned_ranks: Vec = ranks .iter() .map(|xi| fixed_proportion_to_u16(*xi)) diff --git a/pallets/subtensor/src/lib.rs b/pallets/subtensor/src/lib.rs index 62fc8aeb71..94775a66b1 100644 --- a/pallets/subtensor/src/lib.rs +++ b/pallets/subtensor/src/lib.rs @@ -32,7 +32,7 @@ use sp_runtime::{ transaction_validity::{TransactionValidity, TransactionValidityError}, }; use sp_std::marker::PhantomData; -use subtensor_runtime_common::{NetUid, Alpha as AlphaCurrency}; +use subtensor_runtime_common::{Alpha as AlphaCurrency, Currency, NetUid}; // ============================ // ==== Benchmark Imports ===== @@ -90,7 +90,7 @@ pub mod pallet { use sp_std::vec::Vec; use substrate_fixed::types::{I96F32, U64F64}; use subtensor_macros::freeze_struct; - use subtensor_runtime_common::NetUid; + use subtensor_runtime_common::{Alpha as AlphaCurrency, NetUid}; #[cfg(not(feature = "std"))] use alloc::boxed::Box; @@ -309,6 +309,11 @@ pub mod pallet { pub fn DefaultZeroU64() -> u64 { 0 } + /// Default value for Alpha cyrrency. + #[pallet::type_value] + pub fn DefaultZeroAlpha() -> AlphaCurrency { + 0.into() + } #[pallet::type_value] /// Default value for zero. pub fn DefaultZeroU128() -> u128 { @@ -553,8 +558,8 @@ pub mod pallet { } #[pallet::type_value] /// Default value for pending emission. - pub fn DefaultPendingEmission() -> u64 { - 0 + pub fn DefaultPendingEmission() -> AlphaCurrency { + 0.into() } #[pallet::type_value] /// Default value for blocks since last step. @@ -982,7 +987,7 @@ pub mod pallet { T::AccountId, AlphaCurrency, ValueQuery, - DefaultZeroU64, + DefaultZeroAlpha, >; #[pallet::storage] // --- DMAP ( netuid, hotkey ) --> u64 | Last total root dividend paid to this hotkey on this subnet. pub type TaoDividendsPerSubnet = StorageDoubleMap< @@ -1012,7 +1017,7 @@ pub mod pallet { NetUid, AlphaCurrency, ValueQuery, - DefaultZeroU64, + DefaultZeroAlpha, >; /// ========================== @@ -1047,24 +1052,24 @@ pub mod pallet { StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultZeroU64>; #[pallet::storage] // --- MAP ( netuid ) --> alpha_in_emission | Returns the amount of alph in emission into the pool per block. pub type SubnetAlphaInEmission = - StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultZeroU64>; + StorageMap<_, Identity, NetUid, AlphaCurrency, ValueQuery, DefaultZeroAlpha>; #[pallet::storage] // --- MAP ( netuid ) --> alpha_out_emission | Returns the amount of alpha out emission into the network per block. pub type SubnetAlphaOutEmission = - StorageMap<_, Identity, NetUid, AlphaCurrency, ValueQuery, DefaultZeroU64>; + StorageMap<_, Identity, NetUid, AlphaCurrency, ValueQuery, DefaultZeroAlpha>; #[pallet::storage] // --- MAP ( netuid ) --> tao_in_emission | Returns the amount of tao emitted into this subent on the last block. pub type SubnetTaoInEmission = StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultZeroU64>; #[pallet::storage] // --- MAP ( netuid ) --> alpha_supply_in_pool | Returns the amount of alpha in the pool. pub type SubnetAlphaIn = - StorageMap<_, Identity, NetUid, AlphaCurrency, ValueQuery, DefaultZeroU64>; + StorageMap<_, Identity, NetUid, AlphaCurrency, ValueQuery, DefaultZeroAlpha>; #[pallet::storage] // --- MAP ( netuid ) --> alpha_supply_user_in_pool | Returns the amount of alpha in the pool provided by users as liquidity. pub type SubnetAlphaInProvided = - StorageMap<_, Identity, NetUid, AlphaCurrency, ValueQuery, DefaultZeroU64>; + StorageMap<_, Identity, NetUid, AlphaCurrency, ValueQuery, DefaultZeroAlpha>; #[pallet::storage] /// --- MAP ( netuid ) --> alpha_supply_in_subnet | Returns the amount of alpha in the subnet. /// TODO: Deprecate, not accurate and not used in v3 anymore pub type SubnetAlphaOut = - StorageMap<_, Identity, NetUid, AlphaCurrency, ValueQuery, DefaultZeroU64>; + StorageMap<_, Identity, NetUid, AlphaCurrency, ValueQuery, DefaultZeroAlpha>; #[pallet::storage] // --- MAP ( cold ) --> Vec | Maps coldkey to hotkeys that stake to it pub type StakingHotkeys = StorageMap<_, Blake2_128Concat, T::AccountId, Vec, ValueQuery>; @@ -1091,7 +1096,7 @@ pub mod pallet { NetUid, AlphaCurrency, ValueQuery, - DefaultZeroU64, + DefaultZeroAlpha, >; #[pallet::storage] // --- DMAP ( hot, netuid ) --> alpha | Returns the total amount of alpha a hotkey owned in the last epoch. pub type TotalHotkeyAlphaLastEpoch = StorageDoubleMap< @@ -1102,7 +1107,7 @@ pub mod pallet { NetUid, AlphaCurrency, ValueQuery, - DefaultZeroU64, + DefaultZeroAlpha, >; #[pallet::storage] /// DMAP ( hot, netuid ) --> total_alpha_shares | Returns the number of alpha shares for a hotkey on a subnet. @@ -1170,7 +1175,8 @@ pub mod pallet { /// ITEM( network_rate_limit ) pub type NetworkRateLimit = StorageValue<_, u64, ValueQuery, DefaultNetworkRateLimit>; #[pallet::storage] // --- ITEM( nominator_min_required_stake ) - pub type NominatorMinRequiredStake = StorageValue<_, u64, ValueQuery, DefaultZeroU64>; + pub type NominatorMinRequiredStake = + StorageValue<_, AlphaCurrency, ValueQuery, DefaultZeroAlpha>; #[pallet::storage] /// ITEM( weights_version_key_rate_limit ) --- Rate limit in tempos. pub type WeightsVersionKeyRateLimit = @@ -1253,7 +1259,7 @@ pub mod pallet { #[pallet::storage] /// --- MAP ( netuid ) --> pending_emission pub type PendingEmission = - StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultPendingEmission>; + StorageMap<_, Identity, NetUid, AlphaCurrency, ValueQuery, DefaultPendingEmission>; #[pallet::storage] /// --- MAP ( netuid ) --> pending_root_emission pub type PendingRootDivs = @@ -1261,11 +1267,11 @@ pub mod pallet { #[pallet::storage] /// --- MAP ( netuid ) --> pending_alpha_swapped pub type PendingAlphaSwapped = - StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultZeroU64>; + StorageMap<_, Identity, NetUid, AlphaCurrency, ValueQuery, DefaultZeroAlpha>; #[pallet::storage] /// --- MAP ( netuid ) --> pending_owner_cut pub type PendingOwnerCut = - StorageMap<_, Identity, NetUid, u64, ValueQuery, DefaultZeroU64>; + StorageMap<_, Identity, NetUid, AlphaCurrency, ValueQuery, DefaultZeroAlpha>; #[pallet::storage] /// --- MAP ( netuid ) --> blocks_since_last_step pub type BlocksSinceLastStep = @@ -1492,8 +1498,7 @@ pub mod pallet { StorageMap<_, Identity, NetUid, Vec, ValueQuery, EmptyU16Vec>; #[pallet::storage] /// --- MAP ( netuid ) --> emission - pub type Emission = - StorageMap<_, Identity, NetUid, Vec, ValueQuery, EmptyU64Vec>; + pub type Emission = StorageMap<_, Identity, NetUid, Vec, ValueQuery>; #[pallet::storage] /// --- MAP ( netuid ) --> last_update pub type LastUpdate = @@ -2115,7 +2120,7 @@ where *amount_unstaked, false, ), - Self::get_priority_staking(who, hotkey, *amount_unstaked), + Self::get_priority_staking(who, hotkey, (*amount_unstaked).into()), ) .map(|validity| (validity, Some(who.clone()), origin.clone())) } @@ -2142,7 +2147,7 @@ where max_amount, *allow_partial, ), - Self::get_priority_staking(who, hotkey, *amount_unstaked), + Self::get_priority_staking(who, hotkey, (*amount_unstaked).into()), ) .map(|validity| (validity, Some(who.clone()), origin.clone())) } @@ -2187,7 +2192,7 @@ where None, false, ), - Self::get_priority_staking(who, origin_hotkey, *alpha_amount), + Self::get_priority_staking(who, origin_hotkey, (*alpha_amount).into()), ) .map(|validity| (validity, Some(who.clone()), origin.clone())) } @@ -2216,7 +2221,7 @@ where None, true, ), - Self::get_priority_staking(who, hotkey, *alpha_amount), + Self::get_priority_staking(who, hotkey, (*alpha_amount).into()), ) .map(|validity| (validity, Some(who.clone()), origin.clone())) } @@ -2244,7 +2249,7 @@ where None, false, ), - Self::get_priority_staking(who, hotkey, *alpha_amount), + Self::get_priority_staking(who, hotkey, (*alpha_amount).into()), ) .map(|validity| (validity, Some(who.clone()), origin.clone())) } @@ -2283,7 +2288,7 @@ where Some(*allow_partial), false, ), - Self::get_priority_staking(who, hotkey, *alpha_amount), + Self::get_priority_staking(who, hotkey, (*alpha_amount).into()), ) .map(|validity| (validity, Some(who.clone()), origin.clone())) } @@ -2526,7 +2531,7 @@ impl> SubnetTAO::::get(netuid).saturating_add(SubnetTaoProvided::::get(netuid)) } - fn alpha_reserve(netuid: NetUid) -> u64 { + fn alpha_reserve(netuid: NetUid) -> AlphaCurrency { SubnetAlphaIn::::get(netuid).saturating_add(SubnetAlphaInProvided::::get(netuid)) } @@ -2550,7 +2555,11 @@ impl> pallet_balances::Pallet::::free_balance(account_id) } - fn alpha_balance(netuid: NetUid, coldkey: &T::AccountId, hotkey: &T::AccountId) -> u64 { + fn alpha_balance( + netuid: NetUid, + coldkey: &T::AccountId, + hotkey: &T::AccountId, + ) -> AlphaCurrency { Self::get_stake_for_hotkey_and_coldkey_on_subnet(hotkey, coldkey, netuid) } @@ -2566,7 +2575,7 @@ impl> coldkey: &T::AccountId, hotkey: &T::AccountId, netuid: NetUid, - alpha: u64, + alpha: AlphaCurrency, ) -> Result<(), DispatchError> { ensure!( Self::hotkey_account_exists(hotkey), @@ -2582,8 +2591,8 @@ impl> coldkey: &T::AccountId, hotkey: &T::AccountId, netuid: NetUid, - alpha: u64, - ) -> Result { + alpha: AlphaCurrency, + ) -> Result { ensure!( Self::hotkey_account_exists(hotkey), Error::::HotKeyAccountNotExists @@ -2602,11 +2611,11 @@ impl> Self::decrease_provided_tao_reserve(netuid, tao); } - fn increase_provided_alpha_reserve(netuid: NetUid, alpha: u64) { + fn increase_provided_alpha_reserve(netuid: NetUid, alpha: AlphaCurrency) { Self::increase_provided_alpha_reserve(netuid, alpha); } - fn decrease_provided_alpha_reserve(netuid: NetUid, alpha: u64) { + fn decrease_provided_alpha_reserve(netuid: NetUid, alpha: AlphaCurrency) { Self::decrease_provided_alpha_reserve(netuid, alpha); } } diff --git a/pallets/subtensor/src/macros/dispatches.rs b/pallets/subtensor/src/macros/dispatches.rs index 8ceccc5fa2..76012963c1 100644 --- a/pallets/subtensor/src/macros/dispatches.rs +++ b/pallets/subtensor/src/macros/dispatches.rs @@ -11,6 +11,7 @@ mod dispatches { use frame_system::pallet_prelude::BlockNumberFor; use sp_core::ecdsa::Signature; use sp_runtime::traits::Saturating; + // use subtensor_runtime_common::{Alpha as AlphaCurrency}; use crate::MAX_CRV3_COMMIT_SIZE_BYTES; /// Dispatchable functions allow users to interact with the pallet and invoke state changes. @@ -636,7 +637,7 @@ mod dispatches { origin: OriginFor, hotkey: T::AccountId, netuid: NetUid, - amount_unstaked: u64, + amount_unstaked: AlphaCurrency, ) -> DispatchResult { Self::do_remove_stake(origin, hotkey, netuid, amount_unstaked) } @@ -1646,7 +1647,7 @@ mod dispatches { destination_hotkey: T::AccountId, origin_netuid: NetUid, destination_netuid: NetUid, - alpha_amount: u64, + alpha_amount: AlphaCurrency, ) -> DispatchResult { Self::do_move_stake( origin, @@ -1689,7 +1690,7 @@ mod dispatches { hotkey: T::AccountId, origin_netuid: NetUid, destination_netuid: NetUid, - alpha_amount: u64, + alpha_amount: AlphaCurrency, ) -> DispatchResult { Self::do_transfer_stake( origin, @@ -1733,7 +1734,7 @@ mod dispatches { hotkey: T::AccountId, origin_netuid: NetUid, destination_netuid: NetUid, - alpha_amount: u64, + alpha_amount: AlphaCurrency, ) -> DispatchResult { Self::do_swap_stake( origin, @@ -1858,7 +1859,7 @@ mod dispatches { origin: OriginFor, hotkey: T::AccountId, netuid: NetUid, - amount_unstaked: u64, + amount_unstaked: AlphaCurrency, limit_price: u64, allow_partial: bool, ) -> DispatchResult { @@ -1906,7 +1907,7 @@ mod dispatches { hotkey: T::AccountId, origin_netuid: NetUid, destination_netuid: NetUid, - alpha_amount: u64, + alpha_amount: AlphaCurrency, limit_price: u64, allow_partial: bool, ) -> DispatchResult { @@ -2027,7 +2028,7 @@ mod dispatches { pub fn recycle_alpha( origin: T::RuntimeOrigin, hotkey: T::AccountId, - amount: u64, + amount: AlphaCurrency, netuid: NetUid, ) -> DispatchResult { Self::do_recycle_alpha(origin, hotkey, amount, netuid) @@ -2052,7 +2053,7 @@ mod dispatches { pub fn burn_alpha( origin: T::RuntimeOrigin, hotkey: T::AccountId, - amount: u64, + amount: AlphaCurrency, netuid: NetUid, ) -> DispatchResult { Self::do_burn_alpha(origin, hotkey, amount, netuid) diff --git a/pallets/subtensor/src/macros/events.rs b/pallets/subtensor/src/macros/events.rs index 3f3c71860d..8c1ea576f7 100644 --- a/pallets/subtensor/src/macros/events.rs +++ b/pallets/subtensor/src/macros/events.rs @@ -16,7 +16,7 @@ mod events { /// stake has been transferred from the a coldkey account onto the hotkey staking account. StakeAdded(T::AccountId, T::AccountId, u64, u64, NetUid, u64), /// stake has been removed from the hotkey staking account onto the coldkey account. - StakeRemoved(T::AccountId, T::AccountId, u64, u64, NetUid, u64), + StakeRemoved(T::AccountId, T::AccountId, u64, AlphaCurrency, NetUid, u64), /// stake has been moved from origin (hotkey, subnet ID) to destination (hotkey, subnet ID) of this amount (in TAO). StakeMoved( T::AccountId, @@ -304,13 +304,13 @@ mod events { /// /// Parameters: /// (coldkey, hotkey, amount, subnet_id) - AlphaRecycled(T::AccountId, T::AccountId, u64, NetUid), + AlphaRecycled(T::AccountId, T::AccountId, AlphaCurrency, NetUid), /// Alpha have been burned without reducing AlphaOut. /// /// Parameters: /// (coldkey, hotkey, amount, subnet_id) - AlphaBurned(T::AccountId, T::AccountId, u64, NetUid), + AlphaBurned(T::AccountId, T::AccountId, AlphaCurrency, NetUid), /// An EVM key has been associated with a hotkey. EvmKeyAssociated { diff --git a/pallets/subtensor/src/macros/genesis.rs b/pallets/subtensor/src/macros/genesis.rs index ff8f4864b4..5d6df59390 100644 --- a/pallets/subtensor/src/macros/genesis.rs +++ b/pallets/subtensor/src/macros/genesis.rs @@ -45,7 +45,7 @@ mod genesis { let hotkey = DefaultAccount::::get(); SubnetMechanism::::insert(netuid, 1); // Make dynamic. Owner::::insert(hotkey.clone(), hotkey.clone()); - SubnetAlphaIn::::insert(netuid, 10_000_000_000); + SubnetAlphaIn::::insert(netuid, AlphaCurrency::from(10_000_000_000)); SubnetTAO::::insert(netuid, 10_000_000_000); NetworksAdded::::insert(netuid, true); TotalNetworks::::mutate(|n| *n = n.saturating_add(1)); @@ -64,14 +64,18 @@ mod genesis { (hotkey.clone(), hotkey.clone(), netuid), U64F64::saturating_from_num(1_000_000_000), ); - TotalHotkeyAlpha::::insert(hotkey.clone(), netuid, 1_000_000_000); + TotalHotkeyAlpha::::insert( + hotkey.clone(), + netuid, + AlphaCurrency::from(1_000_000_000), + ); TotalHotkeyShares::::insert( hotkey.clone(), netuid, U64F64::saturating_from_num(1_000_000_000), ); // TotalColdkeyAlpha::::insert(hotkey.clone(), netuid, 1_000_000_000); - SubnetAlphaOut::::insert(netuid, 1_000_000_000); + SubnetAlphaOut::::insert(netuid, AlphaCurrency::from(1_000_000_000)); let mut staking_hotkeys = StakingHotkeys::::get(hotkey.clone()); if !staking_hotkeys.contains(&hotkey) { staking_hotkeys.push(hotkey.clone()); @@ -84,7 +88,7 @@ mod genesis { Rank::::mutate(netuid, |v| v.push(0)); Trust::::mutate(netuid, |v| v.push(0)); Active::::mutate(netuid, |v| v.push(true)); - Emission::::mutate(netuid, |v| v.push(0)); + Emission::::mutate(netuid, |v| v.push(0.into())); Consensus::::mutate(netuid, |v| v.push(0)); Incentive::::mutate(netuid, |v| v.push(0)); Dividends::::mutate(netuid, |v| v.push(0)); diff --git a/pallets/subtensor/src/migrations/migrate_delete_subnet_3.rs b/pallets/subtensor/src/migrations/migrate_delete_subnet_3.rs index f9c4b3c196..a30f0a84ea 100644 --- a/pallets/subtensor/src/migrations/migrate_delete_subnet_3.rs +++ b/pallets/subtensor/src/migrations/migrate_delete_subnet_3.rs @@ -6,6 +6,7 @@ use frame_support::{ }; use log::info; use sp_std::vec::Vec; +use subtensor_runtime_common::NetUid; /// Constant for logging purposes const LOG_TARGET: &str = "migrate_delete_subnet_3"; diff --git a/pallets/subtensor/src/migrations/migrate_rao.rs b/pallets/subtensor/src/migrations/migrate_rao.rs index ebc99cdb7a..16aa1dbf83 100644 --- a/pallets/subtensor/src/migrations/migrate_rao.rs +++ b/pallets/subtensor/src/migrations/migrate_rao.rs @@ -2,6 +2,7 @@ use alloc::{format, string::String}; use frame_support::IterableStorageMap; use frame_support::{traits::Get, weights::Weight}; +use subtensor_runtime_common::{Alpha as AlphaCurrency, NetUid}; use super::*; @@ -64,7 +65,7 @@ pub fn migrate_rao() -> Weight { for netuid in netuids.iter() { if netuid.is_root() { // Give root a single RAO in pool to avoid any catestrophic division by zero. - SubnetAlphaIn::::insert(netuid, 1_000_000_000); + SubnetAlphaIn::::insert(netuid, AlphaCurrency::from(1_000_000_000)); SubnetMechanism::::insert(netuid, 0); // Set to zero mechanism. TokenSymbol::::insert(netuid, Pallet::::get_symbol_for_subnet(NetUid::ROOT)); continue; @@ -96,8 +97,8 @@ pub fn migrate_rao() -> Weight { TotalStake::::mutate(|total| { *total = total.saturating_add(pool_initial_tao); }); // Increase total stake. - SubnetAlphaIn::::insert(netuid, pool_initial_tao); // Set initial alpha to pool initial tao. - SubnetAlphaOut::::insert(netuid, 0); // Set zero subnet alpha out. + SubnetAlphaIn::::insert(netuid, AlphaCurrency::from(pool_initial_tao)); // Set initial alpha to pool initial tao. + SubnetAlphaOut::::insert(netuid, AlphaCurrency::ZERO); // Set zero subnet alpha out. SubnetMechanism::::insert(netuid, 1); // Convert to dynamic immediately with initialization. // Set the token symbol for this subnet using Self instead of Pallet:: diff --git a/pallets/subtensor/src/migrations/migrate_remove_zero_total_hotkey_alpha.rs b/pallets/subtensor/src/migrations/migrate_remove_zero_total_hotkey_alpha.rs index 3b45615bf4..670c3e0e16 100644 --- a/pallets/subtensor/src/migrations/migrate_remove_zero_total_hotkey_alpha.rs +++ b/pallets/subtensor/src/migrations/migrate_remove_zero_total_hotkey_alpha.rs @@ -31,7 +31,7 @@ pub fn migrate_remove_zero_total_hotkey_alpha() -> Weight { // For each (hotkey, netuid, alpha) entry, remove if alpha == 0 for (hotkey, netuid, alpha) in TotalHotkeyAlpha::::iter() { - if alpha == 0 { + if alpha == 0.into() { TotalHotkeyAlpha::::remove(&hotkey, netuid); removed_entries_count = removed_entries_count.saturating_add(1); } diff --git a/pallets/subtensor/src/migrations/migrate_set_min_burn.rs b/pallets/subtensor/src/migrations/migrate_set_min_burn.rs index 8a74e1e51c..e11dc5e82d 100644 --- a/pallets/subtensor/src/migrations/migrate_set_min_burn.rs +++ b/pallets/subtensor/src/migrations/migrate_set_min_burn.rs @@ -2,6 +2,7 @@ use alloc::string::String; use frame_support::IterableStorageMap; use frame_support::{traits::Get, weights::Weight}; +use subtensor_runtime_common::NetUid; use super::*; diff --git a/pallets/subtensor/src/migrations/migrate_set_min_difficulty.rs b/pallets/subtensor/src/migrations/migrate_set_min_difficulty.rs index bdc6c993e2..31c85b5831 100644 --- a/pallets/subtensor/src/migrations/migrate_set_min_difficulty.rs +++ b/pallets/subtensor/src/migrations/migrate_set_min_difficulty.rs @@ -2,6 +2,7 @@ use alloc::string::String; use frame_support::IterableStorageMap; use frame_support::{traits::Get, weights::Weight}; +use subtensor_runtime_common::NetUid; use super::*; diff --git a/pallets/subtensor/src/migrations/migrate_to_v1_separate_emission.rs b/pallets/subtensor/src/migrations/migrate_to_v1_separate_emission.rs index edea6a4c4b..84d8a681da 100644 --- a/pallets/subtensor/src/migrations/migrate_to_v1_separate_emission.rs +++ b/pallets/subtensor/src/migrations/migrate_to_v1_separate_emission.rs @@ -6,6 +6,7 @@ use frame_support::{ }; use log::{info, warn}; use sp_std::vec::Vec; +use subtensor_runtime_common::NetUid; /// Constant for logging purposes const LOG_TARGET: &str = "loadedemissionmigration"; diff --git a/pallets/subtensor/src/migrations/migrate_transfer_ownership_to_foundation.rs b/pallets/subtensor/src/migrations/migrate_transfer_ownership_to_foundation.rs index 10a93784bb..25a11958f0 100644 --- a/pallets/subtensor/src/migrations/migrate_transfer_ownership_to_foundation.rs +++ b/pallets/subtensor/src/migrations/migrate_transfer_ownership_to_foundation.rs @@ -8,6 +8,7 @@ use frame_support::{ use log::info; use sp_core::Get; use sp_std::vec::Vec; +use subtensor_runtime_common::NetUid; /// Constant for logging purposes const LOG_TARGET: &str = "migrate_transfer_ownership"; diff --git a/pallets/subtensor/src/rpc_info/delegate_info.rs b/pallets/subtensor/src/rpc_info/delegate_info.rs index 94e4034b66..5395b331cf 100644 --- a/pallets/subtensor/src/rpc_info/delegate_info.rs +++ b/pallets/subtensor/src/rpc_info/delegate_info.rs @@ -6,7 +6,7 @@ use substrate_fixed::types::U64F64; extern crate alloc; use alloc::collections::BTreeMap; use codec::Compact; -use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::{Alpha as AlphaCurrency, NetUid}; #[freeze_struct("1fafc4fcf28cba7a")] #[derive(Decode, Encode, PartialEq, Eq, Clone, Debug, TypeInfo)] @@ -96,7 +96,7 @@ impl Pallet { validator_permits.push((*netuid).into()); } - let emission: U64F64 = Self::get_emission_for_uid(*netuid, uid).into(); + let emission: U64F64 = u64::from(Self::get_emission_for_uid(*netuid, uid)).into(); let tempo: U64F64 = Self::get_tempo(*netuid).into(); if tempo > U64F64::saturating_from_num(0) { let epochs_per_day: U64F64 = U64F64::saturating_from_num(7200).safe_div(tempo); @@ -109,8 +109,11 @@ impl Pallet { let owner = Self::get_owning_coldkey_for_hotkey(&delegate.clone()); let take: Compact = >::get(delegate.clone()).into(); - let total_stake: U64F64 = - Self::get_stake_for_hotkey_on_subnet(&delegate.clone(), NetUid::ROOT).into(); + let total_stake: U64F64 = u64::from(Self::get_stake_for_hotkey_on_subnet( + &delegate.clone(), + NetUid::ROOT, + )) + .into(); let return_per_1000: U64F64 = Self::return_per_1000_tao(take, total_stake, emissions_per_day); @@ -153,9 +156,14 @@ impl Pallet { /// pub fn get_delegated( delegatee: T::AccountId, - ) -> Vec<(DelegateInfo, (Compact, Compact))> { - let mut delegates: Vec<(DelegateInfo, (Compact, Compact))> = - Vec::new(); + ) -> Vec<( + DelegateInfo, + (Compact, Compact), + )> { + let mut delegates: Vec<( + DelegateInfo, + (Compact, Compact), + )> = Vec::new(); for delegate in as IterableStorageMap>::iter_keys() { // Staked to this delegate, so add to list for (netuid, _) in Alpha::::iter_prefix((delegate.clone(), delegatee.clone())) { diff --git a/pallets/subtensor/src/rpc_info/dynamic_info.rs b/pallets/subtensor/src/rpc_info/dynamic_info.rs index e6838404d4..a3b2509f07 100644 --- a/pallets/subtensor/src/rpc_info/dynamic_info.rs +++ b/pallets/subtensor/src/rpc_info/dynamic_info.rs @@ -4,9 +4,9 @@ use codec::Compact; use frame_support::pallet_prelude::{Decode, Encode}; use substrate_fixed::types::I96F32; use subtensor_macros::freeze_struct; -use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::{Alpha, NetUid}; -#[freeze_struct("ddf2c1fdd5bb7e7")] +#[freeze_struct("a21076dce0494dfa")] #[derive(Decode, Encode, PartialEq, Eq, Clone, Debug, TypeInfo)] pub struct DynamicInfo { netuid: Compact, @@ -18,13 +18,13 @@ pub struct DynamicInfo { last_step: Compact, blocks_since_last_step: Compact, emission: Compact, - alpha_in: Compact, - alpha_out: Compact, + alpha_in: Compact, + alpha_out: Compact, tao_in: Compact, - alpha_out_emission: Compact, - alpha_in_emission: Compact, + alpha_out_emission: Compact, + alpha_in_emission: Compact, tao_in_emission: Compact, - pending_alpha_emission: Compact, + pending_alpha_emission: Compact, pending_root_emission: Compact, subnet_volume: Compact, network_registered_at: Compact, diff --git a/pallets/subtensor/src/rpc_info/metagraph.rs b/pallets/subtensor/src/rpc_info/metagraph.rs index d910bbaff5..051c41f1ee 100644 --- a/pallets/subtensor/src/rpc_info/metagraph.rs +++ b/pallets/subtensor/src/rpc_info/metagraph.rs @@ -7,9 +7,9 @@ use frame_support::pallet_prelude::{Decode, Encode}; use substrate_fixed::types::I64F64; use substrate_fixed::types::I96F32; use subtensor_macros::freeze_struct; -use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::{Alpha, NetUid}; -#[freeze_struct("140374b562d8498b")] +#[freeze_struct("e1d9ed0a752ab014")] #[derive(Decode, Encode, PartialEq, Eq, Clone, Debug, TypeInfo)] pub struct Metagraph { // Subnet index @@ -32,17 +32,17 @@ pub struct Metagraph { blocks_since_last_step: Compact, // blocks since last epoch. // Subnet emission terms - subnet_emission: Compact, // subnet emission via stao - alpha_in: Compact, // amount of alpha in reserve - alpha_out: Compact, // amount of alpha outstanding - tao_in: Compact, // amount of tao injected per block - alpha_out_emission: Compact, // amount injected in alpha reserves per block - alpha_in_emission: Compact, // amount injected outstanding per block - tao_in_emission: Compact, // amount of tao injected per block - pending_alpha_emission: Compact, // pending alpha to be distributed - pending_root_emission: Compact, // panding tao for root divs to be distributed - subnet_volume: Compact, // volume of the subnet in TAO - moving_price: I96F32, // subnet moving price. + subnet_emission: Compact, // subnet emission via stao + alpha_in: Compact, // amount of alpha in reserve + alpha_out: Compact, // amount of alpha outstanding + tao_in: Compact, // amount of tao injected per block + alpha_out_emission: Compact, // amount injected in alpha reserves per block + alpha_in_emission: Compact, // amount injected outstanding per block + tao_in_emission: Compact, // amount of tao injected per block + pending_alpha_emission: Compact, // pending alpha to be distributed + pending_root_emission: Compact, // panding tao for root divs to be distributed + subnet_volume: Compact, // volume of the subnet in TAO + moving_price: I96F32, // subnet moving price. // Hparams for epoch rho: Compact, // subnet rho param @@ -93,7 +93,7 @@ pub struct Metagraph { validator_permit: Vec, // Val permit per UID pruning_score: Vec>, // Pruning per UID last_update: Vec>, // Last update per UID - emission: Vec>, // Emission per UID + emission: Vec>, // Emission per UID dividends: Vec>, // Dividends per UID incentives: Vec>, // Mining incentives per UID consensus: Vec>, // Consensus per UID @@ -106,10 +106,10 @@ pub struct Metagraph { // Dividend break down. tao_dividends_per_hotkey: Vec<(AccountId, Compact)>, // List of dividend payouts in tao via root. - alpha_dividends_per_hotkey: Vec<(AccountId, Compact)>, // List of dividend payout in alpha via subnet. + alpha_dividends_per_hotkey: Vec<(AccountId, Compact)>, // List of dividend payout in alpha via subnet. } -#[freeze_struct("55ca82be1558e748")] +#[freeze_struct("c8959e499ea19040")] #[derive(Decode, Encode, PartialEq, Eq, Clone, Debug, TypeInfo)] pub struct SelectiveMetagraph { // Subnet index @@ -133,13 +133,13 @@ pub struct SelectiveMetagraph { // Subnet emission terms subnet_emission: Option>, // subnet emission via stao - alpha_in: Option>, // amount of alpha in reserve - alpha_out: Option>, // amount of alpha outstanding + alpha_in: Option>, // amount of alpha in reserve + alpha_out: Option>, // amount of alpha outstanding tao_in: Option>, // amount of tao injected per block - alpha_out_emission: Option>, // amount injected in alpha reserves per block - alpha_in_emission: Option>, // amount injected outstanding per block + alpha_out_emission: Option>, // amount injected in alpha reserves per block + alpha_in_emission: Option>, // amount injected outstanding per block tao_in_emission: Option>, // amount of tao injected per block - pending_alpha_emission: Option>, // pending alpha to be distributed + pending_alpha_emission: Option>, // pending alpha to be distributed pending_root_emission: Option>, // panding tao for root divs to be distributed subnet_volume: Option>, // volume of the subnet in TAO moving_price: Option, // subnet moving price. @@ -193,7 +193,7 @@ pub struct SelectiveMetagraph { validator_permit: Option>, // Val permit per UID pruning_score: Option>>, // Pruning per UID last_update: Option>>, // Last update per UID - emission: Option>>, // Emission per UID + emission: Option>>, // Emission per UID dividends: Option>>, // Dividends per UID incentives: Option>>, // Mining incentives per UID consensus: Option>>, // Consensus per UID @@ -206,7 +206,7 @@ pub struct SelectiveMetagraph { // Dividend break down. tao_dividends_per_hotkey: Option)>>, // List of dividend payouts in tao via root. - alpha_dividends_per_hotkey: Option)>>, // List of dividend payout in alpha via subnet. + alpha_dividends_per_hotkey: Option)>>, // List of dividend payout in alpha via subnet. // validators validators: Option>>, // List of validators @@ -633,7 +633,7 @@ impl Pallet { axons.push(Self::get_axon_info(netuid, &hotkey)); } let mut tao_dividends_per_hotkey: Vec<(T::AccountId, Compact)> = vec![]; - let mut alpha_dividends_per_hotkey: Vec<(T::AccountId, Compact)> = vec![]; + let mut alpha_dividends_per_hotkey: Vec<(T::AccountId, Compact)> = vec![]; for hotkey in hotkeys.clone() { let tao_divs = TaoDividendsPerSubnet::::get(netuid, hotkey.clone()); let alpha_divs = AlphaDividendsPerSubnet::::get(netuid, hotkey.clone()); @@ -1345,7 +1345,7 @@ impl Pallet { } } Some(SelectiveMetagraphIndex::AlphaDividendsPerHotkey) => { - let mut alpha_dividends_per_hotkey: Vec<(T::AccountId, Compact)> = vec![]; + let mut alpha_dividends_per_hotkey: Vec<(T::AccountId, Compact)> = vec![]; let n: u16 = Self::get_subnetwork_n(netuid); let mut hotkeys: Vec = vec![]; diff --git a/pallets/subtensor/src/rpc_info/neuron_info.rs b/pallets/subtensor/src/rpc_info/neuron_info.rs index 337b89212d..ff9fc3f5b4 100644 --- a/pallets/subtensor/src/rpc_info/neuron_info.rs +++ b/pallets/subtensor/src/rpc_info/neuron_info.rs @@ -2,9 +2,9 @@ use super::*; use frame_support::pallet_prelude::{Decode, Encode}; extern crate alloc; use codec::Compact; -use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::{Alpha as AlphaCurrency, NetUid}; -#[freeze_struct("3bddc0abfa5445a6")] +#[freeze_struct("9e5a291e7e71482d")] #[derive(Decode, Encode, PartialEq, Eq, Clone, Debug, TypeInfo)] pub struct NeuronInfo { hotkey: AccountId, @@ -14,9 +14,9 @@ pub struct NeuronInfo { active: bool, axon_info: AxonInfo, prometheus_info: PrometheusInfo, - stake: Vec<(AccountId, Compact)>, // map of coldkey to stake on this neuron/hotkey (includes delegations) + stake: Vec<(AccountId, Compact)>, // map of coldkey to stake on this neuron/hotkey (includes delegations) rank: Compact, - emission: Compact, + emission: Compact, incentive: Compact, consensus: Compact, trust: Compact, @@ -29,7 +29,7 @@ pub struct NeuronInfo { pruning_score: Compact, } -#[freeze_struct("e2a6a95696a82c4f")] +#[freeze_struct("b9fdff7fc6e023c7")] #[derive(Decode, Encode, PartialEq, Eq, Clone, Debug, TypeInfo)] pub struct NeuronInfoLite { hotkey: AccountId, @@ -39,9 +39,9 @@ pub struct NeuronInfoLite { active: bool, axon_info: AxonInfo, prometheus_info: PrometheusInfo, - stake: Vec<(AccountId, Compact)>, // map of coldkey to stake on this neuron/hotkey (includes delegations) + stake: Vec<(AccountId, Compact)>, // map of coldkey to stake on this neuron/hotkey (includes delegations) rank: Compact, - emission: Compact, + emission: Compact, incentive: Compact, consensus: Compact, trust: Compact, @@ -117,7 +117,7 @@ impl Pallet { } }) .collect::, Compact)>>(); - let stake: Vec<(T::AccountId, Compact)> = vec![( + let stake: Vec<(T::AccountId, Compact)> = vec![( coldkey.clone(), Self::get_stake_for_hotkey_on_subnet(&hotkey, netuid).into(), )]; @@ -182,7 +182,7 @@ impl Pallet { let last_update = Self::get_last_update_for_uid(netuid, uid); let validator_permit = Self::get_validator_permit_for_uid(netuid, uid); - let stake: Vec<(T::AccountId, Compact)> = vec![( + let stake: Vec<(T::AccountId, Compact)> = vec![( coldkey.clone(), Self::get_stake_for_hotkey_on_subnet(&hotkey, netuid).into(), )]; diff --git a/pallets/subtensor/src/rpc_info/show_subnet.rs b/pallets/subtensor/src/rpc_info/show_subnet.rs index aa5b2f4d36..cf65552e6d 100644 --- a/pallets/subtensor/src/rpc_info/show_subnet.rs +++ b/pallets/subtensor/src/rpc_info/show_subnet.rs @@ -4,9 +4,9 @@ use crate::epoch::math::*; use codec::Compact; use frame_support::pallet_prelude::{Decode, Encode}; use substrate_fixed::types::I64F64; -use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::{Alpha, NetUid}; -#[freeze_struct("11f58860434dd863")] +#[freeze_struct("d6326208b0c72fc3")] #[derive(Decode, Encode, PartialEq, Eq, Clone, Debug, TypeInfo)] pub struct SubnetState { netuid: Compact, @@ -16,7 +16,7 @@ pub struct SubnetState { validator_permit: Vec, pruning_score: Vec>, last_update: Vec>, - emission: Vec>, + emission: Vec>, dividends: Vec>, incentives: Vec>, consensus: Vec>, @@ -26,7 +26,7 @@ pub struct SubnetState { alpha_stake: Vec>, tao_stake: Vec>, total_stake: Vec>, - emission_history: Vec>>, + emission_history: Vec>>, // identities: Vec, // tao_stake: Compact, // incentive: Compact, @@ -51,12 +51,12 @@ impl Pallet { /// # Returns /// /// * `Vec>>` - A vector of vectors containing the emission history for each hotkey across all subnets. - pub fn get_emissions_history(hotkeys: Vec) -> Vec>> { - let mut result: Vec>> = vec![]; + pub fn get_emissions_history(hotkeys: Vec) -> Vec>> { + let mut result: Vec>> = vec![]; for netuid in Self::get_all_subnet_netuids() { - let mut hotkeys_emissions: Vec> = vec![]; + let mut hotkeys_emissions: Vec> = vec![]; for hotkey in hotkeys.clone() { - let last_emission: Compact = + let last_emission: Compact = LastHotkeyEmissionOnNetuid::::get(hotkey.clone(), netuid).into(); hotkeys_emissions.push(last_emission); } @@ -107,7 +107,7 @@ impl Pallet { .into_iter() .map(Compact::from) .collect(); - let emission: Vec> = Emission::::get(netuid) + let emission = Emission::::get(netuid) .into_iter() .map(Compact::from) .collect(); @@ -148,7 +148,7 @@ impl Pallet { .iter() .map(|xi| Compact::from(fixed64_to_u64(*xi))) .collect::>>(); - let emission_history: Vec>> = Self::get_emissions_history(hotkeys.clone()); + let emission_history = Self::get_emissions_history(hotkeys.clone()); Some(SubnetState { netuid: netuid.into(), hotkeys, diff --git a/pallets/subtensor/src/rpc_info/stake_info.rs b/pallets/subtensor/src/rpc_info/stake_info.rs index 5fd9f6f7b8..1e281e5ce7 100644 --- a/pallets/subtensor/src/rpc_info/stake_info.rs +++ b/pallets/subtensor/src/rpc_info/stake_info.rs @@ -2,20 +2,20 @@ extern crate alloc; use codec::Compact; use frame_support::pallet_prelude::{Decode, Encode}; -use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::{Alpha, Currency, NetUid}; use subtensor_swap_interface::SwapHandler; use super::*; -#[freeze_struct("56f5e9f33e5ec9da")] +#[freeze_struct("b8e0d5baa7dacb94")] #[derive(Decode, Encode, PartialEq, Eq, Clone, Debug, TypeInfo)] pub struct StakeInfo { hotkey: AccountId, coldkey: AccountId, netuid: Compact, - stake: Compact, + stake: Compact, locked: Compact, - emission: Compact, + emission: Compact, tao_emission: Compact, drain: Compact, is_registered: bool, @@ -36,13 +36,13 @@ impl Pallet { let mut stake_info_for_coldkey: Vec> = Vec::new(); for netuid_i in netuids.clone().iter() { for hotkey_i in staking_hotkeys.clone().iter() { - let alpha: u64 = Self::get_stake_for_hotkey_and_coldkey_on_subnet( + let alpha = Self::get_stake_for_hotkey_and_coldkey_on_subnet( hotkey_i, coldkey_i, *netuid_i, ); - if alpha == 0 { + if alpha.is_zero() { continue; } - let emission: u64 = AlphaDividendsPerSubnet::::get(*netuid_i, &hotkey_i); + let emission = AlphaDividendsPerSubnet::::get(*netuid_i, &hotkey_i); let tao_emission: u64 = TaoDividendsPerSubnet::::get(*netuid_i, &hotkey_i); let is_registered: bool = Self::is_hotkey_registered_on_network(*netuid_i, hotkey_i); @@ -95,12 +95,12 @@ impl Pallet { coldkey_account: T::AccountId, netuid: NetUid, ) -> Option> { - let alpha: u64 = Self::get_stake_for_hotkey_and_coldkey_on_subnet( + let alpha = Self::get_stake_for_hotkey_and_coldkey_on_subnet( &hotkey_account, &coldkey_account, netuid, ); - let emission: u64 = AlphaDividendsPerSubnet::::get(netuid, &hotkey_account); + let emission = AlphaDividendsPerSubnet::::get(netuid, &hotkey_account); let tao_emission: u64 = TaoDividendsPerSubnet::::get(netuid, &hotkey_account); let is_registered: bool = Self::is_hotkey_registered_on_network(netuid, &hotkey_account); diff --git a/pallets/subtensor/src/staking/helpers.rs b/pallets/subtensor/src/staking/helpers.rs index 286877b1c9..19a3644c75 100644 --- a/pallets/subtensor/src/staking/helpers.rs +++ b/pallets/subtensor/src/staking/helpers.rs @@ -72,16 +72,20 @@ impl Pallet { let alpha_stake = Self::get_stake_for_hotkey_and_coldkey_on_subnet( hotkey, coldkey, netuid, ); - T::SwapInterface::sim_swap(netuid.into(), OrderType::Sell, alpha_stake) - .map(|r| { - let fee: u64 = U96F32::saturating_from_num(r.fee_paid) - .saturating_mul(T::SwapInterface::current_alpha_price( - netuid.into(), - )) - .saturating_to_num(); - r.amount_paid_out.saturating_add(fee) - }) - .unwrap_or_default() + T::SwapInterface::sim_swap( + netuid.into(), + OrderType::Sell, + alpha_stake.into(), + ) + .map(|r| { + let fee: u64 = U96F32::saturating_from_num(r.fee_paid) + .saturating_mul(T::SwapInterface::current_alpha_price( + netuid.into(), + )) + .saturating_to_num(); + r.amount_paid_out.saturating_add(fee) + }) + .unwrap_or_default() }) .sum::() }) @@ -180,8 +184,7 @@ impl Pallet { if !Self::coldkey_owns_hotkey(coldkey, hotkey) { // If the stake is below the minimum required, it's considered a small nomination and needs to be cleared. // Log if the stake is below the minimum required - let stake: u64 = - Self::get_stake_for_hotkey_and_coldkey_on_subnet(hotkey, coldkey, netuid); + let stake = Self::get_stake_for_hotkey_and_coldkey_on_subnet(hotkey, coldkey, netuid); if stake < Self::get_nominator_min_required_stake() { // Log the clearing of a small nomination // Remove the stake from the nominator account. (this is a more forceful unstake operation which ) diff --git a/pallets/subtensor/src/staking/move_stake.rs b/pallets/subtensor/src/staking/move_stake.rs index ebacd90194..f70d07ff75 100644 --- a/pallets/subtensor/src/staking/move_stake.rs +++ b/pallets/subtensor/src/staking/move_stake.rs @@ -2,7 +2,7 @@ use super::*; use safe_math::*; use sp_core::Get; use substrate_fixed::types::U64F64; -use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::{Alpha as AlphaCurrency, Currency, NetUid}; use subtensor_swap_interface::SwapHandler; impl Pallet { @@ -33,7 +33,7 @@ impl Pallet { destination_hotkey: T::AccountId, origin_netuid: NetUid, destination_netuid: NetUid, - alpha_amount: u64, + alpha_amount: AlphaCurrency, ) -> dispatch::DispatchResult { // Check that the origin is signed by the origin_hotkey. let coldkey = ensure_signed(origin)?; @@ -127,7 +127,7 @@ impl Pallet { hotkey: T::AccountId, origin_netuid: NetUid, destination_netuid: NetUid, - alpha_amount: u64, + alpha_amount: AlphaCurrency, ) -> dispatch::DispatchResult { // Ensure the extrinsic is signed by the origin_coldkey. let coldkey = ensure_signed(origin)?; @@ -197,7 +197,7 @@ impl Pallet { hotkey: T::AccountId, origin_netuid: NetUid, destination_netuid: NetUid, - alpha_amount: u64, + alpha_amount: AlphaCurrency, ) -> dispatch::DispatchResult { // Ensure the extrinsic is signed by the coldkey. let coldkey = ensure_signed(origin)?; @@ -267,7 +267,7 @@ impl Pallet { hotkey: T::AccountId, origin_netuid: NetUid, destination_netuid: NetUid, - alpha_amount: u64, + alpha_amount: AlphaCurrency, limit_price: u64, allow_partial: bool, ) -> dispatch::DispatchResult { @@ -318,7 +318,7 @@ impl Pallet { destination_hotkey: &T::AccountId, origin_netuid: NetUid, destination_netuid: NetUid, - alpha_amount: u64, + alpha_amount: AlphaCurrency, maybe_limit_price: Option, maybe_allow_partial: Option, check_transfer_toggle: bool, @@ -407,7 +407,7 @@ impl Pallet { origin_netuid: NetUid, destination_netuid: NetUid, limit_price: u64, - ) -> Result> { + ) -> Result> { let tao: U64F64 = U64F64::saturating_from_num(1_000_000_000); // Corner case: both subnet IDs are root or stao @@ -419,7 +419,7 @@ impl Pallet { if limit_price > tao.saturating_to_num::() { return Err(Error::ZeroMaxStakeAmount); } else { - return Ok(u64::MAX); + return Ok(AlphaCurrency::MAX); } } @@ -429,14 +429,15 @@ impl Pallet { && (SubnetMechanism::::get(destination_netuid) == 1) { if limit_price == 0 { - return Ok(u64::MAX); + return Ok(AlphaCurrency::MAX); } else { // The destination price is reverted because the limit_price is origin_price / destination_price let destination_subnet_price = tao .safe_div(U64F64::saturating_from_num(limit_price)) .saturating_mul(tao) .saturating_to_num::(); - return Self::get_max_amount_add(destination_netuid, destination_subnet_price); + return Self::get_max_amount_add(destination_netuid, destination_subnet_price) + .map(Into::into); } } @@ -464,7 +465,7 @@ impl Pallet { .saturating_add(SubnetAlphaInProvided::::get(origin_netuid)); let alpha_in_2 = SubnetAlphaIn::::get(destination_netuid) .saturating_add(SubnetAlphaInProvided::::get(destination_netuid)); - if (alpha_in_1 == 0) || (alpha_in_2 == 0) { + if alpha_in_1.is_zero() || alpha_in_2.is_zero() { return Err(Error::ZeroMaxStakeAmount); } let alpha_in_1_float: U64F64 = U64F64::saturating_from_num(alpha_in_1); @@ -486,7 +487,7 @@ impl Pallet { // Corner case: limit_price is zero if limit_price == 0 { - return Ok(u64::MAX); + return Ok(AlphaCurrency::MAX); } // Main case @@ -505,7 +506,7 @@ impl Pallet { .saturating_to_num::(); if final_result != 0 { - Ok(final_result) + Ok(final_result.into()) } else { Err(Error::ZeroMaxStakeAmount) } diff --git a/pallets/subtensor/src/staking/recycle_alpha.rs b/pallets/subtensor/src/staking/recycle_alpha.rs index 5bb9f2da1c..ce26dfe2b0 100644 --- a/pallets/subtensor/src/staking/recycle_alpha.rs +++ b/pallets/subtensor/src/staking/recycle_alpha.rs @@ -1,6 +1,6 @@ use super::*; use crate::{Error, system::ensure_signed}; -use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::{Alpha as AlphaCurrency, Currency, NetUid}; impl Pallet { /// Recycles alpha from a cold/hot key pair, reducing AlphaOut on a subnet @@ -18,7 +18,7 @@ impl Pallet { pub(crate) fn do_recycle_alpha( origin: T::RuntimeOrigin, hotkey: T::AccountId, - amount: u64, + amount: AlphaCurrency, netuid: NetUid, ) -> DispatchResult { let coldkey: T::AccountId = ensure_signed(origin)?; @@ -87,7 +87,7 @@ impl Pallet { pub(crate) fn do_burn_alpha( origin: T::RuntimeOrigin, hotkey: T::AccountId, - amount: u64, + amount: AlphaCurrency, netuid: NetUid, ) -> DispatchResult { let coldkey = ensure_signed(origin)?; diff --git a/pallets/subtensor/src/staking/remove_stake.rs b/pallets/subtensor/src/staking/remove_stake.rs index 5f54a7449b..ccb7a2bab0 100644 --- a/pallets/subtensor/src/staking/remove_stake.rs +++ b/pallets/subtensor/src/staking/remove_stake.rs @@ -1,7 +1,7 @@ use subtensor_swap_interface::{OrderType, SwapHandler}; use super::*; -use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::{Alpha as AlphaCurrency, Currency, NetUid}; impl Pallet { /// ---- The implementation for the extrinsic remove_stake: Removes stake from a hotkey account and adds it onto a coldkey. @@ -16,8 +16,8 @@ impl Pallet { /// * 'netuid' (u16): /// - Subnetwork UID /// - /// * 'stake_to_be_added' (u64): - /// - The amount of stake to be added to the hotkey staking account. + /// * 'alpha_unstaked' (Alpha): + /// - The amount of stake to be removed from the staking account. /// /// # Event: /// * StakeRemoved; @@ -40,7 +40,7 @@ impl Pallet { origin: T::RuntimeOrigin, hotkey: T::AccountId, netuid: NetUid, - alpha_unstaked: u64, + alpha_unstaked: AlphaCurrency, ) -> dispatch::DispatchResult { // 1. We check the transaction is signed by the caller and retrieve the T::AccountId coldkey information. let coldkey = ensure_signed(origin)?; @@ -65,7 +65,7 @@ impl Pallet { )?; // 3. Swap the alpba to tao and update counters for this subnet. - let tao_unstaked: u64 = Self::unstake_from_subnet( + let tao_unstaked = Self::unstake_from_subnet( &hotkey, &coldkey, netuid, @@ -157,7 +157,7 @@ impl Pallet { continue; } - if alpha_unstaked > 0 { + if !alpha_unstaked.is_zero() { // Swap the alpha to tao and update counters for this subnet. let tao_unstaked: u64 = Self::unstake_from_subnet( &hotkey, @@ -249,7 +249,7 @@ impl Pallet { continue; } - if alpha_unstaked > 0 { + if !alpha_unstaked.is_zero() { // Swap the alpha to tao and update counters for this subnet. let tao_unstaked = Self::unstake_from_subnet( &hotkey, @@ -326,7 +326,7 @@ impl Pallet { origin: T::RuntimeOrigin, hotkey: T::AccountId, netuid: NetUid, - alpha_unstaked: u64, + alpha_unstaked: AlphaCurrency, limit_price: u64, allow_partial: bool, ) -> dispatch::DispatchResult { @@ -379,13 +379,16 @@ impl Pallet { } // Returns the maximum amount of RAO that can be executed with price limit - pub fn get_max_amount_remove(netuid: NetUid, limit_price: u64) -> Result> { + pub fn get_max_amount_remove( + netuid: NetUid, + limit_price: u64, + ) -> Result> { // Corner case: root and stao // There's no slippage for root or stable subnets, so if limit price is 1e9 rao or // lower, then max_amount equals u64::MAX, otherwise it is 0. if netuid.is_root() || SubnetMechanism::::get(netuid) == 0 { if limit_price <= 1_000_000_000 { - return Ok(u64::MAX); + return Ok(AlphaCurrency::MAX); } else { return Err(Error::ZeroMaxStakeAmount); } @@ -398,7 +401,7 @@ impl Pallet { .map_err(|_| Error::ZeroMaxStakeAmount)?; if result != 0 { - Ok(result) + Ok(result.into()) } else { Err(Error::ZeroMaxStakeAmount) } diff --git a/pallets/subtensor/src/staking/stake_utils.rs b/pallets/subtensor/src/staking/stake_utils.rs index cc1a1ad148..58ab1ddc61 100644 --- a/pallets/subtensor/src/staking/stake_utils.rs +++ b/pallets/subtensor/src/staking/stake_utils.rs @@ -3,7 +3,7 @@ use safe_math::*; use share_pool::{SharePool, SharePoolDataOperations}; use sp_std::ops::Neg; use substrate_fixed::types::{I64F64, I96F32, U64F64, U96F32}; -use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::{Alpha as AlphaCurrency, Currency, NetUid}; use subtensor_swap_interface::{OrderType, SwapHandler, SwapResult}; impl Pallet { @@ -17,7 +17,7 @@ impl Pallet { /// /// # Returns /// * `u64` - The total alpha issuance for the specified subnet. - pub fn get_alpha_issuance(netuid: NetUid) -> u64 { + pub fn get_alpha_issuance(netuid: NetUid) -> AlphaCurrency { SubnetAlphaIn::::get(netuid).saturating_add(SubnetAlphaOut::::get(netuid)) } @@ -322,7 +322,10 @@ impl Pallet { finalized_tao.saturating_to_num::() } - pub fn get_inherited_for_hotkey_on_subnet(hotkey: &T::AccountId, netuid: NetUid) -> u64 { + pub fn get_inherited_for_hotkey_on_subnet( + hotkey: &T::AccountId, + netuid: NetUid, + ) -> AlphaCurrency { // Step 1: Retrieve the initial total stake (alpha) for the hotkey on the specified subnet. let initial_alpha: U96F32 = U96F32::saturating_from_num(Self::get_stake_for_hotkey_on_subnet(hotkey, netuid)); @@ -333,7 +336,7 @@ impl Pallet { initial_alpha ); if netuid.is_root() { - return initial_alpha.saturating_to_num::(); + return initial_alpha.saturating_to_num::().into(); } // Initialize variables to track alpha allocated to children and inherited from parents. @@ -424,7 +427,7 @@ impl Pallet { ); // Step 6: Return the final inherited alpha value. - finalized_alpha.saturating_to_num::() + finalized_alpha.saturating_to_num::().into() } /// Checks if a specific hotkey-coldkey pair has enough stake on a subnet to fulfill a given decrement. @@ -448,7 +451,7 @@ impl Pallet { hotkey: &T::AccountId, coldkey: &T::AccountId, netuid: NetUid, - decrement: u64, + decrement: AlphaCurrency, ) -> bool { // Retrieve the current stake for this hotkey-coldkey pair on the subnet let current_stake = @@ -480,9 +483,9 @@ impl Pallet { hotkey: &T::AccountId, coldkey: &T::AccountId, netuid: NetUid, - ) -> u64 { + ) -> AlphaCurrency { let alpha_share_pool = Self::get_alpha_share_pool(hotkey.clone(), netuid); - alpha_share_pool.try_get_value(coldkey).unwrap_or(0) + alpha_share_pool.try_get_value(coldkey).unwrap_or(0).into() } /// Retrieves the total stake (alpha) for a given hotkey on a specific subnet. @@ -499,7 +502,7 @@ impl Pallet { /// /// # Note /// This function returns the cumulative stake across all coldkeys associated with this hotkey on the subnet. - pub fn get_stake_for_hotkey_on_subnet(hotkey: &T::AccountId, netuid: NetUid) -> u64 { + pub fn get_stake_for_hotkey_on_subnet(hotkey: &T::AccountId, netuid: NetUid) -> AlphaCurrency { // Retrieve and return the total alpha this hotkey owns on this subnet. // This value represents the sum of stakes from all coldkeys associated with this hotkey. TotalHotkeyAlpha::::get(hotkey, netuid) @@ -514,9 +517,13 @@ impl Pallet { /// * `netuid` - The unique identifier of the subnet. /// * `amount` - The amount of alpha to be added. /// - pub fn increase_stake_for_hotkey_on_subnet(hotkey: &T::AccountId, netuid: NetUid, amount: u64) { + pub fn increase_stake_for_hotkey_on_subnet( + hotkey: &T::AccountId, + netuid: NetUid, + amount: AlphaCurrency, + ) { let mut alpha_share_pool = Self::get_alpha_share_pool(hotkey.clone(), netuid); - alpha_share_pool.update_value_for_all(amount as i64); + alpha_share_pool.update_value_for_all(amount.to_u64() as i64); } /// Decrease hotkey stake on a subnet. @@ -547,9 +554,9 @@ impl Pallet { hotkey: &T::AccountId, coldkey: &T::AccountId, netuid: NetUid, - amount: u64, - ) -> u64 { - if amount > 0 { + amount: AlphaCurrency, + ) -> AlphaCurrency { + if !amount.is_zero() { let mut staking_hotkeys = StakingHotkeys::::get(coldkey); if !staking_hotkeys.contains(hotkey) { staking_hotkeys.push(hotkey.clone()); @@ -559,20 +566,22 @@ impl Pallet { let mut alpha_share_pool = Self::get_alpha_share_pool(hotkey.clone(), netuid); // We expect to add a positive amount here. - let actual_alpha = alpha_share_pool.update_value_for_one(coldkey, amount as i64); + let amount = amount.to_u64() as i64; + let actual_alpha = alpha_share_pool.update_value_for_one(coldkey, amount); // We should return a positive amount, or 0 if the operation failed. // e.g. the stake was removed due to precision issues. - actual_alpha.max(0).unsigned_abs() + actual_alpha.max(0).unsigned_abs().into() } pub fn try_increase_stake_for_hotkey_and_coldkey_on_subnet( hotkey: &T::AccountId, netuid: NetUid, - amount: u64, + amount: AlphaCurrency, ) -> bool { let mut alpha_share_pool = Self::get_alpha_share_pool(hotkey.clone(), netuid); - alpha_share_pool.sim_update_value_for_one(amount as i64) + let amount = amount.to_u64() as i64; + alpha_share_pool.sim_update_value_for_one(amount) } /// Sell shares in the hotkey on a given subnet @@ -589,9 +598,10 @@ impl Pallet { hotkey: &T::AccountId, coldkey: &T::AccountId, netuid: NetUid, - amount: u64, - ) -> u64 { + amount: AlphaCurrency, + ) -> AlphaCurrency { let mut alpha_share_pool = Self::get_alpha_share_pool(hotkey.clone(), netuid); + let amount = amount.to_u64(); // We expect a negative value here let mut actual_alpha = 0; @@ -605,7 +615,7 @@ impl Pallet { // Get the negation of the removed alpha, and clamp at 0. // This ensures we return a positive value, but only if // `actual_alpha` was negative (i.e. a decrease in stake). - actual_alpha.neg().max(0).unsigned_abs() + actual_alpha.neg().max(0).unsigned_abs().into() } /// Swaps TAO for the alpha token on the subnet. @@ -621,20 +631,14 @@ impl Pallet { if mechanism_id == 1 { let swap_result = T::SwapInterface::swap(netuid.into(), OrderType::Buy, tao, price_limit, false)?; + let alpha_decrease = AlphaCurrency::from(swap_result.alpha_reserve_delta.abs() as u64); // Decrease Alpha reserves. - Self::decrease_provided_alpha_reserve( - netuid.into(), - swap_result - .alpha_reserve_delta - .abs() - .try_into() - .unwrap_or(0), - ); + Self::decrease_provided_alpha_reserve(netuid.into(), alpha_decrease); // Increase Alpha outstanding. SubnetAlphaOut::::mutate(netuid, |total| { - *total = total.saturating_add(swap_result.amount_paid_out); + *total = total.saturating_add(swap_result.amount_paid_out.into()); }); // Increase only the protocol TAO reserve. We only use the sum of @@ -671,21 +675,26 @@ impl Pallet { /// Updates TaoIn, AlphaIn, and AlphaOut pub fn swap_alpha_for_tao( netuid: NetUid, - alpha: u64, + alpha: AlphaCurrency, price_limit: u64, ) -> Result { // Step 1: Get the mechanism type for the subnet (0 for Stable, 1 for Dynamic) let mechanism_id: u16 = SubnetMechanism::::get(netuid); // Step 2: Swap alpha and attain tao if mechanism_id == 1 { - let swap_result = - T::SwapInterface::swap(netuid.into(), OrderType::Sell, alpha, price_limit, false)?; + let swap_result = T::SwapInterface::swap( + netuid.into(), + OrderType::Sell, + alpha.into(), + price_limit, + false, + )?; // Increase only the protocol Alpha reserve. We only use the sum of // (SubnetAlphaIn + SubnetAlphaInProvided) in alpha_reserve(), so it is irrelevant // which one to increase. SubnetAlphaIn::::mutate(netuid, |total| { - *total = total.saturating_add(swap_result.alpha_reserve_delta as u64); + *total = total.saturating_add((swap_result.alpha_reserve_delta as u64).into()); }); // Decrease Alpha outstanding. @@ -715,8 +724,8 @@ impl Pallet { } else { // Step 3.b.1: Stable mechanism, just return the value 1:1 Ok(SwapResult { - amount_paid_in: alpha, - amount_paid_out: alpha, + amount_paid_in: alpha.into(), + amount_paid_out: alpha.into(), fee_paid: 0, tao_reserve_delta: 0, alpha_reserve_delta: 0, @@ -731,7 +740,7 @@ impl Pallet { hotkey: &T::AccountId, coldkey: &T::AccountId, netuid: NetUid, - alpha: u64, + alpha: AlphaCurrency, price_limit: u64, ) -> Result { // Decrease alpha on subneet @@ -745,9 +754,10 @@ impl Pallet { let refund = actual_alpha_decrease.saturating_sub( swap_result .amount_paid_in - .saturating_add(swap_result.fee_paid), + .saturating_add(swap_result.fee_paid) + .into(), ); - if refund > 0 { + if !refund.is_zero() { Self::increase_stake_for_hotkey_and_coldkey_on_subnet(hotkey, coldkey, netuid, refund); } @@ -793,7 +803,7 @@ impl Pallet { netuid: NetUid, tao: u64, price_limit: u64, - ) -> Result { + ) -> Result { // Swap the tao to alpha. let swap_result = Self::swap_tao_for_alpha(netuid, tao, price_limit)?; @@ -803,7 +813,7 @@ impl Pallet { Self::try_increase_stake_for_hotkey_and_coldkey_on_subnet( hotkey, netuid, - swap_result.amount_paid_out, + swap_result.amount_paid_out.into(), ), Error::::InsufficientLiquidity ); @@ -813,11 +823,12 @@ impl Pallet { hotkey, coldkey, netuid, - swap_result.amount_paid_out, - ) == 0 + swap_result.amount_paid_out.into(), + ) + .is_zero() || swap_result.amount_paid_out == 0 { - return Ok(0); + return Ok(AlphaCurrency::ZERO); } // Step 4: Update the list of hotkeys staking for this coldkey @@ -849,7 +860,7 @@ impl Pallet { swap_result.fee_paid, ); - Ok(swap_result.amount_paid_out) + Ok(swap_result.amount_paid_out.into()) } pub fn get_alpha_share_pool( @@ -921,7 +932,7 @@ impl Pallet { let try_stake_result = Self::try_increase_stake_for_hotkey_and_coldkey_on_subnet( hotkey, netuid, - expected_alpha.amount_paid_out, + expected_alpha.amount_paid_out.into(), ); ensure!(try_stake_result, Error::::InsufficientLiquidity); @@ -934,8 +945,8 @@ impl Pallet { coldkey: &T::AccountId, hotkey: &T::AccountId, netuid: NetUid, - alpha_unstaked: u64, - max_amount: u64, + alpha_unstaked: AlphaCurrency, + max_amount: AlphaCurrency, allow_partial: bool, ) -> Result<(), Error> { // Ensure that the subnet exists. @@ -945,7 +956,7 @@ impl Pallet { // Self::ensure_subtoken_enabled(netuid)?; // Ensure that the stake amount to be removed is above the minimum in tao equivalent. - match T::SwapInterface::sim_swap(netuid.into(), OrderType::Sell, alpha_unstaked) { + match T::SwapInterface::sim_swap(netuid.into(), OrderType::Sell, alpha_unstaked.into()) { Ok(res) => ensure!( res.amount_paid_out > DefaultMinStake::::get(), Error::::AmountTooLow @@ -1020,8 +1031,8 @@ impl Pallet { destination_hotkey: &T::AccountId, origin_netuid: NetUid, destination_netuid: NetUid, - alpha_amount: u64, - max_amount: u64, + alpha_amount: AlphaCurrency, + max_amount: AlphaCurrency, maybe_allow_partial: Option, check_transfer_toggle: bool, ) -> Result<(), Error> { @@ -1077,7 +1088,7 @@ impl Pallet { // Ensure that the stake amount to be removed is above the minimum in tao equivalent. let tao_equivalent = - T::SwapInterface::sim_swap(origin_netuid.into(), OrderType::Sell, alpha_amount) + T::SwapInterface::sim_swap(origin_netuid.into(), OrderType::Sell, alpha_amount.into()) .map(|res| res.amount_paid_out) .map_err(|_| Error::::InsufficientLiquidity)?; ensure!( @@ -1128,22 +1139,22 @@ impl Pallet { } } - pub fn increase_provided_alpha_reserve(netuid: NetUid, alpha: u64) { + pub fn increase_provided_alpha_reserve(netuid: NetUid, alpha: AlphaCurrency) { SubnetAlphaInProvided::::mutate(netuid, |total| { *total = total.saturating_add(alpha); }); } - pub fn decrease_provided_alpha_reserve(netuid: NetUid, alpha: u64) { + pub fn decrease_provided_alpha_reserve(netuid: NetUid, alpha: AlphaCurrency) { // First, decrease SubnetAlphaInProvided, then deduct the rest from SubnetAlphaIn let subnet_alpha = SubnetAlphaIn::::get(netuid); let subnet_alpha_provided = SubnetAlphaInProvided::::get(netuid); let remainder = subnet_alpha_provided.saturating_sub(alpha); let carry_over = alpha.saturating_sub(subnet_alpha_provided); - if carry_over == 0 { + if carry_over.is_zero() { SubnetAlphaInProvided::::set(netuid, remainder); } else { - SubnetAlphaInProvided::::set(netuid, 0_u64); + SubnetAlphaInProvided::::set(netuid, AlphaCurrency::from(0)); SubnetAlphaIn::::set(netuid, subnet_alpha.saturating_sub(carry_over)); } } @@ -1196,7 +1207,7 @@ impl SharePoolDataOperations> crate::TotalHotkeyAlpha::::insert( &(self.hotkey), self.netuid, - value.saturating_to_num::(), + AlphaCurrency::from(value.saturating_to_num::()), ); } else { crate::TotalHotkeyAlpha::::remove(&(self.hotkey), self.netuid); diff --git a/pallets/subtensor/src/subnets/registration.rs b/pallets/subtensor/src/subnets/registration.rs index a2eb180af1..d999c299e5 100644 --- a/pallets/subtensor/src/subnets/registration.rs +++ b/pallets/subtensor/src/subnets/registration.rs @@ -2,7 +2,7 @@ use super::*; use sp_core::{H256, U256}; use sp_io::hashing::{keccak_256, sha2_256}; use sp_runtime::Saturating; -use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::{Currency, NetUid}; use subtensor_swap_interface::SwapHandler; use system::pallet_prelude::BlockNumberFor; @@ -141,10 +141,12 @@ impl Pallet { Self::remove_balance_from_coldkey_account(&coldkey, registration_cost)?; // Tokens are swapped and then burned. - let burned_alpha: u64 = + let burned_alpha = Self::swap_tao_for_alpha(netuid, actual_burn_amount, T::SwapInterface::max_price())? .amount_paid_out; - SubnetAlphaOut::::mutate(netuid, |total| *total = total.saturating_sub(burned_alpha)); + SubnetAlphaOut::::mutate(netuid, |total| { + *total = total.saturating_sub(burned_alpha.into()) + }); // Actually perform the registration. let neuron_uid: u16 = Self::register_neuron(netuid, &hotkey); diff --git a/pallets/subtensor/src/subnets/subnet.rs b/pallets/subtensor/src/subnets/subnet.rs index db3e319959..6996baf791 100644 --- a/pallets/subtensor/src/subnets/subnet.rs +++ b/pallets/subtensor/src/subnets/subnet.rs @@ -194,10 +194,11 @@ impl Pallet { // Put initial TAO from lock into subnet TAO and produce numerically equal amount of Alpha // The initial TAO is the locked amount, with a minimum of 1 RAO and a cap of 100 TAO. let pool_initial_tao = Self::get_network_min_lock(); + let pool_initial_alpha = AlphaCurrency::from(Self::get_network_min_lock()); let actual_tao_lock_amount_less_pool_tao = actual_tao_lock_amount.saturating_sub(pool_initial_tao); SubnetTAO::::insert(netuid_to_register, pool_initial_tao); - SubnetAlphaIn::::insert(netuid_to_register, pool_initial_tao); + SubnetAlphaIn::::insert(netuid_to_register, pool_initial_alpha); SubnetOwner::::insert(netuid_to_register, coldkey.clone()); SubnetOwnerHotkey::::insert(netuid_to_register, hotkey.clone()); diff --git a/pallets/subtensor/src/subnets/uids.rs b/pallets/subtensor/src/subnets/uids.rs index fa25b0b9ca..5c88722cdf 100644 --- a/pallets/subtensor/src/subnets/uids.rs +++ b/pallets/subtensor/src/subnets/uids.rs @@ -19,7 +19,7 @@ impl Pallet { /// Resets the trust, emission, consensus, incentive, dividends of the neuron to default pub fn clear_neuron(netuid: NetUid, neuron_uid: u16) { let neuron_index: usize = neuron_uid.into(); - Emission::::mutate(netuid, |v| Self::set_element_at(v, neuron_index, 0)); + Emission::::mutate(netuid, |v| Self::set_element_at(v, neuron_index, 0.into())); Trust::::mutate(netuid, |v| Self::set_element_at(v, neuron_index, 0)); Consensus::::mutate(netuid, |v| Self::set_element_at(v, neuron_index, 0)); Incentive::::mutate(netuid, |v| Self::set_element_at(v, neuron_index, 0)); @@ -100,7 +100,7 @@ impl Pallet { Rank::::mutate(netuid, |v| v.push(0)); Trust::::mutate(netuid, |v| v.push(0)); Active::::mutate(netuid, |v| v.push(true)); - Emission::::mutate(netuid, |v| v.push(0)); + Emission::::mutate(netuid, |v| v.push(0.into())); Consensus::::mutate(netuid, |v| v.push(0)); Incentive::::mutate(netuid, |v| v.push(0)); Dividends::::mutate(netuid, |v| v.push(0)); @@ -150,11 +150,11 @@ impl Pallet { /// Returns the stake of the uid on network or 0 if it doesnt exist. /// - pub fn get_stake_for_uid_and_subnetwork(netuid: NetUid, neuron_uid: u16) -> u64 { + pub fn get_stake_for_uid_and_subnetwork(netuid: NetUid, neuron_uid: u16) -> AlphaCurrency { if let Ok(hotkey) = Self::get_hotkey_for_net_and_uid(netuid, neuron_uid) { Self::get_stake_for_hotkey_on_subnet(&hotkey, netuid) } else { - 0 + 0.into() } } diff --git a/pallets/subtensor/src/swap/swap_hotkey.rs b/pallets/subtensor/src/swap/swap_hotkey.rs index 9cb79a1002..1b6274db54 100644 --- a/pallets/subtensor/src/swap/swap_hotkey.rs +++ b/pallets/subtensor/src/swap/swap_hotkey.rs @@ -2,6 +2,8 @@ use super::*; use frame_support::weights::Weight; use sp_core::Get; use substrate_fixed::types::U64F64; +use subtensor_runtime_common::{Currency, NetUid}; + impl Pallet { /// Swaps the hotkey of a coldkey account. /// diff --git a/pallets/subtensor/src/tests/children.rs b/pallets/subtensor/src/tests/children.rs index f323bbdf0a..5c0c2e9c27 100644 --- a/pallets/subtensor/src/tests/children.rs +++ b/pallets/subtensor/src/tests/children.rs @@ -6,6 +6,7 @@ use super::mock::*; use approx::assert_abs_diff_eq; use frame_support::{assert_err, assert_noop, assert_ok}; use substrate_fixed::types::{I64F64, I96F32, U96F32}; +use subtensor_runtime_common::Alpha as AlphaCurrency; use subtensor_swap_interface::SwapHandler; use crate::{utils::rate_limiting::TransactionType, *}; @@ -385,29 +386,41 @@ fn test_get_stake_for_hotkey_on_subnet() { mock_set_children(&coldkey1, &parent, netuid, &[(u64::MAX, child)]); // Stake 1000 to parent from coldkey1 SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &parent, &coldkey1, netuid, 1000, + &parent, + &coldkey1, + netuid, + 1000.into(), ); // Stake 1000 to parent from coldkey2 SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &parent, &coldkey2, netuid, 1000, + &parent, + &coldkey2, + netuid, + 1000.into(), ); // Stake 1000 to child from coldkey1 SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &child, &coldkey1, netuid, 1000, + &child, + &coldkey1, + netuid, + 1000.into(), ); // Stake 1000 to child from coldkey2 SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &child, &coldkey2, netuid, 1000, + &child, + &coldkey2, + netuid, + 1000.into(), ); let parent_stake = SubtensorModule::get_inherited_for_hotkey_on_subnet(&parent, netuid); let child_stake = SubtensorModule::get_inherited_for_hotkey_on_subnet(&child, netuid); // The parent should have 0 stake as it's all allocated to the child - assert_eq!(parent_stake, 0); + assert_eq!(parent_stake, 0.into()); // The child should have its original stake (2000) plus the parent's stake (2000) - assert_eq!(child_stake, 4000); + assert_eq!(child_stake, 4000.into()); // Ensure total stake is preserved - assert_eq!(parent_stake + child_stake, 4000); + assert_eq!(parent_stake + child_stake, 4000.into()); }); } @@ -1463,7 +1476,7 @@ fn test_children_stake_values() { &hotkey, &coldkey, netuid, - 100_000_000_000_000, + 100_000_000_000_000.into(), ); // Set multiple children with proportions. @@ -1479,26 +1492,26 @@ fn test_children_stake_values() { assert_eq!( SubtensorModule::get_inherited_for_hotkey_on_subnet(&hotkey, netuid), - 25_000_000_069_849 + 25_000_000_069_849.into() ); assert_eq!( SubtensorModule::get_inherited_for_hotkey_on_subnet(&child1, netuid), - 24_999_999_976_716 + 24_999_999_976_716.into() ); assert_eq!( SubtensorModule::get_inherited_for_hotkey_on_subnet(&child2, netuid), - 24_999_999_976_716 + 24_999_999_976_716.into() ); assert_eq!( SubtensorModule::get_inherited_for_hotkey_on_subnet(&child3, netuid), - 24_999_999_976_716 + 24_999_999_976_716.into() ); assert_eq!( SubtensorModule::get_inherited_for_hotkey_on_subnet(&child3, netuid) + SubtensorModule::get_inherited_for_hotkey_on_subnet(&child2, netuid) + SubtensorModule::get_inherited_for_hotkey_on_subnet(&child1, netuid) + SubtensorModule::get_inherited_for_hotkey_on_subnet(&hotkey, netuid), - 99999999999997 + 99999999999997.into() ); }); } @@ -1665,11 +1678,14 @@ fn test_get_stake_for_hotkey_on_subnet_basic() { add_network(netuid, 1, 0); register_ok_neuron(netuid, hotkey, coldkey, 0); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &hotkey, &coldkey, netuid, 1000, + &hotkey, + &coldkey, + netuid, + 1000.into(), ); assert_eq!( SubtensorModule::get_inherited_for_hotkey_on_subnet(&hotkey, netuid), - 1000 + 1000.into() ); }); } @@ -1692,15 +1708,21 @@ fn test_get_stake_for_hotkey_on_subnet_multiple_coldkeys() { register_ok_neuron(netuid, hotkey, coldkey1, 0); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &hotkey, &coldkey1, netuid, 1000, + &hotkey, + &coldkey1, + netuid, + 1000.into(), ); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &hotkey, &coldkey2, netuid, 2000, + &hotkey, + &coldkey2, + netuid, + 2000.into(), ); assert_eq!( SubtensorModule::get_inherited_for_hotkey_on_subnet(&hotkey, netuid), - 3000 + 3000.into() ); }); } @@ -1729,18 +1751,18 @@ fn test_get_stake_for_hotkey_on_subnet_single_parent_child() { &parent, &coldkey, netuid, - 1_000_000_000, + 1_000_000_000.into(), ); mock_set_children_no_epochs(netuid, &parent, &[(u64::MAX, child)]); assert_eq!( SubtensorModule::get_inherited_for_hotkey_on_subnet(&parent, netuid), - 0 + 0.into() ); assert_eq!( SubtensorModule::get_inherited_for_hotkey_on_subnet(&child, netuid), - 1_000_000_000 + 1_000_000_000.into() ); }); } @@ -1770,29 +1792,35 @@ fn test_get_stake_for_hotkey_on_subnet_multiple_parents_single_child() { register_ok_neuron(netuid, child, coldkey, 0); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &parent1, &coldkey, netuid, 1000, + &parent1, + &coldkey, + netuid, + 1000.into(), ); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &parent2, &coldkey, netuid, 2000, + &parent2, + &coldkey, + netuid, + 2000.into(), ); mock_set_children_no_epochs(netuid, &parent1, &[(u64::MAX / 2, child)]); mock_set_children_no_epochs(netuid, &parent2, &[(u64::MAX / 2, child)]); close( - SubtensorModule::get_inherited_for_hotkey_on_subnet(&parent1, netuid), + SubtensorModule::get_inherited_for_hotkey_on_subnet(&parent1, netuid).into(), 500, 10, "Incorrect inherited stake for parent1", ); close( - SubtensorModule::get_inherited_for_hotkey_on_subnet(&parent2, netuid), + SubtensorModule::get_inherited_for_hotkey_on_subnet(&parent2, netuid).into(), 1000, 10, "Incorrect inherited stake for parent2", ); close( - SubtensorModule::get_inherited_for_hotkey_on_subnet(&child, netuid), + SubtensorModule::get_inherited_for_hotkey_on_subnet(&child, netuid).into(), 1499, 10, "Incorrect inherited stake for child", @@ -1824,7 +1852,7 @@ fn test_get_stake_for_hotkey_on_subnet_single_parent_multiple_children() { register_ok_neuron(netuid, child1, coldkey, 0); register_ok_neuron(netuid, child2, coldkey, 0); - let total_stake = 3000; + let total_stake = 3000.into(); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &parent, &coldkey, @@ -1844,18 +1872,18 @@ fn test_get_stake_for_hotkey_on_subnet_single_parent_multiple_children() { // Check that the total stake is preserved close( - parent_stake + child1_stake + child2_stake, - total_stake, + (parent_stake + child1_stake + child2_stake).into(), + total_stake.into(), 10, "Total stake not preserved", ); // Check that the parent stake is slightly higher due to rounding - close(parent_stake, 1000, 10, "Parent stake incorrect"); + close(parent_stake.into(), 1000, 10, "Parent stake incorrect"); // Check that each child gets an equal share of the remaining stake - close(child1_stake, 1000, 10, "Child1 stake incorrect"); - close(child2_stake, 1000, 10, "Child2 stake incorrect"); + close(child1_stake.into(), 1000, 10, "Child1 stake incorrect"); + close(child2_stake.into(), 1000, 10, "Child2 stake incorrect"); // Log the actual stake values log::info!("Parent stake: {}", parent_stake); @@ -1889,7 +1917,7 @@ fn test_get_stake_for_hotkey_on_subnet_edge_cases() { register_ok_neuron(netuid, child2, coldkey, 0); // Set above old value of network max stake - let network_max_stake: u64 = 600_000_000_000_000; + let network_max_stake = 600_000_000_000_000.into(); // Increase stake to the network max SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( @@ -1910,8 +1938,8 @@ fn test_get_stake_for_hotkey_on_subnet_edge_cases() { log::info!("Child1 stake: {}", child1_stake); log::info!("Child2 stake: {}", child2_stake); - assert_eq!(parent_stake, 0, "Parent should have 0 stake"); - assert_eq!(child1_stake, 0, "Child1 should have 0 stake"); + assert_eq!(parent_stake, 0.into(), "Parent should have 0 stake"); + assert_eq!(child1_stake, 0.into(), "Child1 should have 0 stake"); assert_eq!( child2_stake, network_max_stake, "Child2 should have all the stake" @@ -1919,8 +1947,8 @@ fn test_get_stake_for_hotkey_on_subnet_edge_cases() { // Check that the total stake is preserved and equal to the network max stake close( - parent_stake + child1_stake + child2_stake, - network_max_stake, + (parent_stake + child1_stake + child2_stake).into(), + network_max_stake.into(), 10, "Total stake should equal network max stake", ); @@ -1959,7 +1987,7 @@ fn test_get_stake_for_hotkey_on_subnet_complex_hierarchy() { register_ok_neuron(netuid, child2, coldkey_child2, 0); register_ok_neuron(netuid, grandchild, coldkey_grandchild, 0); - let total_stake = 1000; + let total_stake = 1000.into(); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &parent, &coldkey_parent, @@ -2015,11 +2043,22 @@ fn test_get_stake_for_hotkey_on_subnet_complex_hierarchy() { log::info!("Child2 stake: {}", child2_stake_1); assert_eq!( - parent_stake_1, 0, + parent_stake_1, + 0.into(), "Parent should have 0 stake after distributing all stake to children" ); - close(child1_stake_1, 499, 10, "Child1 should have 499 stake"); - close(child2_stake_1, 499, 10, "Child2 should have 499 stake"); + close( + child1_stake_1.into(), + 499, + 10, + "Child1 should have 499 stake", + ); + close( + child2_stake_1.into(), + 499, + 10, + "Child2 should have 499 stake", + ); // Step 2: Set children for child1 mock_set_children_no_epochs(netuid, &child1, &[(u64::MAX, grandchild)]); @@ -2045,21 +2084,21 @@ fn test_get_stake_for_hotkey_on_subnet_complex_hierarchy() { log::info!("Child2 stake: {}", child2_stake_2); log::info!("Grandchild stake: {}", grandchild_stake); - close(parent_stake_2, 0, 10, "Parent stake should remain 2"); + close(parent_stake_2.into(), 0, 10, "Parent stake should remain 2"); close( - child1_stake_2, + child1_stake_2.into(), 499, 10, "Child1 should still have 499 stake", ); close( - child2_stake_2, + child2_stake_2.into(), 499, 10, "Child2 should still have 499 stake", ); close( - grandchild_stake, + grandchild_stake.into(), 0, 10, "Grandchild should have 0 stake, as child1 doesn't have any owned stake", @@ -2067,8 +2106,8 @@ fn test_get_stake_for_hotkey_on_subnet_complex_hierarchy() { // Check that the total stake is preserved close( - parent_stake_2 + child1_stake_2 + child2_stake_2 + grandchild_stake, - total_stake, + (parent_stake_2 + child1_stake_2 + child2_stake_2 + grandchild_stake).into(), + total_stake.into(), 10, "Total stake should equal the initial stake", ); @@ -2146,17 +2185,20 @@ fn test_get_stake_for_hotkey_on_subnet_multiple_networks() { register_ok_neuron(netuid2, hotkey, coldkey, 0); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &hotkey, &coldkey, netuid1, 1000, + &hotkey, + &coldkey, + netuid1, + 1000.into(), ); close( - SubtensorModule::get_inherited_for_hotkey_on_subnet(&hotkey, netuid1), + SubtensorModule::get_inherited_for_hotkey_on_subnet(&hotkey, netuid1).into(), 1000, 10, "Stake on network 1 incorrect", ); close( - SubtensorModule::get_inherited_for_hotkey_on_subnet(&hotkey, netuid2), + SubtensorModule::get_inherited_for_hotkey_on_subnet(&hotkey, netuid2).into(), 0, 10, "Stake on network 2 incorrect", @@ -2216,7 +2258,7 @@ fn test_do_remove_stake_clears_pending_childkeys() { SubtensorModule::add_balance_to_coldkey_account(&coldkey, 10_000_000_000_000); let reserve = 1_000_000_000_000_000; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); // Set non-default value for childkey stake threshold StakeThreshold::::set(1_000_000_000_000); @@ -2225,7 +2267,7 @@ fn test_do_remove_stake_clears_pending_childkeys() { RuntimeOrigin::signed(coldkey), hotkey, netuid, - StakeThreshold::::get() * 2 + (StakeThreshold::::get() * 2).into() )); let alpha = @@ -2292,7 +2334,7 @@ fn test_do_set_child_cooldown_period() { &parent, &coldkey, netuid, - StakeThreshold::::get(), + StakeThreshold::::get().into(), ); // Schedule parent-child relationship @@ -2317,7 +2359,7 @@ fn test_do_set_child_cooldown_period() { &parent, &coldkey, netuid, - StakeThreshold::::get(), + StakeThreshold::::get().into(), ); // Verify child assignment @@ -2365,7 +2407,7 @@ fn test_do_set_pending_children_runs_in_epoch() { &parent, &coldkey, netuid, - StakeThreshold::::get(), + StakeThreshold::::get().into(), ); // Schedule parent-child relationship @@ -2427,8 +2469,8 @@ fn test_revoke_child_no_min_stake_check() { register_ok_neuron(netuid, parent, coldkey, 0); let reserve = 1_000_000_000_000_000; - mock::setup_reserves(netuid, reserve, reserve); - mock::setup_reserves(NetUid::ROOT, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(NetUid::ROOT, reserve, reserve.into()); // Set minimum stake for setting children StakeThreshold::::put(1_000_000_000_000); @@ -2438,7 +2480,7 @@ fn test_revoke_child_no_min_stake_check() { &parent, &coldkey, NetUid::ROOT, - StakeThreshold::::get() + fee, + (StakeThreshold::::get() + fee).into(), ); // Schedule parent-child relationship @@ -2458,7 +2500,7 @@ fn test_revoke_child_no_min_stake_check() { &parent, &coldkey, NetUid::ROOT, - StakeThreshold::::get() + fee, + (StakeThreshold::::get() + fee).into(), ); // Ensure the childkeys are applied @@ -2505,7 +2547,7 @@ fn test_do_set_child_registration_disabled() { register_ok_neuron(netuid, parent, coldkey, 0); let reserve = 1_000_000_000_000_000; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); // Set minimum stake for setting children StakeThreshold::::put(1_000_000_000_000); @@ -2514,7 +2556,7 @@ fn test_do_set_child_registration_disabled() { &parent, &coldkey, netuid, - StakeThreshold::::get() + fee, + (StakeThreshold::::get() + fee).into(), ); // Disable subnet registrations @@ -2533,7 +2575,7 @@ fn test_do_set_child_registration_disabled() { &parent, &coldkey, netuid, - StakeThreshold::::get() + fee, + (StakeThreshold::::get() + fee).into(), ); // Ensure the childkeys are applied @@ -2643,13 +2685,13 @@ fn test_childkey_set_weights_single_parent() { &parent, &coldkey_parent, netuid, - stake_to_give_child, + stake_to_give_child.into(), ); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &weight_setter, &coldkey_weight_setter, netuid, - 1_000_000, + 1_000_000.into(), ); SubtensorModule::set_weights_set_rate_limit(netuid, 0); @@ -2744,7 +2786,7 @@ fn test_set_weights_no_parent() { &hotkey, &coldkey, netuid, - stake_to_give_child, + stake_to_give_child.into(), ); SubtensorModule::set_weights_set_rate_limit(netuid, 0); @@ -2840,7 +2882,7 @@ fn test_childkey_take_drain() { // Add network, register hotkeys, and setup network parameters add_network(netuid, subnet_tempo, 0); - mock::setup_reserves(netuid, stake * 10_000, stake * 10_000); + mock::setup_reserves(netuid, stake * 10_000, (stake * 10_000).into()); register_ok_neuron(netuid, child_hotkey, child_coldkey, 0); register_ok_neuron(netuid, parent_hotkey, parent_coldkey, 1); register_ok_neuron(netuid, miner_hotkey, miner_coldkey, 1); @@ -2955,7 +2997,7 @@ fn test_parent_child_chain_emission() { // Setup large LPs to prevent slippage SubnetTAO::::insert(netuid, 1_000_000_000_000_000); - SubnetAlphaIn::::insert(netuid, 1_000_000_000_000_000); + SubnetAlphaIn::::insert(netuid, AlphaCurrency::from(1_000_000_000_000_000)); // Set owner cut to 0 SubtensorModule::set_subnet_owner_cut(0_u16); @@ -2999,19 +3041,25 @@ fn test_parent_child_chain_emission() { &hotkey_a, &coldkey_a, netuid, - (total_alpha * I96F32::from_num(stake_a) / total_tao).saturating_to_num::(), + (total_alpha * I96F32::from_num(stake_a) / total_tao) + .saturating_to_num::() + .into(), ); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &hotkey_b, &coldkey_b, netuid, - (total_alpha * I96F32::from_num(stake_b) / total_tao).saturating_to_num::(), + (total_alpha * I96F32::from_num(stake_b) / total_tao) + .saturating_to_num::() + .into(), ); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &hotkey_c, &coldkey_c, netuid, - (total_alpha * I96F32::from_num(stake_c) / total_tao).saturating_to_num::(), + (total_alpha * I96F32::from_num(stake_c) / total_tao) + .saturating_to_num::() + .into(), ); // Get old stakes @@ -3063,7 +3111,7 @@ fn test_parent_child_chain_emission() { let emission: U96F32 = U96F32::from_num(SubtensorModule::get_block_emission().unwrap_or(0)); // Set pending emission to 0 - PendingEmission::::insert(netuid, 0); + PendingEmission::::insert(netuid, AlphaCurrency::from(0)); // Run epoch with emission value SubtensorModule::run_coinbase(emission); @@ -3126,7 +3174,7 @@ fn test_parent_child_chain_emission() { ); let hotkeys = [hotkey_a, hotkey_b, hotkey_c]; - let mut total_stake_now = 0; + let mut total_stake_now = AlphaCurrency::from(0); for (hotkey, netuid, stake) in TotalHotkeyAlpha::::iter() { if hotkeys.contains(&hotkey) { total_stake_now += stake; @@ -3187,7 +3235,7 @@ fn test_parent_child_chain_epoch() { SubtensorModule::add_balance_to_coldkey_account(&coldkey_b, 1_000); SubtensorModule::add_balance_to_coldkey_account(&coldkey_c, 1_000); - mock::setup_reserves(netuid, 1_000_000_000_000, 1_000_000_000_000); + mock::setup_reserves(netuid, 1_000_000_000_000, 1_000_000_000_000.into()); // Swap to alpha let total_tao = I96F32::from_num(300_000 + 100_000 + 50_000); @@ -3200,19 +3248,25 @@ fn test_parent_child_chain_epoch() { &hotkey_a, &coldkey_a, netuid, - (total_alpha * I96F32::from_num(300_000) / total_tao).saturating_to_num::(), + (total_alpha * I96F32::from_num(300_000) / total_tao) + .saturating_to_num::() + .into(), ); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &hotkey_b, &coldkey_b, netuid, - (total_alpha * I96F32::from_num(100_000) / total_tao).saturating_to_num::(), + (total_alpha * I96F32::from_num(100_000) / total_tao) + .saturating_to_num::() + .into(), ); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &hotkey_c, &coldkey_c, netuid, - (total_alpha * I96F32::from_num(50_000) / total_tao).saturating_to_num::(), + (total_alpha * I96F32::from_num(50_000) / total_tao) + .saturating_to_num::() + .into(), ); // Get old stakes @@ -3258,7 +3312,7 @@ fn test_parent_child_chain_epoch() { let hardcoded_emission = I96F32::from_num(1_000_000); // 1 million (adjust as needed) let hotkey_emission = - SubtensorModule::epoch(netuid, hardcoded_emission.saturating_to_num::()); + SubtensorModule::epoch(netuid, hardcoded_emission.saturating_to_num::().into()); log::info!("hotkey_emission: {:?}", hotkey_emission); let total_emission: I96F32 = hotkey_emission .iter() @@ -3304,7 +3358,7 @@ fn test_dividend_distribution_with_children() { new_test_ext(1).execute_with(|| { let netuid = NetUid::from(1); add_network(netuid, 1, 0); - mock::setup_reserves(netuid, 1_000_000_000_000_000, 1_000_000_000_000_000); + mock::setup_reserves(netuid, 1_000_000_000_000_000, 1_000_000_000_000_000.into()); // Set owner cut to 0 SubtensorModule::set_subnet_owner_cut(0_u16); @@ -3337,19 +3391,25 @@ fn test_dividend_distribution_with_children() { &hotkey_a, &coldkey_a, netuid, - (total_alpha * I96F32::from_num(300_000) / total_tao).saturating_to_num::(), + (total_alpha * I96F32::from_num(300_000) / total_tao) + .saturating_to_num::() + .into(), ); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &hotkey_b, &coldkey_b, netuid, - (total_alpha * I96F32::from_num(100_000) / total_tao).saturating_to_num::(), + (total_alpha * I96F32::from_num(100_000) / total_tao) + .saturating_to_num::() + .into(), ); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &hotkey_c, &coldkey_c, netuid, - (total_alpha * I96F32::from_num(50_000) / total_tao).saturating_to_num::(), + (total_alpha * I96F32::from_num(50_000) / total_tao) + .saturating_to_num::() + .into(), ); // Get old stakes @@ -3388,8 +3448,8 @@ fn test_dividend_distribution_with_children() { let hardcoded_emission: I96F32 = I96F32::from_num(1_000_000); // 1 million (adjust as needed) - let hotkey_emission: Vec<(U256, u64, u64)> = - SubtensorModule::epoch(netuid, hardcoded_emission.saturating_to_num::()); + let hotkey_emission = + SubtensorModule::epoch(netuid, hardcoded_emission.saturating_to_num::().into()); log::info!("hotkey_emission: {:?}", hotkey_emission); let total_emission: I96F32 = hotkey_emission .iter() @@ -3423,17 +3483,17 @@ fn test_dividend_distribution_with_children() { let dividends_a = SubtensorModule::get_parent_child_dividends_distribution( &hotkey_a, netuid, - hardcoded_emission.saturating_to_num::(), + hardcoded_emission.saturating_to_num::().into(), ); let dividends_b = SubtensorModule::get_parent_child_dividends_distribution( &hotkey_b, netuid, - hardcoded_emission.saturating_to_num::(), + hardcoded_emission.saturating_to_num::().into(), ); let dividends_c = SubtensorModule::get_parent_child_dividends_distribution( &hotkey_c, netuid, - hardcoded_emission.saturating_to_num::(), + hardcoded_emission.saturating_to_num::().into(), ); log::info!("dividends_a: {:?}", dividends_a); log::info!("dividends_b: {:?}", dividends_b); @@ -3444,12 +3504,12 @@ fn test_dividend_distribution_with_children() { assert_eq!(dividends_a[0].0, hotkey_a); assert_eq!( dividends_a[0].1, - hardcoded_emission.saturating_to_num::() + hardcoded_emission.saturating_to_num::().into() ); assert_abs_diff_eq!( dividends_a .iter() - .map(|(_, emission)| *emission) + .map(|(_, emission)| u64::from(*emission)) .sum::(), hardcoded_emission.saturating_to_num::(), epsilon = (hardcoded_emission / 1000).saturating_to_num::() @@ -3464,21 +3524,21 @@ fn test_dividend_distribution_with_children() { assert_eq!(dividends_b.len(), 2); // A and B assert_eq!(dividends_b[1].0, hotkey_b); assert_abs_diff_eq!( - dividends_b[1].1, + u64::from(dividends_b[1].1), expected_b_b, epsilon = (hardcoded_emission / 1000).saturating_to_num::() ); let expected_b_a: u64 = hardcoded_emission.saturating_to_num::() - expected_b_b; assert_eq!(dividends_b[0].0, hotkey_a); assert_abs_diff_eq!( - dividends_b[0].1, + u64::from(dividends_b[0].1), expected_b_a, epsilon = (hardcoded_emission / 1000).saturating_to_num::() ); assert_abs_diff_eq!( dividends_b .iter() - .map(|(_, emission)| *emission) + .map(|(_, emission)| u64::from(*emission)) .sum::(), hardcoded_emission.saturating_to_num::(), epsilon = (hardcoded_emission / 1000).saturating_to_num::() @@ -3492,21 +3552,21 @@ fn test_dividend_distribution_with_children() { assert_eq!(dividends_c.len(), 2); // B and C assert_eq!(dividends_c[1].0, hotkey_c); assert_abs_diff_eq!( - dividends_c[1].1, + u64::from(dividends_c[1].1), expected_c_c, epsilon = (hardcoded_emission / 1000).saturating_to_num::() ); let expected_c_b: u64 = hardcoded_emission.saturating_to_num::() - expected_c_c; assert_eq!(dividends_c[0].0, hotkey_b); assert_abs_diff_eq!( - dividends_c[0].1, + u64::from(dividends_c[0].1), expected_c_b, epsilon = (hardcoded_emission / 1000).saturating_to_num::() ); assert_abs_diff_eq!( dividends_c .iter() - .map(|(_, emission)| *emission) + .map(|(_, emission)| u64::from(*emission)) .sum::(), hardcoded_emission.saturating_to_num::(), epsilon = (hardcoded_emission / 1000).saturating_to_num::() @@ -3554,7 +3614,7 @@ fn test_dynamic_parent_child_relationships() { SubtensorModule::add_balance_to_coldkey_account(&coldkey_child2, 30_000 + 1_000); let reserve = 1_000_000_000_000; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); // Swap to alpha let total_tao = I96F32::from_num(500_000 + 50_000 + 30_000); @@ -3568,30 +3628,36 @@ fn test_dynamic_parent_child_relationships() { &parent, &coldkey_parent, netuid, - (total_alpha * I96F32::from_num(500_000) / total_tao).saturating_to_num::(), + (total_alpha * I96F32::from_num(500_000) / total_tao) + .saturating_to_num::() + .into(), ); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &child1, &coldkey_child1, netuid, - (total_alpha * I96F32::from_num(50_000) / total_tao).saturating_to_num::(), + (total_alpha * I96F32::from_num(50_000) / total_tao) + .saturating_to_num::() + .into(), ); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &child2, &coldkey_child2, netuid, - (total_alpha * I96F32::from_num(30_000) / total_tao).saturating_to_num::(), + (total_alpha * I96F32::from_num(30_000) / total_tao) + .saturating_to_num::() + .into(), ); // Get old stakes - let stake_parent_0: u64 = SubtensorModule::get_stake_for_hotkey_on_subnet(&parent, netuid); - let stake_child1_0: u64 = SubtensorModule::get_stake_for_hotkey_on_subnet(&child1, netuid); - let stake_child2_0: u64 = SubtensorModule::get_stake_for_hotkey_on_subnet(&child2, netuid); + let stake_parent_0 = SubtensorModule::get_stake_for_hotkey_on_subnet(&parent, netuid); + let stake_child1_0 = SubtensorModule::get_stake_for_hotkey_on_subnet(&child1, netuid); + let stake_child2_0 = SubtensorModule::get_stake_for_hotkey_on_subnet(&child2, netuid); log::info!("stake_parent_0: {:?}", stake_parent_0); log::info!("stake_child1_0: {:?}", stake_child1_0); log::info!("stake_child2_0: {:?}", stake_child2_0); - let total_stake_0: u64 = stake_parent_0 + stake_child1_0 + stake_child2_0; + let total_stake_0 = stake_parent_0 + stake_child1_0 + stake_child2_0; // Assert initial stake is correct let rel_stake_parent_0 = I96F32::from_num(stake_parent_0) / total_alpha; @@ -3655,12 +3721,9 @@ fn test_dynamic_parent_child_relationships() { log::info!("total_stake_2: {:?}", total_stake_2); // Check final emission distribution - let stake_parent_2: u64 = - SubtensorModule::get_inherited_for_hotkey_on_subnet(&parent, netuid); - let stake_child1_2: u64 = - SubtensorModule::get_inherited_for_hotkey_on_subnet(&child1, netuid); - let stake_child2_2: u64 = - SubtensorModule::get_inherited_for_hotkey_on_subnet(&child2, netuid); + let stake_parent_2 = SubtensorModule::get_inherited_for_hotkey_on_subnet(&parent, netuid); + let stake_child1_2 = SubtensorModule::get_inherited_for_hotkey_on_subnet(&child1, netuid); + let stake_child2_2 = SubtensorModule::get_inherited_for_hotkey_on_subnet(&child2, netuid); let total_parent_stake = SubtensorModule::get_stake_for_hotkey_on_subnet(&parent, netuid); let _total_child1_stake = SubtensorModule::get_stake_for_hotkey_on_subnet(&child1, netuid); let _total_child2_stake = SubtensorModule::get_stake_for_hotkey_on_subnet(&child2, netuid); @@ -3678,14 +3741,14 @@ fn test_dynamic_parent_child_relationships() { let payout_2 = total_stake_2 - total_stake_1; log::info!("payout_2: {:?}", payout_2); - let total_emission: I96F32 = I96F32::from_num(payout_1 + payout_2); + let total_emission = I96F32::from_num(payout_1 + payout_2); #[allow(non_snake_case)] - let TOLERANCE: I96F32 = I96F32::from_num(0.001); // Allow for a small discrepancy due to potential rounding + let TOLERANCE = I96F32::from_num(0.001); // Allow for a small discrepancy due to potential rounding // Precise assertions with tolerance log::info!("total_emission: {:?}", total_emission); - let expected_parent_stake = ((I96F32::from_num(stake_parent_0) + let expected_parent_stake = ((I96F32::from_num(u64::from(stake_parent_0)) + total_emission * rel_stake_parent_0) * I96F32::from_num(5)) / I96F32::from_num(12); @@ -3703,7 +3766,7 @@ fn test_dynamic_parent_child_relationships() { // Second epoch: 5/12 parent_stake let expected_child1_stake = total_emission * rel_stake_child1_0 - + I96F32::from_num(stake_child1_0 + (total_parent_stake) / 4); + + I96F32::from_num(stake_child1_0 + total_parent_stake / 4.into()); assert!( (I96F32::from_num(stake_child1_2) - expected_child1_stake).abs() / expected_child1_stake @@ -3718,7 +3781,7 @@ fn test_dynamic_parent_child_relationships() { // Second epoch: 1/4 parent_stake + child1_stake let expected_child2_stake = total_emission * rel_stake_child2_0 - + I96F32::from_num(stake_child2_0 + (total_parent_stake) / 3); + + I96F32::from_num(u64::from(stake_child2_0 + total_parent_stake / 3.into())); assert!( (I96F32::from_num(stake_child2_2) - expected_child2_stake).abs() / expected_child2_stake @@ -3833,7 +3896,7 @@ fn test_dividend_distribution_with_children_same_coldkey_owner() { add_network(netuid, 1, 0); // Set SN owner cut to 0 SubtensorModule::set_subnet_owner_cut(0_u16); - mock::setup_reserves(netuid, 1_000_000_000_000, 1_000_000_000_000); + mock::setup_reserves(netuid, 1_000_000_000_000, 1_000_000_000_000.into()); // Define hotkeys and coldkeys let hotkey_a: U256 = U256::from(1); @@ -3859,18 +3922,22 @@ fn test_dividend_distribution_with_children_same_coldkey_owner() { &hotkey_a, &coldkey_a, netuid, - (total_alpha * I96F32::from_num(300_000) / total_tao).saturating_to_num::(), + (total_alpha * I96F32::from_num(300_000) / total_tao) + .saturating_to_num::() + .into(), ); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &hotkey_b, &coldkey_a, netuid, - (total_alpha * I96F32::from_num(100_000) / total_tao).saturating_to_num::(), + (total_alpha * I96F32::from_num(100_000) / total_tao) + .saturating_to_num::() + .into(), ); // Get old stakes - let stake_a: u64 = SubtensorModule::get_total_stake_for_hotkey(&hotkey_a); - let stake_b: u64 = SubtensorModule::get_total_stake_for_hotkey(&hotkey_b); + let stake_a = SubtensorModule::get_total_stake_for_hotkey(&hotkey_a); + let stake_b = SubtensorModule::get_total_stake_for_hotkey(&hotkey_b); // Assert initial stake is correct let rel_stake_a = I96F32::from_num(stake_a) / total_alpha; @@ -3896,8 +3963,8 @@ fn test_dividend_distribution_with_children_same_coldkey_owner() { let hardcoded_emission: I96F32 = I96F32::from_num(1_000_000); // 1 million (adjust as needed) - let hotkey_emission: Vec<(U256, u64, u64)> = - SubtensorModule::epoch(netuid, hardcoded_emission.saturating_to_num::()); + let hotkey_emission = + SubtensorModule::epoch(netuid, hardcoded_emission.saturating_to_num::().into()); log::info!("hotkey_emission: {:?}", hotkey_emission); let total_emission: I96F32 = hotkey_emission .iter() @@ -3926,12 +3993,12 @@ fn test_dividend_distribution_with_children_same_coldkey_owner() { let dividends_a = SubtensorModule::get_parent_child_dividends_distribution( &hotkey_a, netuid, - hardcoded_emission.saturating_to_num::(), + hardcoded_emission.saturating_to_num::().into(), ); let dividends_b = SubtensorModule::get_parent_child_dividends_distribution( &hotkey_b, netuid, - hardcoded_emission.saturating_to_num::(), + hardcoded_emission.saturating_to_num::().into(), ); log::info!("dividends_a: {:?}", dividends_a); log::info!("dividends_b: {:?}", dividends_b); @@ -3941,12 +4008,12 @@ fn test_dividend_distribution_with_children_same_coldkey_owner() { assert_eq!(dividends_a[0].0, hotkey_a); assert_eq!( dividends_a[0].1, - hardcoded_emission.saturating_to_num::() + hardcoded_emission.saturating_to_num::().into() ); assert_abs_diff_eq!( dividends_a .iter() - .map(|(_, emission)| *emission) + .map(|(_, emission)| u64::from(*emission)) .sum::(), hardcoded_emission.saturating_to_num::(), epsilon = (hardcoded_emission / 1000).saturating_to_num::() @@ -3966,7 +4033,7 @@ fn test_dividend_distribution_with_children_same_coldkey_owner() { (rel_stake_b / total_stake_b * hardcoded_emission).saturating_to_num::(); assert_abs_diff_eq!( - dividends_b[1].1, + u64::from(dividends_b[1].1), expected_b_b, epsilon = (hardcoded_emission / 1000).saturating_to_num::(), ); @@ -3975,14 +4042,14 @@ fn test_dividend_distribution_with_children_same_coldkey_owner() { ((rel_stake_a * 1 / 2) / total_stake_b * hardcoded_emission).saturating_to_num::(); assert_eq!(dividends_b[0].0, hotkey_a); assert_abs_diff_eq!( - dividends_b[0].1, + u64::from(dividends_b[0].1), expected_b_a, epsilon = (hardcoded_emission / 1000).saturating_to_num::() ); assert_abs_diff_eq!( dividends_b .iter() - .map(|(_, emission)| *emission) + .map(|(_, emission)| u64::from(*emission)) .sum::(), hardcoded_emission.saturating_to_num::(), epsilon = (hardcoded_emission / 1000).saturating_to_num::() diff --git a/pallets/subtensor/src/tests/coinbase.rs b/pallets/subtensor/src/tests/coinbase.rs index 285c318ba2..290e7415ac 100644 --- a/pallets/subtensor/src/tests/coinbase.rs +++ b/pallets/subtensor/src/tests/coinbase.rs @@ -9,6 +9,7 @@ use frame_support::assert_ok; use pallet_subtensor_swap::position::PositionId; use sp_core::U256; use substrate_fixed::types::{I64F64, I96F32, U96F32}; +use subtensor_runtime_common::Alpha as AlphaCurrency; #[allow(clippy::arithmetic_side_effects)] fn close(value: u64, target: u64, eps: u64) { @@ -52,7 +53,7 @@ fn test_dynamic_function_various_values() { // Set the price. SubnetMechanism::::insert(NetUid::from(1), 1); SubnetTAO::::insert(NetUid::from(1), (price * 1_000_000_000.0) as u64); - SubnetAlphaIn::::insert(NetUid::from(1), 1_000_000_000); + SubnetAlphaIn::::insert(NetUid::from(1), AlphaCurrency::from(1_000_000_000)); let (tao_in_emission, alpha_in_emission, alpha_out_emission) = SubtensorModule::get_dynamic_tao_emission(1.into(), tao_in, alpha_emission); assert!(tao_in_emission <= tao_in, "tao_in_emission is greater than tao_in"); assert!(alpha_in_emission <= alpha_emission, "alpha_in_emission is greater than alpha_emission"); @@ -189,7 +190,7 @@ fn test_coinbase_moving_prices() { add_network(netuid, 1, 0); // Set price to 1.0 SubnetTAO::::insert(netuid, 1_000_000); - SubnetAlphaIn::::insert(netuid, 1_000_000); + SubnetAlphaIn::::insert(netuid, AlphaCurrency::from(1_000_000)); SubnetMechanism::::insert(netuid, 1); SubnetMovingPrice::::insert(netuid, I96F32::from_num(1)); FirstEmissionBlockNumber::::insert(netuid, 1); @@ -245,7 +246,7 @@ fn test_update_moving_price_initial() { add_network(netuid, 1, 0); // Set current price to 1.0 SubnetTAO::::insert(netuid, 1_000_000); - SubnetAlphaIn::::insert(netuid, 1_000_000); + SubnetAlphaIn::::insert(netuid, AlphaCurrency::from(1_000_000)); SubnetMechanism::::insert(netuid, 1); SubnetMovingAlpha::::set(I96F32::from_num(0.5)); SubnetMovingPrice::::insert(netuid, I96F32::from_num(0)); @@ -270,7 +271,7 @@ fn test_update_moving_price_after_time() { add_network(netuid, 1, 0); // Set current price to 1.0 SubnetTAO::::insert(netuid, 1_000_000); - SubnetAlphaIn::::insert(netuid, 1_000_000); + SubnetAlphaIn::::insert(netuid, AlphaCurrency::from(1_000_000)); SubnetMechanism::::insert(netuid, 1); SubnetMovingAlpha::::set(I96F32::from_num(0.5)); SubnetMovingPrice::::insert(netuid, I96F32::from_num(0)); @@ -303,15 +304,21 @@ fn test_coinbase_alpha_issuance_base() { // Set up prices 1 and 1 let initial: u64 = 1_000_000; SubnetTAO::::insert(netuid1, initial); - SubnetAlphaIn::::insert(netuid1, initial); + SubnetAlphaIn::::insert(netuid1, AlphaCurrency::from(initial)); SubnetTAO::::insert(netuid2, initial); - SubnetAlphaIn::::insert(netuid2, initial); + SubnetAlphaIn::::insert(netuid2, AlphaCurrency::from(initial)); // Check initial SubtensorModule::run_coinbase(U96F32::from_num(emission)); // tao_in = 500_000 // alpha_in = 500_000/price = 500_000 - assert_eq!(SubnetAlphaIn::::get(netuid1), initial + emission / 2); - assert_eq!(SubnetAlphaIn::::get(netuid2), initial + emission / 2); + assert_eq!( + SubnetAlphaIn::::get(netuid1), + (initial + emission / 2).into() + ); + assert_eq!( + SubnetAlphaIn::::get(netuid2), + (initial + emission / 2).into() + ); }); } @@ -335,9 +342,9 @@ fn test_coinbase_alpha_issuance_different() { // Setup prices 1 and 1 let initial: u64 = 1_000_000; SubnetTAO::::insert(netuid1, initial); - SubnetAlphaIn::::insert(netuid1, initial); + SubnetAlphaIn::::insert(netuid1, AlphaCurrency::from(initial)); SubnetTAO::::insert(netuid2, initial); - SubnetAlphaIn::::insert(netuid2, initial); + SubnetAlphaIn::::insert(netuid2, AlphaCurrency::from(initial)); // Set subnet prices. SubnetMovingPrice::::insert(netuid1, I96F32::from_num(1)); SubnetMovingPrice::::insert(netuid2, I96F32::from_num(2)); @@ -345,12 +352,15 @@ fn test_coinbase_alpha_issuance_different() { SubtensorModule::run_coinbase(U96F32::from_num(emission)); // tao_in = 333_333 // alpha_in = 333_333/price = 333_333 + initial - assert_eq!(SubnetAlphaIn::::get(netuid1), initial + emission / 3); + assert_eq!( + SubnetAlphaIn::::get(netuid1), + (initial + emission / 3).into() + ); // tao_in = 666_666 // alpha_in = 666_666/price = 666_666 + initial assert_eq!( SubnetAlphaIn::::get(netuid2), - initial + emission / 3 + emission / 3 + (initial + emission / 3 + emission / 3).into() ); }); } @@ -371,9 +381,9 @@ fn test_coinbase_alpha_issuance_with_cap_trigger() { let initial: u64 = 1_000; let initial_alpha: u64 = initial * 1000000; SubnetTAO::::insert(netuid1, initial); - SubnetAlphaIn::::insert(netuid1, initial_alpha); // Make price extremely low. + SubnetAlphaIn::::insert(netuid1, AlphaCurrency::from(initial_alpha)); // Make price extremely low. SubnetTAO::::insert(netuid2, initial); - SubnetAlphaIn::::insert(netuid2, initial_alpha); // Make price extremely low. + SubnetAlphaIn::::insert(netuid2, AlphaCurrency::from(initial_alpha)); // Make price extremely low. // Set subnet prices. SubnetMovingPrice::::insert(netuid1, I96F32::from_num(1)); SubnetMovingPrice::::insert(netuid2, I96F32::from_num(2)); @@ -383,16 +393,16 @@ fn test_coinbase_alpha_issuance_with_cap_trigger() { // alpha_in = 333_333/price > 1_000_000_000 --> 1_000_000_000 + initial_alpha assert_eq!( SubnetAlphaIn::::get(netuid1), - initial_alpha + 1_000_000_000 + (initial_alpha + 1_000_000_000).into() ); - assert_eq!(SubnetAlphaOut::::get(netuid2), 1_000_000_000); + assert_eq!(SubnetAlphaOut::::get(netuid2), 1_000_000_000.into()); // tao_in = 666_666 // alpha_in = 666_666/price > 1_000_000_000 --> 1_000_000_000 + initial_alpha assert_eq!( SubnetAlphaIn::::get(netuid2), - initial_alpha + 1_000_000_000 + (initial_alpha + 1_000_000_000).into() ); - assert_eq!(SubnetAlphaOut::::get(netuid2), 1_000_000_000); // Gets full block emission. + assert_eq!(SubnetAlphaOut::::get(netuid2), 1_000_000_000.into()); // Gets full block emission. }); } @@ -410,14 +420,14 @@ fn test_coinbase_alpha_issuance_with_cap_trigger_and_block_emission() { SubnetMechanism::::insert(netuid2, 1); // Setup prices 1000000 let initial: u64 = 1_000; - let initial_alpha: u64 = initial * 1000000; + let initial_alpha = AlphaCurrency::from(initial * 1000000); SubnetTAO::::insert(netuid1, initial); SubnetAlphaIn::::insert(netuid1, initial_alpha); // Make price extremely low. SubnetTAO::::insert(netuid2, initial); SubnetAlphaIn::::insert(netuid2, initial_alpha); // Make price extremely low. // Set issuance to greater than 21M - SubnetAlphaOut::::insert(netuid1, 22_000_000_000_000_000); // Set issuance above 21M - SubnetAlphaOut::::insert(netuid2, 22_000_000_000_000_000); // Set issuance above 21M + SubnetAlphaOut::::insert(netuid1, AlphaCurrency::from(22_000_000_000_000_000)); // Set issuance above 21M + SubnetAlphaOut::::insert(netuid2, AlphaCurrency::from(22_000_000_000_000_000)); // Set issuance above 21M // Set subnet prices. SubnetMovingPrice::::insert(netuid1, I96F32::from_num(1)); SubnetMovingPrice::::insert(netuid2, I96F32::from_num(2)); @@ -426,11 +436,17 @@ fn test_coinbase_alpha_issuance_with_cap_trigger_and_block_emission() { // tao_in = 333_333 // alpha_in = 333_333/price > 1_000_000_000 --> 0 + initial_alpha assert_eq!(SubnetAlphaIn::::get(netuid1), initial_alpha); - assert_eq!(SubnetAlphaOut::::get(netuid2), 22_000_000_000_000_000); + assert_eq!( + SubnetAlphaOut::::get(netuid2), + 22_000_000_000_000_000.into() + ); // tao_in = 666_666 // alpha_in = 666_666/price > 1_000_000_000 --> 0 + initial_alpha assert_eq!(SubnetAlphaIn::::get(netuid2), initial_alpha); - assert_eq!(SubnetAlphaOut::::get(netuid2), 22_000_000_000_000_000); + assert_eq!( + SubnetAlphaOut::::get(netuid2), + 22_000_000_000_000_000.into() + ); // No emission. }); } @@ -441,14 +457,14 @@ fn test_owner_cut_base() { new_test_ext(1).execute_with(|| { let netuid = NetUid::from(1); add_network(netuid, 1, 0); - mock::setup_reserves(netuid, 1_000_000_000_000, 1_000_000_000_000); + mock::setup_reserves(netuid, 1_000_000_000_000, 1_000_000_000_000.into()); SubtensorModule::set_tempo(netuid, 10000); // Large number (dont drain) SubtensorModule::set_subnet_owner_cut(0); SubtensorModule::run_coinbase(U96F32::from_num(0)); - assert_eq!(PendingOwnerCut::::get(netuid), 0); // No cut + assert_eq!(PendingOwnerCut::::get(netuid), 0.into()); // No cut SubtensorModule::set_subnet_owner_cut(u16::MAX); SubtensorModule::run_coinbase(U96F32::from_num(0)); - assert_eq!(PendingOwnerCut::::get(netuid), 1_000_000_000); // Full cut. + assert_eq!(PendingOwnerCut::::get(netuid), 1_000_000_000.into()); // Full cut. }); } @@ -459,34 +475,40 @@ fn test_pending_swapped() { let netuid = NetUid::from(1); let emission: u64 = 1_000_000; add_network(netuid, 1, 0); - mock::setup_reserves(netuid, 1_000_000, 1); + mock::setup_reserves(netuid, 1_000_000, 1.into()); SubtensorModule::run_coinbase(U96F32::from_num(0)); - assert_eq!(PendingAlphaSwapped::::get(netuid), 0); // Zero tao weight and no root. + assert_eq!(PendingAlphaSwapped::::get(netuid), 0.into()); // Zero tao weight and no root. SubnetTAO::::insert(NetUid::ROOT, 1_000_000_000); // Add root weight. SubtensorModule::run_coinbase(U96F32::from_num(0)); - assert_eq!(PendingAlphaSwapped::::get(netuid), 0); // Zero tao weight with 1 root. + assert_eq!(PendingAlphaSwapped::::get(netuid), 0.into()); // Zero tao weight with 1 root. SubtensorModule::set_tempo(netuid, 10000); // Large number (dont drain) SubtensorModule::set_tao_weight(u64::MAX); // Set TAO weight to 1.0 SubtensorModule::run_coinbase(U96F32::from_num(0)); // 1 TAO / ( 1 + 3 ) = 0.25 * 1 / 2 = 125000000 assert_abs_diff_eq!( - PendingAlphaSwapped::::get(netuid), + u64::from(PendingAlphaSwapped::::get(netuid)), 125000000, epsilon = 1 ); assert_abs_diff_eq!( - PendingEmission::::get(netuid), + u64::from(PendingEmission::::get(netuid)), 1_000_000_000 - 125000000, epsilon = 1 ); // 1 - swapped. - assert_abs_diff_eq!(PendingRootDivs::::get(netuid), 125000000, epsilon = 1); // swapped * (price = 1) + assert_abs_diff_eq!( + u64::from(PendingRootDivs::::get(netuid)), + 125000000, + epsilon = 1 + ); // swapped * (price = 1) }); } // SKIP_WASM_BUILD=1 RUST_LOG=debug cargo test --package pallet-subtensor --lib -- tests::coinbase::test_drain_base --exact --show-output --nocapture #[test] fn test_drain_base() { - new_test_ext(1).execute_with(|| SubtensorModule::drain_pending_emission(0.into(), 0, 0, 0, 0)); + new_test_ext(1).execute_with(|| { + SubtensorModule::drain_pending_emission(0.into(), 0.into(), 0, 0.into(), 0.into()) + }); } // SKIP_WASM_BUILD=1 RUST_LOG=debug cargo test --package pallet-subtensor --lib -- tests::coinbase::test_drain_base_with_subnet --exact --show-output --nocapture @@ -495,7 +517,7 @@ fn test_drain_base_with_subnet() { new_test_ext(1).execute_with(|| { let netuid = NetUid::from(1); add_network(netuid, 1, 0); - SubtensorModule::drain_pending_emission(netuid, 0, 0, 0, 0) + SubtensorModule::drain_pending_emission(netuid, 0.into(), 0, 0.into(), 0.into()) }); } @@ -507,15 +529,21 @@ fn test_drain_base_with_subnet_with_single_staker_not_registered() { add_network(netuid, 1, 0); let hotkey = U256::from(1); let coldkey = U256::from(2); - let stake_before: u64 = 1_000_000_000; + let stake_before = AlphaCurrency::from(1_000_000_000); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &hotkey, &coldkey, netuid, stake_before, ); - let pending_alpha: u64 = 1_000_000_000; - SubtensorModule::drain_pending_emission(netuid, pending_alpha, 0, 0, 0); + let pending_alpha = AlphaCurrency::from(1_000_000_000); + SubtensorModule::drain_pending_emission( + netuid, + pending_alpha.into(), + 0, + 0.into(), + 0.into(), + ); let stake_after = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey, &coldkey, netuid); assert_eq!(stake_before, stake_after); // Not registered. @@ -530,7 +558,7 @@ fn test_drain_base_with_subnet_with_single_staker_registered() { add_network(netuid, 1, 0); let hotkey = U256::from(1); let coldkey = U256::from(2); - let stake_before: u64 = 1_000_000_000; + let stake_before = AlphaCurrency::from(1_000_000_000); register_ok_neuron(netuid, hotkey, coldkey, 0); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &hotkey, @@ -538,11 +566,15 @@ fn test_drain_base_with_subnet_with_single_staker_registered() { netuid, stake_before, ); - let pending_alpha: u64 = 1_000_000_000; - SubtensorModule::drain_pending_emission(netuid, pending_alpha, 0, 0, 0); + let pending_alpha = AlphaCurrency::from(1_000_000_000); + SubtensorModule::drain_pending_emission(netuid, pending_alpha, 0, 0.into(), 0.into()); let stake_after = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey, &coldkey, netuid); - close(stake_before + pending_alpha, stake_after, 10); // Registered gets all emission. + close( + (stake_before + pending_alpha).into(), + stake_after.into(), + 10, + ); // Registered gets all emission. }); } @@ -554,7 +586,7 @@ fn test_drain_base_with_subnet_with_single_staker_registered_root_weight() { add_network(netuid, 1, 0); let hotkey = U256::from(1); let coldkey = U256::from(2); - let stake_before: u64 = 1_000_000_000; + let stake_before = AlphaCurrency::from(1_000_000_000); // register_ok_neuron(root, hotkey, coldkey, 0); register_ok_neuron(netuid, hotkey, coldkey, 0); Delegates::::insert(hotkey, 0); @@ -572,8 +604,14 @@ fn test_drain_base_with_subnet_with_single_staker_registered_root_weight() { stake_before, ); let pending_tao: u64 = 1_000_000_000; - let pending_alpha: u64 = 1_000_000_000; - SubtensorModule::drain_pending_emission(netuid, pending_alpha, pending_tao, 0, 0); + let pending_alpha = AlphaCurrency::from(1_000_000_000); + SubtensorModule::drain_pending_emission( + netuid, + pending_alpha, + pending_tao, + 0.into(), + 0.into(), + ); let stake_after = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey, &coldkey, netuid); let root_after = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( @@ -581,8 +619,12 @@ fn test_drain_base_with_subnet_with_single_staker_registered_root_weight() { &coldkey, NetUid::ROOT, ); - close(stake_before + pending_alpha, stake_after, 10); // Registered gets all alpha emission. - close(stake_before + pending_tao, root_after, 10); // Registered gets all tao emission + close( + (stake_before + pending_alpha).into(), + stake_after.into(), + 10, + ); // Registered gets all alpha emission. + close(u64::from(stake_before) + pending_tao, root_after.into(), 10); // Registered gets all tao emission }); } @@ -595,7 +637,7 @@ fn test_drain_base_with_subnet_with_two_stakers_registered() { let hotkey1 = U256::from(1); let hotkey2 = U256::from(2); let coldkey = U256::from(3); - let stake_before: u64 = 1_000_000_000; + let stake_before = AlphaCurrency::from(1_000_000_000); register_ok_neuron(netuid, hotkey1, coldkey, 0); register_ok_neuron(netuid, hotkey2, coldkey, 0); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( @@ -610,14 +652,22 @@ fn test_drain_base_with_subnet_with_two_stakers_registered() { netuid, stake_before, ); - let pending_alpha: u64 = 1_000_000_000; - SubtensorModule::drain_pending_emission(netuid, pending_alpha, 0, 0, 0); + let pending_alpha = AlphaCurrency::from(1_000_000_000); + SubtensorModule::drain_pending_emission(netuid, pending_alpha, 0, 0.into(), 0.into()); let stake_after1 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey1, &coldkey, netuid); let stake_after2 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey2, &coldkey, netuid); - close(stake_before + pending_alpha / 2, stake_after1, 10); // Registered gets 1/2 emission - close(stake_before + pending_alpha / 2, stake_after2, 10); // Registered gets 1/2 emission. + close( + (stake_before + pending_alpha / 2.into()).into(), + stake_after1.into(), + 10, + ); // Registered gets 1/2 emission + close( + (stake_before + pending_alpha / 2.into()).into(), + stake_after2.into(), + 10, + ); // Registered gets 1/2 emission. }); } @@ -630,7 +680,7 @@ fn test_drain_base_with_subnet_with_two_stakers_registered_and_root() { let hotkey1 = U256::from(1); let hotkey2 = U256::from(2); let coldkey = U256::from(3); - let stake_before: u64 = 1_000_000_000; + let stake_before = AlphaCurrency::from(1_000_000_000); register_ok_neuron(netuid, hotkey1, coldkey, 0); register_ok_neuron(netuid, hotkey2, coldkey, 0); Delegates::::insert(hotkey1, 0); @@ -661,8 +711,14 @@ fn test_drain_base_with_subnet_with_two_stakers_registered_and_root() { stake_before, ); let pending_tao: u64 = 1_000_000_000; - let pending_alpha: u64 = 1_000_000_000; - SubtensorModule::drain_pending_emission(netuid, pending_alpha, pending_tao, 0, 0); + let pending_alpha = AlphaCurrency::from(1_000_000_000); + SubtensorModule::drain_pending_emission( + netuid, + pending_alpha, + pending_tao, + 0.into(), + 0.into(), + ); let stake_after1 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey1, &coldkey, netuid); let root_after1 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( @@ -677,10 +733,26 @@ fn test_drain_base_with_subnet_with_two_stakers_registered_and_root() { &coldkey, NetUid::ROOT, ); - close(stake_before + pending_alpha / 2, stake_after1, 10); // Registered gets 1/2 emission - close(stake_before + pending_alpha / 2, stake_after2, 10); // Registered gets 1/2 emission. - close(stake_before + pending_tao / 2, root_after1, 10); // Registered gets 1/2 tao emission - close(stake_before + pending_tao / 2, root_after2, 10); // Registered gets 1/2 tao emission + close( + (stake_before + pending_alpha / 2.into()).into(), + stake_after1.into(), + 10, + ); // Registered gets 1/2 emission + close( + (stake_before + pending_alpha / 2.into()).into(), + stake_after2.into(), + 10, + ); // Registered gets 1/2 emission. + close( + u64::from(stake_before) + pending_tao / 2, + root_after1.into(), + 10, + ); // Registered gets 1/2 tao emission + close( + u64::from(stake_before) + pending_tao / 2, + root_after2.into(), + 10, + ); // Registered gets 1/2 tao emission }); } @@ -693,7 +765,7 @@ fn test_drain_base_with_subnet_with_two_stakers_registered_and_root_different_am let hotkey1 = U256::from(1); let hotkey2 = U256::from(2); let coldkey = U256::from(3); - let stake_before: u64 = 1_000_000_000; + let stake_before = AlphaCurrency::from(1_000_000_000); Delegates::::insert(hotkey1, 0); Delegates::::insert(hotkey2, 0); register_ok_neuron(netuid, hotkey1, coldkey, 0); @@ -709,7 +781,7 @@ fn test_drain_base_with_subnet_with_two_stakers_registered_and_root_different_am &hotkey1, &coldkey, NetUid::ROOT, - 2 * stake_before, // Hotkey 1 has twice as much root weight. + stake_before * 2.into(), // Hotkey 1 has twice as much root weight. ); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &hotkey2, @@ -724,8 +796,14 @@ fn test_drain_base_with_subnet_with_two_stakers_registered_and_root_different_am stake_before, ); let pending_tao: u64 = 1_000_000_000; - let pending_alpha: u64 = 1_000_000_000; - SubtensorModule::drain_pending_emission(netuid, pending_alpha, pending_tao, 0, 0); + let pending_alpha = AlphaCurrency::from(1_000_000_000); + SubtensorModule::drain_pending_emission( + netuid, + pending_alpha, + pending_tao, + 0.into(), + 0.into(), + ); let stake_after1 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey1, &coldkey, netuid); let root_after1 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( @@ -742,16 +820,32 @@ fn test_drain_base_with_subnet_with_two_stakers_registered_and_root_different_am ); let expected_stake = I96F32::from_num(stake_before) + (I96F32::from_num(pending_alpha) * I96F32::from_num(1.0 / 2.0)); - assert_abs_diff_eq!(expected_stake.to_num::(), stake_after1, epsilon = 10); // Registered gets 50% of alpha emission + assert_abs_diff_eq!( + expected_stake.to_num::(), + stake_after1.into(), + epsilon = 10 + ); // Registered gets 50% of alpha emission let expected_stake2 = I96F32::from_num(stake_before) + I96F32::from_num(pending_alpha) * I96F32::from_num(1.0 / 2.0); - assert_abs_diff_eq!(expected_stake2.to_num::(), stake_after2, epsilon = 10); // Registered gets 50% emission - let expected_root1 = I96F32::from_num(2 * stake_before) + assert_abs_diff_eq!( + expected_stake2.to_num::(), + stake_after2.into(), + epsilon = 10 + ); // Registered gets 50% emission + let expected_root1 = I96F32::from_num(2 * u64::from(stake_before)) + I96F32::from_num(pending_tao) * I96F32::from_num(2.0 / 3.0); - assert_abs_diff_eq!(expected_root1.to_num::(), root_after1, epsilon = 10); // Registered gets 2/3 tao emission - let expected_root2 = I96F32::from_num(stake_before) + assert_abs_diff_eq!( + expected_root1.to_num::(), + root_after1.into(), + epsilon = 10 + ); // Registered gets 2/3 tao emission + let expected_root2 = I96F32::from_num(u64::from(stake_before)) + I96F32::from_num(pending_tao) * I96F32::from_num(1.0 / 3.0); - assert_abs_diff_eq!(expected_root2.to_num::(), root_after2, epsilon = 10); // Registered gets 1/3 tao emission + assert_abs_diff_eq!( + expected_root2.to_num::(), + root_after2.into(), + epsilon = 10 + ); // Registered gets 1/3 tao emission }); } @@ -765,7 +859,7 @@ fn test_drain_base_with_subnet_with_two_stakers_registered_and_root_different_am let hotkey1 = U256::from(1); let hotkey2 = U256::from(2); let coldkey = U256::from(3); - let stake_before: u64 = 1_000_000_000; + let stake_before = AlphaCurrency::from(1_000_000_000); Delegates::::insert(hotkey1, 0); Delegates::::insert(hotkey2, 0); register_ok_neuron(netuid, hotkey1, coldkey, 0); @@ -781,7 +875,7 @@ fn test_drain_base_with_subnet_with_two_stakers_registered_and_root_different_am &hotkey1, &coldkey, NetUid::ROOT, - 2 * stake_before, // Hotkey 1 has twice as much root weight. + stake_before * 2.into(), // Hotkey 1 has twice as much root weight. ); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &hotkey2, @@ -796,8 +890,14 @@ fn test_drain_base_with_subnet_with_two_stakers_registered_and_root_different_am stake_before, ); let pending_tao: u64 = 1_000_000_000; - let pending_alpha: u64 = 1_000_000_000; - SubtensorModule::drain_pending_emission(netuid, pending_alpha, pending_tao, 0, 0); + let pending_alpha = AlphaCurrency::from(1_000_000_000); + SubtensorModule::drain_pending_emission( + netuid, + pending_alpha, + pending_tao, + 0.into(), + 0.into(), + ); let stake_after1 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey1, &coldkey, netuid); let root_after1 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( @@ -814,18 +914,34 @@ fn test_drain_base_with_subnet_with_two_stakers_registered_and_root_different_am ); let expected_stake = I96F32::from_num(stake_before) + I96F32::from_num(pending_alpha) * I96F32::from_num(1.0 / 2.0); - assert_abs_diff_eq!(expected_stake.to_num::(), stake_after1, epsilon = 10); + assert_abs_diff_eq!( + expected_stake.to_num::(), + u64::from(stake_after1), + epsilon = 10 + ); let expected_stake2 = I96F32::from_num(stake_before) + I96F32::from_num(pending_alpha) * I96F32::from_num(1.0 / 2.0); - assert_abs_diff_eq!(expected_stake2.to_num::(), stake_after2, epsilon = 10); + assert_abs_diff_eq!( + expected_stake2.to_num::(), + u64::from(stake_after2), + epsilon = 10 + ); // hotkey 1 has 2 / 3 root tao - let expected_root1 = I96F32::from_num(2 * stake_before) + let expected_root1 = I96F32::from_num(2 * u64::from(stake_before)) + I96F32::from_num(pending_tao) * I96F32::from_num(2.0 / 3.0); - assert_abs_diff_eq!(expected_root1.to_num::(), root_after1, epsilon = 10); + assert_abs_diff_eq!( + expected_root1.to_num::(), + u64::from(root_after1), + epsilon = 10 + ); // hotkey 1 has 1 / 3 root tao - let expected_root2 = I96F32::from_num(stake_before) + let expected_root2 = I96F32::from_num(u64::from(stake_before)) + I96F32::from_num(pending_tao) * I96F32::from_num(1.0 / 3.0); - assert_abs_diff_eq!(expected_root2.to_num::(), root_after2, epsilon = 10); + assert_abs_diff_eq!( + expected_root2.to_num::(), + u64::from(root_after2), + epsilon = 10 + ); }); } @@ -838,7 +954,7 @@ fn test_drain_alpha_childkey_parentkey() { let parent = U256::from(1); let child = U256::from(2); let coldkey = U256::from(3); - let stake_before: u64 = 1_000_000_000; + let stake_before = AlphaCurrency::from(1_000_000_000); register_ok_neuron(netuid, child, coldkey, 0); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &parent, @@ -851,8 +967,8 @@ fn test_drain_alpha_childkey_parentkey() { // Childkey take is 10% ChildkeyTake::::insert(child, netuid, u16::MAX / 10); - let pending_alpha: u64 = 1_000_000_000; - SubtensorModule::drain_pending_emission(netuid, pending_alpha, 0, 0, 0); + let pending_alpha = AlphaCurrency::from(1_000_000_000); + SubtensorModule::drain_pending_emission(netuid, pending_alpha, 0, 0.into(), 0.into()); let parent_stake_after = SubtensorModule::get_stake_for_hotkey_on_subnet(&parent, netuid); let child_stake_after = SubtensorModule::get_stake_for_hotkey_on_subnet(&child, netuid); @@ -864,9 +980,9 @@ fn test_drain_alpha_childkey_parentkey() { expected.to_num::(), parent_stake_after ); - close(expected.to_num::(), parent_stake_after, 10_000); - let expected = I96F32::from_num(pending_alpha) / I96F32::from_num(10); - close(expected.to_num::(), child_stake_after, 10_000); + close(expected.to_num::(), parent_stake_after.into(), 10_000); + let expected = I96F32::from_num(u64::from(pending_alpha)) / I96F32::from_num(10); + close(expected.to_num::(), child_stake_after.into(), 10_000); }); } @@ -900,14 +1016,14 @@ fn test_get_root_children() { )); // Add stake for Alice and Bob on root. - let alice_root_stake: u64 = 1_000_000_000; + let alice_root_stake = AlphaCurrency::from(1_000_000_000); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &alice, &cold, NetUid::ROOT, alice_root_stake, ); - let bob_root_stake: u64 = 1_000_000_000; + let bob_root_stake = AlphaCurrency::from(1_000_000_000); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &bob, &cold, @@ -916,14 +1032,14 @@ fn test_get_root_children() { ); // Add stake for Alice and Bob on netuid. - let alice_alpha_stake: u64 = 1_000_000_000; + let alice_alpha_stake = AlphaCurrency::from(1_000_000_000); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &alice, &cold, alpha, alice_alpha_stake, ); - let bob_alpha_stake: u64 = 1_000_000_000; + let bob_alpha_stake = AlphaCurrency::from(1_000_000_000); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &bob, &cold, @@ -960,7 +1076,7 @@ fn test_get_root_children() { ); assert_eq!( SubtensorModule::get_inherited_for_hotkey_on_subnet(&alice, alpha), - 0 + 0.into() ); assert_eq!( SubtensorModule::get_inherited_for_hotkey_on_subnet(&bob, NetUid::ROOT), @@ -978,7 +1094,7 @@ fn test_get_root_children() { ); assert_eq!( SubtensorModule::get_tao_inherited_for_hotkey_on_subnet(&bob, alpha), - bob_root_stake + alice_root_stake + u64::from(bob_root_stake + alice_root_stake) ); // Get Alice stake amounts on subnet alpha. @@ -989,7 +1105,10 @@ fn test_get_root_children() { // Get Bob stake amounts on subnet alpha. let (bob_total, bob_alpha, bob_tao): (I64F64, I64F64, I64F64) = SubtensorModule::get_stake_weights_for_hotkey_on_subnet(&bob, alpha); - assert_eq!(bob_total, I64F64::from_num(4 * bob_root_stake)); + assert_eq!( + bob_total, + I64F64::from_num(u64::from(bob_root_stake * 4.into())) + ); }); } @@ -1020,14 +1139,14 @@ fn test_get_root_children_drain() { bob, )); // Add stake for Alice and Bob on root. - let alice_root_stake: u64 = 1_000_000_000; + let alice_root_stake = AlphaCurrency::from(1_000_000_000); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &alice, &cold_alice, NetUid::ROOT, alice_root_stake, ); - let bob_root_stake: u64 = 1_000_000_000; + let bob_root_stake = AlphaCurrency::from(1_000_000_000); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &bob, &cold_bob, @@ -1035,14 +1154,14 @@ fn test_get_root_children_drain() { alice_root_stake, ); // Add stake for Alice and Bob on netuid. - let alice_alpha_stake: u64 = 1_000_000_000; + let alice_alpha_stake = AlphaCurrency::from(1_000_000_000); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &alice, &cold_alice, alpha, alice_alpha_stake, ); - let bob_alpha_stake: u64 = 1_000_000_000; + let bob_alpha_stake = AlphaCurrency::from(1_000_000_000); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &bob, &cold_bob, @@ -1064,52 +1183,67 @@ fn test_get_root_children_drain() { // Get Bob stake amounts on subnet alpha. let (bob_total, bob_alpha, bob_tao): (I64F64, I64F64, I64F64) = SubtensorModule::get_stake_weights_for_hotkey_on_subnet(&bob, alpha); - assert_eq!(bob_total, I64F64::from_num(4 * bob_root_stake)); + assert_eq!( + bob_total, + I64F64::from_num(u64::from(bob_root_stake * 4.into())) + ); // Lets drain - let pending_alpha: u64 = 1_000_000_000; - SubtensorModule::drain_pending_emission(alpha, pending_alpha, 0, 0, 0); + let pending_alpha = AlphaCurrency::from(1_000_000_000); + SubtensorModule::drain_pending_emission(alpha, pending_alpha, 0, 0.into(), 0.into()); // Alice and Bob both made half of the dividends. assert_eq!( SubtensorModule::get_stake_for_hotkey_on_subnet(&alice, alpha), - alice_alpha_stake + pending_alpha / 2 + alice_alpha_stake + pending_alpha / 2.into() ); assert_eq!( SubtensorModule::get_stake_for_hotkey_on_subnet(&bob, alpha), - bob_alpha_stake + pending_alpha / 2 + bob_alpha_stake + pending_alpha / 2.into() ); // Lets drain - let pending_alpha: u64 = 1_000_000_000; + let pending_alpha = AlphaCurrency::from(1_000_000_000); let pending_root: u64 = 1_000_000_000; - SubtensorModule::drain_pending_emission(alpha, pending_alpha, pending_root, 0, 0); + SubtensorModule::drain_pending_emission( + alpha, + pending_alpha, + pending_root, + 0.into(), + 0.into(), + ); // Alice and Bob both made half of the dividends. assert_eq!( SubtensorModule::get_stake_for_hotkey_on_subnet(&alice, NetUid::ROOT), - alice_root_stake + pending_root / 2 + alice_root_stake + (pending_root / 2).into() ); assert_eq!( SubtensorModule::get_stake_for_hotkey_on_subnet(&bob, NetUid::ROOT), - bob_root_stake + pending_root / 2 + bob_root_stake + (pending_root / 2).into() ); // Lets change the take value. (Bob is greedy.) ChildkeyTake::::insert(bob, alpha, u16::MAX); // Lets drain - let pending_alpha: u64 = 1_000_000_000; + let pending_alpha = AlphaCurrency::from(1_000_000_000); let pending_root: u64 = 1_000_000_000; - SubtensorModule::drain_pending_emission(alpha, pending_alpha, pending_root, 0, 0); + SubtensorModule::drain_pending_emission( + alpha, + pending_alpha, + pending_root, + 0.into(), + 0.into(), + ); // Alice makes nothing - assert_eq!(AlphaDividendsPerSubnet::::get(alpha, alice), 0); + assert_eq!(AlphaDividendsPerSubnet::::get(alpha, alice), 0.into()); assert_eq!(TaoDividendsPerSubnet::::get(alpha, alice), 0); // Bob makes it all. assert_abs_diff_eq!( - AlphaDividendsPerSubnet::::get(alpha, bob), - pending_alpha, + u64::from(AlphaDividendsPerSubnet::::get(alpha, bob)), + u64::from(pending_alpha), epsilon = 1 ); assert_eq!(TaoDividendsPerSubnet::::get(alpha, bob), pending_root); @@ -1143,14 +1277,14 @@ fn test_get_root_children_drain_half_proportion() { bob, )); // Add stake for Alice and Bob on root. - let alice_root_stake: u64 = 1_000_000_000; + let alice_root_stake = AlphaCurrency::from(1_000_000_000); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &alice, &cold_alice, NetUid::ROOT, alice_root_stake, ); - let bob_root_stake: u64 = 1_000_000_000; + let bob_root_stake = AlphaCurrency::from(1_000_000_000); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &bob, &cold_bob, @@ -1158,14 +1292,14 @@ fn test_get_root_children_drain_half_proportion() { alice_root_stake, ); // Add stake for Alice and Bob on netuid. - let alice_alpha_stake: u64 = 1_000_000_000; + let alice_alpha_stake = AlphaCurrency::from(1_000_000_000); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &alice, &cold_alice, alpha, alice_alpha_stake, ); - let bob_alpha_stake: u64 = 1_000_000_000; + let bob_alpha_stake = AlphaCurrency::from(1_000_000_000); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &bob, &cold_bob, @@ -1181,18 +1315,18 @@ fn test_get_root_children_drain_half_proportion() { Delegates::::insert(bob, 0); // Lets drain! - let pending_alpha: u64 = 1_000_000_000; - SubtensorModule::drain_pending_emission(alpha, pending_alpha, 0, 0, 0); + let pending_alpha = AlphaCurrency::from(1_000_000_000); + SubtensorModule::drain_pending_emission(alpha, pending_alpha, 0, 0.into(), 0.into()); // Alice and Bob make the same amount. close( - AlphaDividendsPerSubnet::::get(alpha, alice), - pending_alpha / 2, + AlphaDividendsPerSubnet::::get(alpha, alice).into(), + (pending_alpha / 2.into()).into(), 10, ); close( - AlphaDividendsPerSubnet::::get(alpha, bob), - pending_alpha / 2, + AlphaDividendsPerSubnet::::get(alpha, bob).into(), + (pending_alpha / 2.into()).into(), 10, ); }); @@ -1225,14 +1359,14 @@ fn test_get_root_children_drain_with_take() { bob, )); // Add stake for Alice and Bob on root. - let alice_root_stake: u64 = 1_000_000_000; + let alice_root_stake = AlphaCurrency::from(1_000_000_000); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &alice, &cold_alice, NetUid::ROOT, alice_root_stake, ); - let bob_root_stake: u64 = 1_000_000_000; + let bob_root_stake = AlphaCurrency::from(1_000_000_000); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &bob, &cold_bob, @@ -1240,14 +1374,14 @@ fn test_get_root_children_drain_with_take() { alice_root_stake, ); // Add stake for Alice and Bob on netuid. - let alice_alpha_stake: u64 = 1_000_000_000; + let alice_alpha_stake = AlphaCurrency::from(1_000_000_000); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &alice, &cold_alice, alpha, alice_alpha_stake, ); - let bob_alpha_stake: u64 = 1_000_000_000; + let bob_alpha_stake = AlphaCurrency::from(1_000_000_000); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &bob, &cold_bob, @@ -1262,14 +1396,18 @@ fn test_get_root_children_drain_with_take() { Delegates::::insert(bob, 0); // Lets drain! - let pending_alpha: u64 = 1_000_000_000; - SubtensorModule::drain_pending_emission(alpha, pending_alpha, 0, 0, 0); + let pending_alpha = AlphaCurrency::from(1_000_000_000); + SubtensorModule::drain_pending_emission(alpha, pending_alpha, 0, 0.into(), 0.into()); // Bob makes it all. - close(AlphaDividendsPerSubnet::::get(alpha, alice), 0, 10); close( - AlphaDividendsPerSubnet::::get(alpha, bob), - pending_alpha, + AlphaDividendsPerSubnet::::get(alpha, alice).into(), + 0, + 10, + ); + close( + AlphaDividendsPerSubnet::::get(alpha, bob).into(), + pending_alpha.into(), 10, ); }); @@ -1302,14 +1440,14 @@ fn test_get_root_children_drain_with_half_take() { bob, )); // Add stake for Alice and Bob on root. - let alice_root_stake: u64 = 1_000_000_000; + let alice_root_stake = AlphaCurrency::from(1_000_000_000); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &alice, &cold_alice, NetUid::ROOT, alice_root_stake, ); - let bob_root_stake: u64 = 1_000_000_000; + let bob_root_stake = AlphaCurrency::from(1_000_000_000); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &bob, &cold_bob, @@ -1317,14 +1455,14 @@ fn test_get_root_children_drain_with_half_take() { alice_root_stake, ); // Add stake for Alice and Bob on netuid. - let alice_alpha_stake: u64 = 1_000_000_000; + let alice_alpha_stake = AlphaCurrency::from(1_000_000_000); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &alice, &cold_alice, alpha, alice_alpha_stake, ); - let bob_alpha_stake: u64 = 1_000_000_000; + let bob_alpha_stake = AlphaCurrency::from(1_000_000_000); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &bob, &cold_bob, @@ -1339,18 +1477,18 @@ fn test_get_root_children_drain_with_half_take() { Delegates::::insert(bob, 0); // Lets drain! - let pending_alpha: u64 = 1_000_000_000; - SubtensorModule::drain_pending_emission(alpha, pending_alpha, 0, 0, 0); + let pending_alpha = AlphaCurrency::from(1_000_000_000); + SubtensorModule::drain_pending_emission(alpha, pending_alpha, 0, 0.into(), 0.into()); // Alice and Bob make the same amount. close( - AlphaDividendsPerSubnet::::get(alpha, alice), - pending_alpha / 4, + AlphaDividendsPerSubnet::::get(alpha, alice).into(), + (pending_alpha / 4.into()).into(), 10000, ); close( - AlphaDividendsPerSubnet::::get(alpha, bob), - 3 * (pending_alpha / 4), + AlphaDividendsPerSubnet::::get(alpha, bob).into(), + 3 * u64::from(pending_alpha / 4.into()), 10000, ); }); @@ -1382,14 +1520,14 @@ fn test_get_root_children_drain_with_half_take() { // bob, // )); // // Add stake for Alice and Bob on root. -// let alice_root_stake: u64 = 1_000_000_000; +// let alice_root_stake = AlphaCurrency::from(1_000_000_000); // SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( // &alice, // &cold, // NetUid::ROOT, // alice_root_stake, // ); -// let bob_root_stake: u64 = 1_000_000_000; +// let bob_root_stake = AlphaCurrency::from(1_000_000_000); // SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( // &bob, // &cold, @@ -1397,14 +1535,14 @@ fn test_get_root_children_drain_with_half_take() { // alice_root_stake, // ); // // Add stake for Alice and Bob on netuid. -// let alice_alpha_stake: u64 = 1_000_000_000; +// let alice_alpha_stake = AlphaCurrency::from(1_000_000_000); // SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( // &alice, // &cold, // alpha, // alice_alpha_stake, // ); -// let bob_alpha_stake: u64 = 1_000_000_000; +// let bob_alpha_stake = AlphaCurrency::from(1_000_000_000); // SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( // &bob, // &cold, @@ -1436,8 +1574,8 @@ fn test_get_root_children_drain_with_half_take() { // )); // // Lets drain! -// let pending_alpha: u64 = 1_000_000_000; -// SubtensorModule::drain_pending_emission(alpha, pending_alpha, 0, 0, 0); +// let pending_alpha = AlphaCurrency::from(1_000_000_000); +// SubtensorModule::drain_pending_emission(alpha, pending_alpha, 0, 0.into(), 0.into()); // // Alice and Bob make the same amount. // close( @@ -1466,22 +1604,22 @@ fn test_incentive_to_subnet_owner_is_burned() { let netuid = add_dynamic_network(&subnet_owner_hk, &subnet_owner_ck); let pending_tao: u64 = 1_000_000_000; - let pending_alpha: u64 = 0; // None to valis - let owner_cut: u64 = 0; - let mut incentives: BTreeMap = BTreeMap::new(); + let pending_alpha = AlphaCurrency::ZERO; // None to valis + let owner_cut = AlphaCurrency::ZERO; + let mut incentives: BTreeMap = BTreeMap::new(); // Give incentive to other_hk - incentives.insert(other_hk, 10_000_000); + incentives.insert(other_hk, 10_000_000.into()); // Give incentives to subnet_owner_hk - incentives.insert(subnet_owner_hk, 10_000_000); + incentives.insert(subnet_owner_hk, 10_000_000.into()); // Verify stake before let subnet_owner_stake_before = SubtensorModule::get_stake_for_hotkey_on_subnet(&subnet_owner_hk, netuid); - assert_eq!(subnet_owner_stake_before, 0); + assert_eq!(subnet_owner_stake_before, 0.into()); let other_stake_before = SubtensorModule::get_stake_for_hotkey_on_subnet(&other_hk, netuid); - assert_eq!(other_stake_before, 0); + assert_eq!(other_stake_before, 0.into()); // Distribute dividends and incentives SubtensorModule::distribute_dividends_and_incentives( @@ -1495,27 +1633,27 @@ fn test_incentive_to_subnet_owner_is_burned() { // Verify stake after let subnet_owner_stake_after = SubtensorModule::get_stake_for_hotkey_on_subnet(&subnet_owner_hk, netuid); - assert_eq!(subnet_owner_stake_after, 0); + assert_eq!(subnet_owner_stake_after, 0.into()); let other_stake_after = SubtensorModule::get_stake_for_hotkey_on_subnet(&other_hk, netuid); - assert!(other_stake_after > 0); + assert!(other_stake_after > 0.into()); }); } #[test] fn test_calculate_dividend_distribution_totals() { new_test_ext(1).execute_with(|| { - let mut stake_map: BTreeMap = BTreeMap::new(); + let mut stake_map: BTreeMap = BTreeMap::new(); let mut dividends: BTreeMap = BTreeMap::new(); - let pending_validator_alpha: u64 = 183_123_567_452; + let pending_validator_alpha = AlphaCurrency::from(183_123_567_452); let pending_tao: u64 = 837_120_949_872; let tao_weight: U96F32 = U96F32::saturating_from_num(0.18); // 18% let hotkeys = [U256::from(0), U256::from(1)]; // Stake map and dividends shouldn't matter for this test. - stake_map.insert(hotkeys[0], (4_859_302, 2_342_352)); - stake_map.insert(hotkeys[1], (23_423, 859_273)); + stake_map.insert(hotkeys[0], (4_859_302.into(), 2_342_352.into())); + stake_map.insert(hotkeys[1], (23_423.into(), 859_273.into())); dividends.insert(hotkeys[0], 77_783_738_u64.into()); dividends.insert(hotkeys[1], 19_283_940_u64.into()); @@ -1533,7 +1671,7 @@ fn test_calculate_dividend_distribution_totals() { assert_abs_diff_eq!( total_alpha_dividends.saturating_to_num::(), - pending_validator_alpha, + u64::from(pending_validator_alpha), epsilon = 1_000 ); assert_abs_diff_eq!( @@ -1547,18 +1685,18 @@ fn test_calculate_dividend_distribution_totals() { #[test] fn test_calculate_dividend_distribution_total_only_tao() { new_test_ext(1).execute_with(|| { - let mut stake_map: BTreeMap = BTreeMap::new(); + let mut stake_map: BTreeMap = BTreeMap::new(); let mut dividends: BTreeMap = BTreeMap::new(); - let pending_validator_alpha: u64 = 0; + let pending_validator_alpha = AlphaCurrency::ZERO; let pending_tao: u64 = 837_120_949_872; let tao_weight: U96F32 = U96F32::saturating_from_num(0.18); // 18% let hotkeys = [U256::from(0), U256::from(1)]; // Stake map and dividends shouldn't matter for this test. - stake_map.insert(hotkeys[0], (4_859_302, 2_342_352)); - stake_map.insert(hotkeys[1], (23_423, 859_273)); + stake_map.insert(hotkeys[0], (4_859_302.into(), 2_342_352.into())); + stake_map.insert(hotkeys[1], (23_423.into(), 859_273.into())); dividends.insert(hotkeys[0], 77_783_738_u64.into()); dividends.insert(hotkeys[1], 19_283_940_u64.into()); @@ -1576,7 +1714,7 @@ fn test_calculate_dividend_distribution_total_only_tao() { assert_abs_diff_eq!( total_alpha_dividends.saturating_to_num::(), - pending_validator_alpha, + u64::from(pending_validator_alpha), epsilon = 1_000 ); assert_abs_diff_eq!( @@ -1590,18 +1728,18 @@ fn test_calculate_dividend_distribution_total_only_tao() { #[test] fn test_calculate_dividend_distribution_total_no_tao_weight() { new_test_ext(1).execute_with(|| { - let mut stake_map: BTreeMap = BTreeMap::new(); + let mut stake_map: BTreeMap = BTreeMap::new(); let mut dividends: BTreeMap = BTreeMap::new(); - let pending_validator_alpha: u64 = 183_123_567_452; + let pending_validator_alpha = AlphaCurrency::from(183_123_567_452); let pending_tao: u64 = 0; // If tao weight is 0, then only alpha dividends should be input. let tao_weight: U96F32 = U96F32::saturating_from_num(0.0); // 0% let hotkeys = [U256::from(0), U256::from(1)]; // Stake map and dividends shouldn't matter for this test. - stake_map.insert(hotkeys[0], (4_859_302, 2_342_352)); - stake_map.insert(hotkeys[1], (23_423, 859_273)); + stake_map.insert(hotkeys[0], (4_859_302.into(), 2_342_352.into())); + stake_map.insert(hotkeys[1], (23_423.into(), 859_273.into())); dividends.insert(hotkeys[0], 77_783_738_u64.into()); dividends.insert(hotkeys[1], 19_283_940_u64.into()); @@ -1619,7 +1757,7 @@ fn test_calculate_dividend_distribution_total_no_tao_weight() { assert_abs_diff_eq!( total_alpha_dividends.saturating_to_num::(), - pending_validator_alpha, + u64::from(pending_validator_alpha), epsilon = 1_000 ); assert_abs_diff_eq!( @@ -1633,18 +1771,18 @@ fn test_calculate_dividend_distribution_total_no_tao_weight() { #[test] fn test_calculate_dividend_distribution_total_only_alpha() { new_test_ext(1).execute_with(|| { - let mut stake_map: BTreeMap = BTreeMap::new(); + let mut stake_map: BTreeMap = BTreeMap::new(); let mut dividends: BTreeMap = BTreeMap::new(); - let pending_validator_alpha: u64 = 183_123_567_452; + let pending_validator_alpha = AlphaCurrency::from(183_123_567_452); let pending_tao: u64 = 0; let tao_weight: U96F32 = U96F32::saturating_from_num(0.18); // 18% let hotkeys = [U256::from(0), U256::from(1)]; // Stake map and dividends shouldn't matter for this test. - stake_map.insert(hotkeys[0], (4_859_302, 2_342_352)); - stake_map.insert(hotkeys[1], (23_423, 859_273)); + stake_map.insert(hotkeys[0], (4_859_302.into(), 2_342_352.into())); + stake_map.insert(hotkeys[1], (23_423.into(), 859_273.into())); dividends.insert(hotkeys[0], 77_783_738_u64.into()); dividends.insert(hotkeys[1], 19_283_940_u64.into()); @@ -1662,7 +1800,7 @@ fn test_calculate_dividend_distribution_total_only_alpha() { assert_abs_diff_eq!( total_alpha_dividends.saturating_to_num::(), - pending_validator_alpha, + u64::from(pending_validator_alpha), epsilon = 1_000 ); assert_abs_diff_eq!( @@ -1686,17 +1824,20 @@ fn test_calculate_dividend_and_incentive_distribution() { register_ok_neuron(netuid, hotkey, coldkey, 0); // Give non-zero alpha SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &hotkey, &coldkey, netuid, 1, + &hotkey, + &coldkey, + netuid, + 1.into(), ); - let pending_alpha = 123_456_789; - let pending_validator_alpha = pending_alpha / 2; // Pay half to validators. + let pending_alpha = AlphaCurrency::from(123_456_789); + let pending_validator_alpha = pending_alpha / 2.into(); // Pay half to validators. let pending_tao: u64 = 0; let pending_swapped = 0; // Only alpha output. let tao_weight: U96F32 = U96F32::saturating_from_num(0.0); // 0% // Hotkey, Incentive, Dividend - let hotkey_emission = vec![(hotkey, pending_alpha / 2, pending_alpha / 2)]; + let hotkey_emission = vec![(hotkey, pending_alpha / 2.into(), pending_alpha / 2.into())]; let (incentives, (alpha_dividends, tao_dividends)) = SubtensorModule::calculate_dividend_and_incentive_distribution( @@ -1707,7 +1848,7 @@ fn test_calculate_dividend_and_incentive_distribution() { tao_weight, ); - let incentives_total = incentives.values().sum::(); + let incentives_total = incentives.values().copied().map(u64::from).sum::(); let dividends_total = alpha_dividends .values() .sum::() @@ -1715,7 +1856,7 @@ fn test_calculate_dividend_and_incentive_distribution() { assert_abs_diff_eq!( dividends_total.saturating_add(incentives_total), - pending_alpha, + u64::from(pending_alpha), epsilon = 2 ); }); @@ -1734,16 +1875,19 @@ fn test_calculate_dividend_and_incentive_distribution_all_to_validators() { register_ok_neuron(netuid, hotkey, coldkey, 0); // Give non-zero alpha SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &hotkey, &coldkey, netuid, 1, + &hotkey, + &coldkey, + netuid, + 1.into(), ); - let pending_alpha = 123_456_789; + let pending_alpha = AlphaCurrency::from(123_456_789); let pending_validator_alpha = pending_alpha; // Pay all to validators. let pending_tao: u64 = 0; let tao_weight: U96F32 = U96F32::saturating_from_num(0.0); // 0% // Hotkey, Incentive, Dividend - let hotkey_emission = vec![(hotkey, 0, pending_alpha)]; + let hotkey_emission = vec![(hotkey, 0.into(), pending_alpha)]; let (incentives, (alpha_dividends, tao_dividends)) = SubtensorModule::calculate_dividend_and_incentive_distribution( @@ -1754,14 +1898,14 @@ fn test_calculate_dividend_and_incentive_distribution_all_to_validators() { tao_weight, ); - let incentives_total = incentives.values().sum::(); + let incentives_total = incentives.values().copied().map(u64::from).sum::(); let dividends_total = alpha_dividends .values() .sum::() .saturating_to_num::(); assert_eq!( - dividends_total.saturating_add(incentives_total), + AlphaCurrency::from(dividends_total.saturating_add(incentives_total)), pending_alpha ); }); @@ -1780,12 +1924,15 @@ fn test_calculate_dividends_and_incentives() { register_ok_neuron(netuid, hotkey, coldkey, 0); // Give non-zero alpha SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &hotkey, &coldkey, netuid, 1, + &hotkey, + &coldkey, + netuid, + 1.into(), ); - let divdends: u64 = 123_456_789; - let incentive: u64 = 683_051_923; - let total_emission: u64 = divdends.saturating_add(incentive); + let divdends = AlphaCurrency::from(123_456_789); + let incentive = AlphaCurrency::from(683_051_923); + let total_emission = divdends.saturating_add(incentive); // Hotkey, Incentive, Dividend let hotkey_emission = vec![(hotkey, incentive, divdends)]; @@ -1793,11 +1940,16 @@ fn test_calculate_dividends_and_incentives() { let (incentives, dividends) = SubtensorModule::calculate_dividends_and_incentives(netuid, hotkey_emission); - let incentives_total = incentives.values().sum::(); - let dividends_total = dividends + let incentives_total = incentives .values() - .sum::() - .saturating_to_num::(); + .copied() + .fold(AlphaCurrency::ZERO, |acc, x| acc + x); + let dividends_total = AlphaCurrency::from( + dividends + .values() + .sum::() + .saturating_to_num::(), + ); assert_eq!( dividends_total.saturating_add(incentives_total), @@ -1819,11 +1971,14 @@ fn test_calculate_dividends_and_incentives_only_validators() { register_ok_neuron(netuid, hotkey, coldkey, 0); // Give non-zero alpha SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &hotkey, &coldkey, netuid, 1, + &hotkey, + &coldkey, + netuid, + 1.into(), ); - let divdends: u64 = 123_456_789; - let incentive: u64 = 0; + let divdends = AlphaCurrency::from(123_456_789); + let incentive = AlphaCurrency::ZERO; // Hotkey, Incentive, Dividend let hotkey_emission = vec![(hotkey, incentive, divdends)]; @@ -1831,14 +1986,19 @@ fn test_calculate_dividends_and_incentives_only_validators() { let (incentives, dividends) = SubtensorModule::calculate_dividends_and_incentives(netuid, hotkey_emission); - let incentives_total = incentives.values().sum::(); - let dividends_total = dividends + let incentives_total = incentives .values() - .sum::() - .saturating_to_num::(); + .copied() + .fold(AlphaCurrency::ZERO, |acc, x| acc + x); + let dividends_total = AlphaCurrency::from( + dividends + .values() + .sum::() + .saturating_to_num::(), + ); assert_eq!(dividends_total, divdends); - assert_eq!(incentives_total, 0); + assert_eq!(incentives_total, AlphaCurrency::ZERO); }); } @@ -1855,11 +2015,14 @@ fn test_calculate_dividends_and_incentives_only_miners() { register_ok_neuron(netuid, hotkey, coldkey, 0); // Give non-zero alpha SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &hotkey, &coldkey, netuid, 1, + &hotkey, + &coldkey, + netuid, + 1.into(), ); - let divdends: u64 = 0; - let incentive: u64 = 123_456_789; + let divdends = AlphaCurrency::ZERO; + let incentive = AlphaCurrency::from(123_456_789); // Hotkey, Incentive, Dividend let hotkey_emission = vec![(hotkey, incentive, divdends)]; @@ -1867,11 +2030,16 @@ fn test_calculate_dividends_and_incentives_only_miners() { let (incentives, dividends) = SubtensorModule::calculate_dividends_and_incentives(netuid, hotkey_emission); - let incentives_total = incentives.values().sum::(); - let dividends_total = dividends + let incentives_total = incentives .values() - .sum::() - .saturating_to_num::(); + .copied() + .fold(AlphaCurrency::ZERO, |acc, x| acc + x); + let dividends_total = AlphaCurrency::from( + dividends + .values() + .sum::() + .saturating_to_num::(), + ); assert_eq!(incentives_total, incentive); assert_eq!(dividends_total, divdends); @@ -1884,11 +2052,14 @@ fn test_drain_pending_emission_no_miners_all_drained() { let netuid = add_dynamic_network(&U256::from(1), &U256::from(2)); let hotkey = U256::from(3); let coldkey = U256::from(4); - let init_stake: u64 = 1; + let init_stake = 1; register_ok_neuron(netuid, hotkey, coldkey, 0); // Give non-zero stake SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &hotkey, &coldkey, netuid, init_stake, + &hotkey, + &coldkey, + netuid, + init_stake.into(), ); assert_eq!( SubtensorModule::get_total_stake_for_hotkey(&hotkey), @@ -1899,15 +2070,19 @@ fn test_drain_pending_emission_no_miners_all_drained() { SubtensorModule::set_tao_weight(0); // Set the emission to be 1 million. - let emission: u64 = 1_000_000; + let emission = AlphaCurrency::from(1_000_000); // Run drain pending without any miners. - SubtensorModule::drain_pending_emission(netuid, emission, 0, 0, 0); + SubtensorModule::drain_pending_emission(netuid, emission, 0, 0.into(), 0.into()); // Get the new stake of the hotkey. let new_stake = SubtensorModule::get_total_stake_for_hotkey(&hotkey); // We expect this neuron to get *all* the emission. // Slight epsilon due to rounding (hotkey_take). - assert_abs_diff_eq!(new_stake, emission.saturating_add(init_stake), epsilon = 1); + assert_abs_diff_eq!( + new_stake, + u64::from(emission.saturating_add(init_stake.into())), + epsilon = 1 + ); }); } @@ -1929,7 +2104,10 @@ fn test_drain_pending_emission_zero_emission() { register_ok_neuron(netuid, miner_hk, miner_ck, 0); // Give non-zero stake SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &hotkey, &coldkey, netuid, init_stake, + &hotkey, + &coldkey, + netuid, + init_stake.into(), ); assert_eq!( SubtensorModule::get_total_stake_for_hotkey(&hotkey), @@ -1942,7 +2120,7 @@ fn test_drain_pending_emission_zero_emission() { run_to_block_no_epoch(netuid, 50); // Run epoch for initial setup. - SubtensorModule::epoch(netuid, 0); + SubtensorModule::epoch(netuid, AlphaCurrency::ZERO); // Set weights on miner assert_ok!(SubtensorModule::set_weights( @@ -1960,7 +2138,7 @@ fn test_drain_pending_emission_zero_emission() { Dividends::::remove(netuid); // Set the emission to be ZERO. - SubtensorModule::drain_pending_emission(netuid, 0, 0, 0, 0); + SubtensorModule::drain_pending_emission(netuid, 0.into(), 0, 0.into(), 0.into()); // Get the new stake of the hotkey. let new_stake = SubtensorModule::get_total_stake_for_hotkey(&hotkey); @@ -1999,14 +2177,17 @@ fn test_run_coinbase_not_started() { SubtensorModule::set_weights_set_rate_limit(netuid, 0); let reserve = init_stake * 1000; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); register_ok_neuron(netuid, hotkey, coldkey, 0); register_ok_neuron(netuid, miner_hk, miner_ck, 0); register_ok_neuron(netuid, sn_owner_hk, sn_owner_ck, 0); // Give non-zero stake SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &hotkey, &coldkey, netuid, init_stake, + &hotkey, + &coldkey, + netuid, + init_stake.into(), ); assert_eq!( SubtensorModule::get_total_stake_for_hotkey(&hotkey), @@ -2019,7 +2200,7 @@ fn test_run_coinbase_not_started() { run_to_block_no_epoch(netuid, 30); // Run epoch for initial setup. - SubtensorModule::epoch(netuid, 0); + SubtensorModule::epoch(netuid, AlphaCurrency::ZERO); // Set weights on miner assert_ok!(SubtensorModule::set_weights( @@ -2088,7 +2269,10 @@ fn test_run_coinbase_not_started_start_after() { register_ok_neuron(netuid, sn_owner_hk, sn_owner_ck, 0); // Give non-zero stake SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &hotkey, &coldkey, netuid, init_stake, + &hotkey, + &coldkey, + netuid, + init_stake.into(), ); assert_eq!( SubtensorModule::get_total_stake_for_hotkey(&hotkey), @@ -2101,7 +2285,7 @@ fn test_run_coinbase_not_started_start_after() { run_to_block_no_epoch(netuid, 30); // Run epoch for initial setup. - SubtensorModule::epoch(netuid, 0); + SubtensorModule::epoch(netuid, AlphaCurrency::ZERO); // Set weights on miner assert_ok!(SubtensorModule::set_weights( diff --git a/pallets/subtensor/src/tests/consensus.rs b/pallets/subtensor/src/tests/consensus.rs index b11cd44e06..0afca99445 100644 --- a/pallets/subtensor/src/tests/consensus.rs +++ b/pallets/subtensor/src/tests/consensus.rs @@ -189,7 +189,7 @@ fn init_run_epochs( &U256::from(key), &U256::from(key), netuid, - stake, + stake.into(), ); } assert_eq!(SubtensorModule::get_subnetwork_n(netuid), n); @@ -200,7 +200,7 @@ fn init_run_epochs( SubtensorModule::get_max_allowed_validators(netuid), validators.len() as u16 ); - SubtensorModule::epoch(netuid, 1_000_000_000); // run first epoch to set allowed validators + SubtensorModule::epoch(netuid, 1_000_000_000.into()); // run first epoch to set allowed validators run_to_block(1); // run to next block to ensure weights are set on nodes after their registration block // === Set weights @@ -251,9 +251,9 @@ fn init_run_epochs( let start = Instant::now(); for _ in 0..epochs { if sparse { - SubtensorModule::epoch(netuid, 1_000_000_000); + SubtensorModule::epoch(netuid, 1_000_000_000.into()); } else { - SubtensorModule::epoch_dense(netuid, 1_000_000_000); + SubtensorModule::epoch_dense(netuid, 1_000_000_000.into()); } } let duration = start.elapsed(); diff --git a/pallets/subtensor/src/tests/delegate_info.rs b/pallets/subtensor/src/tests/delegate_info.rs index 8168755439..22b2aab2bf 100644 --- a/pallets/subtensor/src/tests/delegate_info.rs +++ b/pallets/subtensor/src/tests/delegate_info.rs @@ -135,7 +135,7 @@ fn test_get_delegated() { .or_default() .entry(*delegate) .or_default(); - stakes.insert(*netuid, expected_stake); + stakes.insert(*netuid, expected_stake.into()); } } @@ -149,7 +149,7 @@ fn test_get_delegated() { coldkey_stakes_map.get(&delegate_info.delegate_ss58) { if let Some(expected_stake) = expected_under_delegate.get(&netuid.0) { - assert_eq!(u64::from(*staked), *expected_stake); + assert_eq!(u64::from(staked.0), *expected_stake); } else { panic!("Netuid {} not found in expected stake map", netuid.0); }; diff --git a/pallets/subtensor/src/tests/epoch.rs b/pallets/subtensor/src/tests/epoch.rs index 2b8fdac910..6fed5d8ced 100644 --- a/pallets/subtensor/src/tests/epoch.rs +++ b/pallets/subtensor/src/tests/epoch.rs @@ -11,6 +11,7 @@ use frame_support::{assert_err, assert_ok}; use rand::{Rng, SeedableRng, distributions::Uniform, rngs::StdRng, seq::SliceRandom, thread_rng}; use sp_core::{Get, U256}; use substrate_fixed::types::I32F32; +use subtensor_runtime_common::Alpha as AlphaCurrency; use subtensor_swap_interface::SwapHandler; use super::mock::*; @@ -182,7 +183,7 @@ fn init_run_epochs( &U256::from(key), &U256::from(key), netuid, - stake, + stake.into(), ); } assert_eq!(SubtensorModule::get_subnetwork_n(netuid), n); @@ -193,7 +194,7 @@ fn init_run_epochs( SubtensorModule::get_max_allowed_validators(netuid), validators.len() as u16 ); - SubtensorModule::epoch(netuid, 1_000_000_000); // run first epoch to set allowed validators + SubtensorModule::epoch(netuid, 1_000_000_000.into()); // run first epoch to set allowed validators run_to_block(1); // run to next block to ensure weights are set on nodes after their registration block // === Set weights @@ -244,9 +245,9 @@ fn init_run_epochs( let start = Instant::now(); for _ in 0..epochs { if sparse { - SubtensorModule::epoch(netuid, 1_000_000_000); + SubtensorModule::epoch(netuid, 1_000_000_000.into()); } else { - SubtensorModule::epoch_dense(netuid, 1_000_000_000); + SubtensorModule::epoch_dense(netuid, 1_000_000_000.into()); } } let duration = start.elapsed(); @@ -589,7 +590,7 @@ fn test_1_graph() { )); // SubtensorModule::set_weights_for_testing( netuid, i as u16, vec![ ( 0, u16::MAX )]); // doesn't set update status // SubtensorModule::set_bonds_for_testing( netuid, uid, vec![ ( 0, u16::MAX )]); // rather, bonds are calculated in epoch - SubtensorModule::epoch(netuid, 1_000_000_000); + SubtensorModule::epoch(netuid, 1_000_000_000.into()); assert_eq!( SubtensorModule::get_total_stake_for_hotkey(&hotkey), stake_amount @@ -623,7 +624,7 @@ fn test_10_graph() { &hotkey, &coldkey, netuid, - stake_amount, + stake_amount.into(), ); SubtensorModule::append_neuron(netuid, &hotkey, 0); assert_eq!(SubtensorModule::get_subnetwork_n(netuid) - 1, uid); @@ -649,7 +650,7 @@ fn test_10_graph() { )); } // Run the epoch. - SubtensorModule::epoch(netuid, 1_000_000_000); + SubtensorModule::epoch(netuid, 1_000_000_000.into()); // Check return values. for i in 0..n { assert_eq!( @@ -663,7 +664,7 @@ fn test_10_graph() { assert_eq!(SubtensorModule::get_dividends_for_uid(netuid, i as u16), 0); assert_eq!( SubtensorModule::get_emission_for_uid(netuid, i as u16), - 99999999 + 99999999.into() ); } }); @@ -718,7 +719,10 @@ fn test_512_graph() { assert_eq!(SubtensorModule::get_consensus_for_uid(netuid, uid), 0); assert_eq!(SubtensorModule::get_incentive_for_uid(netuid, uid), 0); assert_eq!(SubtensorModule::get_dividends_for_uid(netuid, uid), 1023); // Note D = floor(1 / 64 * 65_535) = 1023 - assert_eq!(SubtensorModule::get_emission_for_uid(netuid, uid), 7812500); // Note E = 0.5 / 200 * 1_000_000_000 = 7_812_500 + assert_eq!( + SubtensorModule::get_emission_for_uid(netuid, uid), + 7812500.into() + ); // Note E = 0.5 / 200 * 1_000_000_000 = 7_812_500 assert_eq!(bonds[uid as usize][validator], 0.0); assert_eq!(bonds[uid as usize][server], I32F32::from_num(65_535)); // Note B_ij = floor(1 / 64 * 65_535) / 65_535 = 1023 / 65_535, then max-upscaled to 65_535 @@ -733,7 +737,10 @@ fn test_512_graph() { assert_eq!(SubtensorModule::get_consensus_for_uid(netuid, uid), 146); // Note C = floor(1 / (512 - 64) * 65_535) = 146 assert_eq!(SubtensorModule::get_incentive_for_uid(netuid, uid), 146); // Note I = floor(1 / (512 - 64) * 65_535) = 146 assert_eq!(SubtensorModule::get_dividends_for_uid(netuid, uid), 0); - assert_eq!(SubtensorModule::get_emission_for_uid(netuid, uid), 1116071); // Note E = floor(0.5 / (512 - 64) * 1_000_000_000) = 1_116_071 + assert_eq!( + SubtensorModule::get_emission_for_uid(netuid, uid), + 1116071.into() + ); // Note E = floor(0.5 / (512 - 64) * 1_000_000_000) = 1_116_071 assert_eq!(bonds[uid as usize][validator], 0.0); assert_eq!(bonds[uid as usize][server], 0.0); } @@ -766,7 +773,7 @@ fn test_512_graph_random_weights() { Vec, Vec, Vec, - Vec, + Vec, Vec, Vec, ) = (vec![], vec![], vec![], vec![], vec![], vec![]); @@ -1016,7 +1023,7 @@ fn test_bonds() { SubtensorModule::add_balance_to_coldkey_account( &U256::from(key), max_stake ); let (nonce, work): (u64, Vec) = SubtensorModule::create_work_for_block_number( netuid, block_number, key * 1_000_000, &U256::from(key)); assert_ok!(SubtensorModule::register(<::RuntimeOrigin>::signed(U256::from(key)), netuid, block_number, nonce, work, U256::from(key), U256::from(key))); - SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &U256::from(key), &U256::from(key), netuid, stakes[key as usize] ); + SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &U256::from(key), &U256::from(key), netuid, stakes[key as usize].into() ); } assert_eq!(SubtensorModule::get_max_allowed_uids(netuid), n); assert_eq!(SubtensorModule::get_subnetwork_n(netuid), n); @@ -1024,15 +1031,15 @@ fn test_bonds() { // === Issue validator permits SubtensorModule::set_max_allowed_validators(netuid, n); assert_eq!( SubtensorModule::get_max_allowed_validators(netuid), n); - SubtensorModule::epoch( netuid, 1_000_000_000 ); // run first epoch to set allowed validators + SubtensorModule::epoch( netuid, 1_000_000_000 .into()); // run first epoch to set allowed validators next_block_no_epoch(netuid); // run to next block to ensure weights are set on nodes after their registration block // === Set weights [val->srv1: 0.1, val->srv2: 0.2, val->srv3: 0.3, val->srv4: 0.4] for uid in 0..(n/2) as u64 { assert_ok!(SubtensorModule::set_weights(RuntimeOrigin::signed(U256::from(uid)), netuid, ((n/2)..n).collect(), vec![ u16::MAX/4, u16::MAX/2, (u16::MAX/4)*3, u16::MAX], 0)); } - if sparse { SubtensorModule::epoch( netuid, 1_000_000_000 ); } - else { SubtensorModule::epoch_dense( netuid, 1_000_000_000 ); } + if sparse { SubtensorModule::epoch( netuid, 1_000_000_000 .into()); } + else { SubtensorModule::epoch_dense( netuid, 1_000_000_000 .into()); } /* n: 8 current_block: 1; activity_cutoff: 5000; Last update: [1, 1, 1, 1, 0, 0, 0, 0] Inactive: [false, false, false, false, false, false, false, false] @@ -1077,8 +1084,8 @@ fn test_bonds() { assert_ok!(SubtensorModule::set_weights(RuntimeOrigin::signed(U256::from(uid)), netuid, vec![uid], vec![u16::MAX], 0)); next_block_no_epoch(netuid); - if sparse { SubtensorModule::epoch( netuid, 1_000_000_000 ); } - else { SubtensorModule::epoch_dense( netuid, 1_000_000_000 ); } + if sparse { SubtensorModule::epoch( netuid, 1_000_000_000 .into()); } + else { SubtensorModule::epoch_dense( netuid, 1_000_000_000.into() ); } /* n: 8 current_block: 2 activity_cutoff: 5000 @@ -1125,8 +1132,8 @@ fn test_bonds() { assert_ok!(SubtensorModule::set_weights(RuntimeOrigin::signed(U256::from(uid)), netuid, vec![uid], vec![u16::MAX], 0)); next_block_no_epoch(netuid); - if sparse { SubtensorModule::epoch( netuid, 1_000_000_000 ); } - else { SubtensorModule::epoch_dense( netuid, 1_000_000_000 ); } + if sparse { SubtensorModule::epoch( netuid, 1_000_000_000 .into()); } + else { SubtensorModule::epoch_dense( netuid, 1_000_000_000.into() ); } /* current_block: 3 W: [[(0, 65535)], [(1, 65535)], [(4, 16383), (5, 32767), (6, 49149), (7, 65535)], [(4, 16383), (5, 32767), (6, 49149), (7, 65535)], [], [], [], []] W (permit): [[(0, 65535)], [(1, 65535)], [(4, 16383), (5, 32767), (6, 49149), (7, 65535)], [(4, 16383), (5, 32767), (6, 49149), (7, 65535)], [], [], [], []] @@ -1162,8 +1169,8 @@ fn test_bonds() { assert_ok!(SubtensorModule::set_weights(RuntimeOrigin::signed(U256::from(uid)), netuid, vec![uid], vec![u16::MAX], 0)); next_block_no_epoch(netuid); - if sparse { SubtensorModule::epoch( netuid, 1_000_000_000 ); } - else { SubtensorModule::epoch_dense( netuid, 1_000_000_000 ); } + if sparse { SubtensorModule::epoch( netuid, 1_000_000_000 .into()); } + else { SubtensorModule::epoch_dense( netuid, 1_000_000_000.into() ); } /* current_block: 4 W: [[(0, 65535)], [(1, 65535)], [(2, 65535)], [(4, 16383), (5, 32767), (6, 49149), (7, 65535)], [], [], [], []] W (permit): [[(0, 65535)], [(1, 65535)], [(2, 65535)], [(4, 16383), (5, 32767), (6, 49149), (7, 65535)], [], [], [], []] @@ -1198,8 +1205,8 @@ fn test_bonds() { assert_ok!(SubtensorModule::set_weights(RuntimeOrigin::signed(U256::from(2)), netuid, vec![7], vec![u16::MAX], 0)); next_block_no_epoch(netuid); - if sparse { SubtensorModule::epoch( netuid, 1_000_000_000 ); } - else { SubtensorModule::epoch_dense( netuid, 1_000_000_000 ); } + if sparse { SubtensorModule::epoch( netuid, 1_000_000_000 .into()); } + else { SubtensorModule::epoch_dense( netuid, 1_000_000_000.into() ); } /* current_block: 5 W: [[(0, 65535)], [(1, 65535)], [(7, 65535)], [(4, 16383), (5, 32767), (6, 49149), (7, 65535)], [], [], [], []] W (permit): [[(0, 65535)], [(1, 65535)], [(7, 65535)], [(4, 16383), (5, 32767), (6, 49149), (7, 65535)], [], [], [], []] @@ -1232,8 +1239,8 @@ fn test_bonds() { next_block_no_epoch(netuid); - if sparse { SubtensorModule::epoch( netuid, 1_000_000_000 ); } - else { SubtensorModule::epoch_dense( netuid, 1_000_000_000 ); } + if sparse { SubtensorModule::epoch( netuid, 1_000_000_000 .into()); } + else { SubtensorModule::epoch_dense( netuid, 1_000_000_000.into() ); } /* current_block: 6 B: [[(4, 12601), (5, 12601), (6, 12601), (7, 10951)], [(4, 28319), (5, 28319), (6, 28319), (7, 24609)], [(4, 49149), (5, 49149), (6, 49149), (7, 49150)], [(4, 65535), (5, 65535), (6, 65535), (7, 65535)], [], [], [], []] B (outdatedmask): [[(4, 12601), (5, 12601), (6, 12601), (7, 10951)], [(4, 28319), (5, 28319), (6, 28319), (7, 24609)], [(4, 49149), (5, 49149), (6, 49149), (7, 49150)], [(4, 65535), (5, 65535), (6, 65535), (7, 65535)], [], [], [], []] @@ -1254,8 +1261,8 @@ fn test_bonds() { next_block_no_epoch(netuid); - if sparse { SubtensorModule::epoch( netuid, 1_000_000_000 ); } - else { SubtensorModule::epoch_dense( netuid, 1_000_000_000 ); } + if sparse { SubtensorModule::epoch( netuid, 1_000_000_000 .into()); } + else { SubtensorModule::epoch_dense( netuid, 1_000_000_000.into() ); } /* current_block: 7 B: [[(4, 12600), (5, 12600), (6, 12600), (7, 9559)], [(4, 28318), (5, 28318), (6, 28318), (7, 21482)], [(4, 49148), (5, 49148), (6, 49148), (7, 49150)], [(4, 65535), (5, 65535), (6, 65535), (7, 65535)], [], [], [], []] B (outdatedmask): [[(4, 12600), (5, 12600), (6, 12600), (7, 9559)], [(4, 28318), (5, 28318), (6, 28318), (7, 21482)], [(4, 49148), (5, 49148), (6, 49148), (7, 49150)], [(4, 65535), (5, 65535), (6, 65535), (7, 65535)], [], [], [], []] @@ -1276,8 +1283,8 @@ fn test_bonds() { next_block_no_epoch(netuid); - if sparse { SubtensorModule::epoch( netuid, 1_000_000_000 ); } - else { SubtensorModule::epoch_dense( netuid, 1_000_000_000 ); } + if sparse { SubtensorModule::epoch( netuid, 1_000_000_000 .into()); } + else { SubtensorModule::epoch_dense( netuid, 1_000_000_000.into() ); } /* current_block: 8 B: [[(4, 12599), (5, 12599), (6, 12599), (7, 8376)], [(4, 28317), (5, 28317), (6, 28317), (7, 18824)], [(4, 49147), (5, 49147), (6, 49147), (7, 49150)], [(4, 65535), (5, 65535), (6, 65535), (7, 65535)], [], [], [], []] B (outdatedmask): [[(4, 12599), (5, 12599), (6, 12599), (7, 8376)], [(4, 28317), (5, 28317), (6, 28317), (7, 18824)], [(4, 49147), (5, 49147), (6, 49147), (7, 49150)], [(4, 65535), (5, 65535), (6, 65535), (7, 65535)], [], [], [], []] @@ -1377,7 +1384,7 @@ fn test_active_stake() { &U256::from(key), &U256::from(key), netuid, - stake, + stake.into(), ); } assert_eq!(SubtensorModule::get_max_allowed_uids(netuid), n); @@ -1386,7 +1393,7 @@ fn test_active_stake() { // === Issue validator permits SubtensorModule::set_max_allowed_validators(netuid, n); assert_eq!(SubtensorModule::get_max_allowed_validators(netuid), n); - SubtensorModule::epoch(netuid, 1_000_000_000); // run first epoch to set allowed validators + SubtensorModule::epoch(netuid, 1_000_000_000.into()); // run first epoch to set allowed validators next_block_no_epoch(netuid); // run to next block to ensure weights are set on nodes after their registration block // === Set weights [val1->srv1: 0.5, val1->srv2: 0.5, val2->srv1: 0.5, val2->srv2: 0.5] @@ -1400,9 +1407,9 @@ fn test_active_stake() { )); } if sparse { - SubtensorModule::epoch(netuid, 1_000_000_000); + SubtensorModule::epoch(netuid, 1_000_000_000.into()); } else { - SubtensorModule::epoch_dense(netuid, 1_000_000_000); + SubtensorModule::epoch_dense(netuid, 1_000_000_000.into()); } let bonds = SubtensorModule::get_bonds(netuid); for uid in 0..n { @@ -1415,7 +1422,7 @@ fn test_active_stake() { } assert_eq!( SubtensorModule::get_emission_for_uid(netuid, uid), - 250000000 + 250000000.into() ); // Note E = 0.5 / (n/2) * 1_000_000_000 = 250_000_000 } for bond in bonds.iter().take((n / 2) as usize) { @@ -1439,9 +1446,9 @@ fn test_active_stake() { 0 )); if sparse { - SubtensorModule::epoch(netuid, 1_000_000_000); + SubtensorModule::epoch(netuid, 1_000_000_000.into()); } else { - SubtensorModule::epoch_dense(netuid, 1_000_000_000); + SubtensorModule::epoch_dense(netuid, 1_000_000_000.into()); } /* current_block: 5002; activity_cutoff: 5000 Last update: [5002, 1, 0, 0]; Inactive: [false, true, true, true]; Block at registration: [0, 0, 0, 0] @@ -1471,7 +1478,10 @@ fn test_active_stake() { P (u16): [65535, 53619, 59577, 59577] */ let bonds = SubtensorModule::get_bonds(netuid); assert_eq!(SubtensorModule::get_dividends_for_uid(netuid, 0), 36044); // Note D = floor((0.5 * 0.9 + 0.1) * 65_535) - assert_eq!(SubtensorModule::get_emission_for_uid(netuid, 0), 274999999); // Note E = 0.5 * 0.55 * 1_000_000_000 = 275_000_000 (discrepancy) + assert_eq!( + SubtensorModule::get_emission_for_uid(netuid, 0), + 274999999.into() + ); // Note E = 0.5 * 0.55 * 1_000_000_000 = 275_000_000 (discrepancy) for server in ((n / 2) as usize)..n as usize { assert_eq!(bonds[0][server], I32F32::from_num(65_535)); // floor(0.55*(2^16-1))/(2^16-1), then max-upscale } @@ -1482,7 +1492,7 @@ fn test_active_stake() { ); // Note D = floor((0.5 * 0.9) * 65_535) assert_eq!( SubtensorModule::get_emission_for_uid(netuid, validator), - 224999999 + 224999999.into() ); // Note E = 0.5 * 0.45 * 1_000_000_000 = 225_000_000 (discrepancy) for server in ((n / 2) as usize)..n as usize { assert_eq!(bonds[validator as usize][server], I32F32::from_num(53619)); @@ -1500,9 +1510,9 @@ fn test_active_stake() { )); run_to_block_no_epoch(netuid, activity_cutoff + 3); // run to block where validator (uid 0, 1) weights become outdated if sparse { - SubtensorModule::epoch(netuid, 1_000_000_000); + SubtensorModule::epoch(netuid, 1_000_000_000.into()); } else { - SubtensorModule::epoch_dense(netuid, 1_000_000_000); + SubtensorModule::epoch_dense(netuid, 1_000_000_000.into()); } /* current_block: 5003; activity_cutoff: 5000 Last update: [5002, 5002, 0, 0]; Inactive: [false, false, true, true]; Block at registration: [0, 0, 0, 0] @@ -1532,12 +1542,18 @@ fn test_active_stake() { P (u16): [65535, 54711, 60123, 60123] */ let bonds = SubtensorModule::get_bonds(netuid); assert_eq!(SubtensorModule::get_dividends_for_uid(netuid, 0), 35716); // Note D = floor((0.55 * 0.9 + 0.5 * 0.1) * 65_535) - assert_eq!(SubtensorModule::get_emission_for_uid(netuid, 0), 272501132); // Note E = 0.5 * (0.55 * 0.9 + 0.5 * 0.1) * 1_000_000_000 = 272_500_000 (discrepancy) + assert_eq!( + SubtensorModule::get_emission_for_uid(netuid, 0), + 272501132.into() + ); // Note E = 0.5 * (0.55 * 0.9 + 0.5 * 0.1) * 1_000_000_000 = 272_500_000 (discrepancy) for server in ((n / 2) as usize)..n as usize { assert_eq!(bonds[0][server], I32F32::from_num(65_535)); // floor((0.55 * 0.9 + 0.5 * 0.1)*(2^16-1))/(2^16-1), then max-upscale } assert_eq!(SubtensorModule::get_dividends_for_uid(netuid, 1), 29818); // Note D = floor((0.45 * 0.9 + 0.5 * 0.1) * 65_535) - assert_eq!(SubtensorModule::get_emission_for_uid(netuid, 1), 227498866); // Note E = 0.5 * (0.45 * 0.9 + 0.5 * 0.1) * 1_000_000_000 = 227_500_000 (discrepancy) + assert_eq!( + SubtensorModule::get_emission_for_uid(netuid, 1), + 227498866.into() + ); // Note E = 0.5 * (0.45 * 0.9 + 0.5 * 0.1) * 1_000_000_000 = 227_500_000 (discrepancy) for server in ((n / 2) as usize)..n as usize { assert_eq!(bonds[1][server], I32F32::from_num(54712)); // floor((0.45 * 0.9 + 0.5 * 0.1)/(0.55 * 0.9 + 0.5 * 0.1)*(2^16-1)) } @@ -1586,7 +1602,7 @@ fn test_outdated_weights() { &U256::from(key), &U256::from(key), netuid, - stake, + stake.into(), ); } assert_eq!(SubtensorModule::get_subnetwork_n(netuid), n); @@ -1595,7 +1611,7 @@ fn test_outdated_weights() { // === Issue validator permits SubtensorModule::set_max_allowed_validators(netuid, n); assert_eq!(SubtensorModule::get_max_allowed_validators(netuid), n); - SubtensorModule::epoch(netuid, 1_000_000_000); // run first epoch to set allowed validators + SubtensorModule::epoch(netuid, 1_000_000_000.into()); // run first epoch to set allowed validators assert_eq!(SubtensorModule::get_registrations_this_block(netuid), 4); block_number = next_block_no_epoch(netuid); // run to next block to ensure weights are set on nodes after their registration block assert_eq!(SubtensorModule::get_registrations_this_block(netuid), 0); @@ -1620,9 +1636,9 @@ fn test_outdated_weights() { )); // server self-weight } if sparse { - SubtensorModule::epoch(netuid, 1_000_000_000); + SubtensorModule::epoch(netuid, 1_000_000_000.into()); } else { - SubtensorModule::epoch_dense(netuid, 1_000_000_000); + SubtensorModule::epoch_dense(netuid, 1_000_000_000.into()); } /* current_block: 1; activity_cutoff: 5000 Last update: [1, 1, 1, 1]; Inactive: [false, false, false, false]; Block at registration: [0, 0, 0, 0] @@ -1689,9 +1705,9 @@ fn test_outdated_weights() { 0 )); if sparse { - SubtensorModule::epoch(netuid, 1_000_000_000); + SubtensorModule::epoch(netuid, 1_000_000_000.into()); } else { - SubtensorModule::epoch_dense(netuid, 1_000_000_000); + SubtensorModule::epoch_dense(netuid, 1_000_000_000.into()); } /* current_block: 2; activity_cutoff: 5000 Last update: [2, 1, 1, 1]; Inactive: [false, false, false, false]; Block at registration: [0, 0, 0, 1] @@ -1725,7 +1741,10 @@ fn test_outdated_weights() { P (u16): [32767, 32767, 65535, 0] */ let bonds = SubtensorModule::get_bonds(netuid); assert_eq!(SubtensorModule::get_dividends_for_uid(netuid, 0), 32767); // Note D = floor(0.5 * 65_535) - assert_eq!(SubtensorModule::get_emission_for_uid(netuid, 0), 250000000); // Note E = 0.5 * 0.5 * 1_000_000_000 = 249311245 + assert_eq!( + SubtensorModule::get_emission_for_uid(netuid, 0), + 250000000.into() + ); // Note E = 0.5 * 0.5 * 1_000_000_000 = 249311245 assert_eq!(bonds[0][2], I32F32::from_num(65_535)); // floor(0.5*(2^16-1))/(2^16-1), then max-upscale assert_eq!(bonds[0][3], I32F32::from_num(65_535)); // only uid0 has updated weights for new reg }); @@ -1773,16 +1792,16 @@ fn test_zero_weights() { &U256::from(validator), &U256::from(validator), netuid, - stake, + stake.into(), ); } assert_eq!(SubtensorModule::get_subnetwork_n(netuid), n); // === No weights if sparse { - SubtensorModule::epoch(netuid, 1_000_000_000); + SubtensorModule::epoch(netuid, 1_000_000_000.into()); } else { - SubtensorModule::epoch_dense(netuid, 1_000_000_000); + SubtensorModule::epoch_dense(netuid, 1_000_000_000.into()); } /* current_block: 0; activity_cutoff: 5000; Last update: [0, 0]; Inactive: [false, false] S: [1, 0]; S (mask): [1, 0]; S (mask+norm): [1, 0]; Block at registration: [0, 0] @@ -1794,11 +1813,14 @@ fn test_zero_weights() { for validator in 0..(n / 2) { assert_eq!( SubtensorModule::get_emission_for_uid(netuid, validator), - 1000000000 + 1000000000.into() ); // Note E = 1 * 1_000_000_000 } for server in (n / 2)..n { - assert_eq!(SubtensorModule::get_emission_for_uid(netuid, server), 0); + assert_eq!( + SubtensorModule::get_emission_for_uid(netuid, server), + 0.into() + ); // no stake } run_to_block(1); @@ -1815,9 +1837,9 @@ fn test_zero_weights() { )); // server self-weight } if sparse { - SubtensorModule::epoch(netuid, 1_000_000_000); + SubtensorModule::epoch(netuid, 1_000_000_000.into()); } else { - SubtensorModule::epoch_dense(netuid, 1_000_000_000); + SubtensorModule::epoch_dense(netuid, 1_000_000_000.into()); } /* current_block: 1; activity_cutoff: 5000; Last update: [0, 1]; Inactive: [false, false] S: [1, 0]; S (mask): [1, 0]; S (mask+norm): [1, 0]; Block at registration: [0, 0] @@ -1830,11 +1852,14 @@ fn test_zero_weights() { for validator in 0..(n / 2) { assert_eq!( SubtensorModule::get_emission_for_uid(netuid, validator), - 1000000000 + 1000000000.into() ); // Note E = 1 * 1_000_000_000 } for server in (n / 2)..n { - assert_eq!(SubtensorModule::get_emission_for_uid(netuid, server), 0); + assert_eq!( + SubtensorModule::get_emission_for_uid(netuid, server), + 0.into() + ); // no stake } run_to_block(2); @@ -1871,9 +1896,9 @@ fn test_zero_weights() { )); } if sparse { - SubtensorModule::epoch(netuid, 1_000_000_000); + SubtensorModule::epoch(netuid, 1_000_000_000.into()); } else { - SubtensorModule::epoch_dense(netuid, 1_000_000_000); + SubtensorModule::epoch_dense(netuid, 1_000_000_000.into()); } /* current_block: 2; activity_cutoff: 5000; Last update: [2, 1]; Inactive: [false, false]; S: [1, 0]; S (mask): [1, 0]; S (mask+norm): [1, 0]; Block at registration: [0, 2]; @@ -1885,11 +1910,14 @@ fn test_zero_weights() { for validator in 0..(n / 2) { assert_eq!( SubtensorModule::get_emission_for_uid(netuid, validator), - 1000000000 + 1000000000.into() ); // Note E = 1 * 1_000_000_000 } for server in (n / 2)..n { - assert_eq!(SubtensorModule::get_emission_for_uid(netuid, server), 0); + assert_eq!( + SubtensorModule::get_emission_for_uid(netuid, server), + 0.into() + ); // no stake } run_to_block(3); @@ -1905,9 +1933,9 @@ fn test_zero_weights() { )); } if sparse { - SubtensorModule::epoch(netuid, 1_000_000_000); + SubtensorModule::epoch(netuid, 1_000_000_000.into()); } else { - SubtensorModule::epoch_dense(netuid, 1_000_000_000); + SubtensorModule::epoch_dense(netuid, 1_000_000_000.into()); } /* current_block: 3; activity_cutoff: 5000; Last update: [3, 1]; Inactive: [false, false]; S: [1, 0]; S (mask): [1, 0]; S (mask+norm): [1, 0]; Block at registration: [0, 2]; @@ -1919,7 +1947,7 @@ fn test_zero_weights() { for validator in 0..n { assert_eq!( SubtensorModule::get_emission_for_uid(netuid, validator), - 1000000000 / (n as u64) + (1000000000 / (n as u64)).into() ); // Note E = 1/2 * 1_000_000_000 } }); @@ -1968,7 +1996,7 @@ fn test_deregistered_miner_bonds() { &U256::from(key), &U256::from(key), netuid, - stake, + stake.into(), ); } assert_eq!(SubtensorModule::get_subnetwork_n(netuid), n); @@ -1977,7 +2005,7 @@ fn test_deregistered_miner_bonds() { // === Issue validator permits SubtensorModule::set_max_allowed_validators(netuid, n); assert_eq!(SubtensorModule::get_max_allowed_validators(netuid), n); - SubtensorModule::epoch(netuid, 1_000_000_000); // run first epoch to set allowed validators + SubtensorModule::epoch(netuid, 1_000_000_000.into()); // run first epoch to set allowed validators assert_eq!(SubtensorModule::get_registrations_this_block(netuid), 4); next_block(); // run to next block to ensure weights are set on nodes after their registration block assert_eq!(SubtensorModule::get_registrations_this_block(netuid), 0); @@ -2004,9 +2032,9 @@ fn test_deregistered_miner_bonds() { SubtensorModule::set_tempo(netuid, 2); // Run epoch if sparse { - SubtensorModule::epoch(netuid, 1_000_000_000); + SubtensorModule::epoch(netuid, 1_000_000_000.into()); } else { - SubtensorModule::epoch_dense(netuid, 1_000_000_000); + SubtensorModule::epoch_dense(netuid, 1_000_000_000.into()); } // Check the bond values for the servers @@ -2078,9 +2106,9 @@ fn test_deregistered_miner_bonds() { SubtensorModule::set_tempo(netuid, 2); // Run epoch again. if sparse { - SubtensorModule::epoch(netuid, 1_000_000_000); + SubtensorModule::epoch(netuid, 1_000_000_000.into()); } else { - SubtensorModule::epoch_dense(netuid, 1_000_000_000); + SubtensorModule::epoch_dense(netuid, 1_000_000_000.into()); } // Check the bond values for the servers @@ -2171,7 +2199,7 @@ fn test_validator_permits() { &U256::from(key), &U256::from(key), netuid, - stake[key as usize], + stake[key as usize].into(), ); } assert_eq!(SubtensorModule::get_subnetwork_n(netuid), network_n as u16); @@ -2182,7 +2210,7 @@ fn test_validator_permits() { SubtensorModule::get_max_allowed_validators(netuid), validators_n as u16 ); - SubtensorModule::epoch(netuid, 1_000_000_000); // run first epoch to set allowed validators + SubtensorModule::epoch(netuid, 1_000_000_000.into()); // run first epoch to set allowed validators for validator in &validators { assert_eq!( stake[*validator as usize] >= min_stake, @@ -2206,13 +2234,13 @@ fn test_validator_permits() { &(U256::from(*server as u64)), &(U256::from(*server as u64)), netuid, - 2 * network_n as u64, + (2 * network_n as u64).into(), ); } // === Update validator permits run_to_block(1); - SubtensorModule::epoch(netuid, 1_000_000_000); + SubtensorModule::epoch(netuid, 1_000_000_000.into()); // === Check that servers now own permits instead of the validator uids for validator in &validators { @@ -2458,7 +2486,7 @@ fn test_can_set_self_weight_as_subnet_owner() { &subnet_owner_hotkey, &subnet_owner_coldkey, netuid, - stake, + stake.into(), ); // Give vpermits to owner hotkey ONLY @@ -2474,7 +2502,7 @@ fn test_can_set_self_weight_as_subnet_owner() { LastUpdate::::insert(netuid, vec![2, 0]); // Run epoch - let hotkey_emission: Vec<(U256, u64, u64)> = SubtensorModule::epoch(netuid, to_emit); + let hotkey_emission = SubtensorModule::epoch(netuid, to_emit.into()); // hotkey_emission is [(hotkey, incentive, dividend)] assert_eq!(hotkey_emission.len(), 2); @@ -2483,8 +2511,8 @@ fn test_can_set_self_weight_as_subnet_owner() { log::debug!("hotkey_emission: {:?}", hotkey_emission); // Both should have received incentive emission - assert!(hotkey_emission[0].1 > 0); - assert!(hotkey_emission[1].1 > 0); + assert!(hotkey_emission[0].1 > 0.into()); + assert!(hotkey_emission[1].1 > 0.into()); // Their incentive should be equal assert_eq!(hotkey_emission[0].1, hotkey_emission[1].1); @@ -2503,25 +2531,30 @@ fn test_epoch_outputs_single_staker_registered_no_weights() { register_ok_neuron(netuid, hotkey, coldkey, 0); // Give non-zero alpha SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &hotkey, &coldkey, netuid, 1, + &hotkey, + &coldkey, + netuid, + 1.into(), ); - let pending_alpha: u64 = 1_000_000_000; - let hotkey_emission: Vec<(U256, u64, u64)> = SubtensorModule::epoch(netuid, pending_alpha); + let pending_alpha = AlphaCurrency::from(1_000_000_000); + let hotkey_emission = SubtensorModule::epoch(netuid, pending_alpha); - let sum_incentives: u64 = hotkey_emission + let sum_incentives = hotkey_emission .iter() .map(|(_, incentive, _)| incentive) - .sum(); - let sum_dividends: u64 = hotkey_emission + .copied() + .fold(AlphaCurrency::ZERO, |acc, x| acc + x); + let sum_dividends: AlphaCurrency = hotkey_emission .iter() .map(|(_, _, dividend)| dividend) - .sum(); + .copied() + .fold(AlphaCurrency::ZERO, |acc, x| acc + x); assert_abs_diff_eq!( sum_incentives.saturating_add(sum_dividends), pending_alpha, - epsilon = 1_000 + epsilon = 1_000.into() ); }); } @@ -2684,7 +2717,7 @@ fn setup_yuma_3_scenario(netuid: NetUid, n: u16, sparse: bool, max_stake: u64, s &U256::from(key), &U256::from(key), netuid, - stakes[key as usize], + stakes[key as usize].into(), ); } assert_eq!(SubtensorModule::get_max_allowed_uids(netuid), n); @@ -2709,9 +2742,9 @@ fn setup_yuma_3_scenario(netuid: NetUid, n: u16, sparse: bool, max_stake: u64, s fn run_epoch(netuid: NetUid, sparse: bool) { next_block_no_epoch(netuid); if sparse { - SubtensorModule::epoch(netuid, 1_000_000_000); + SubtensorModule::epoch(netuid, 1_000_000_000.into()); } else { - SubtensorModule::epoch_dense(netuid, 1_000_000_000); + SubtensorModule::epoch_dense(netuid, 1_000_000_000.into()); } } diff --git a/pallets/subtensor/src/tests/migration.rs b/pallets/subtensor/src/tests/migration.rs index adb4601724..5bcad233d9 100644 --- a/pallets/subtensor/src/tests/migration.rs +++ b/pallets/subtensor/src/tests/migration.rs @@ -476,11 +476,11 @@ fn test_migrate_remove_zero_total_hotkey_alpha() { let hotkey_nonzero = U256::from(101u64); // Insert one zero-alpha entry and one non-zero entry - TotalHotkeyAlpha::::insert(hotkey_zero, netuid, 0u64); - TotalHotkeyAlpha::::insert(hotkey_nonzero, netuid, 123u64); + TotalHotkeyAlpha::::insert(hotkey_zero, netuid, AlphaCurrency::ZERO); + TotalHotkeyAlpha::::insert(hotkey_nonzero, netuid, AlphaCurrency::from(123)); - assert_eq!(TotalHotkeyAlpha::::get(hotkey_zero, netuid), 0u64); - assert_eq!(TotalHotkeyAlpha::::get(hotkey_nonzero, netuid), 123u64); + assert_eq!(TotalHotkeyAlpha::::get(hotkey_zero, netuid), AlphaCurrency::ZERO); + assert_eq!(TotalHotkeyAlpha::::get(hotkey_nonzero, netuid), AlphaCurrency::from(123)); assert!( !HasMigrationRun::::get(MIGRATION_NAME.as_bytes().to_vec()), @@ -499,7 +499,7 @@ fn test_migrate_remove_zero_total_hotkey_alpha() { "Zero-alpha entry should have been removed." ); - assert_eq!(TotalHotkeyAlpha::::get(hotkey_nonzero, netuid), 123u64); + assert_eq!(TotalHotkeyAlpha::::get(hotkey_nonzero, netuid), AlphaCurrency::from(123)); assert!( !weight.is_zero(), diff --git a/pallets/subtensor/src/tests/mock.rs b/pallets/subtensor/src/tests/mock.rs index d47fbc1ea6..3b0d47c2ae 100644 --- a/pallets/subtensor/src/tests/mock.rs +++ b/pallets/subtensor/src/tests/mock.rs @@ -919,14 +919,14 @@ pub fn increase_stake_on_hotkey_account(hotkey: &U256, increment: u64, netuid: N ); } -pub(crate) fn setup_reserves(netuid: NetUid, tao: u64, alpha: u64) { +pub(crate) fn setup_reserves(netuid: NetUid, tao: u64, alpha: AlphaCurrency) { SubnetTAO::::set(netuid, tao); SubnetAlphaIn::::set(netuid, alpha); } -pub(crate) fn swap_tao_to_alpha(netuid: NetUid, tao: u64) -> (u64, u64) { +pub(crate) fn swap_tao_to_alpha(netuid: NetUid, tao: u64) -> (AlphaCurrency, u64) { if netuid.is_root() { - return (tao, 0); + return (tao.into(), 0); } let result = ::SwapInterface::swap( @@ -944,12 +944,12 @@ pub(crate) fn swap_tao_to_alpha(netuid: NetUid, tao: u64) -> (u64, u64) { // we don't want to have silent 0 comparissons in tests assert!(result.amount_paid_out > 0); - (result.amount_paid_out, result.fee_paid) + (result.amount_paid_out.into(), result.fee_paid) } -pub(crate) fn swap_alpha_to_tao(netuid: NetUid, alpha: u64) -> (u64, u64) { +pub(crate) fn swap_alpha_to_tao(netuid: NetUid, alpha: AlphaCurrency) -> (u64, u64) { if netuid.is_root() { - return (alpha, 0); + return (alpha.into(), 0); } println!( @@ -960,7 +960,7 @@ pub(crate) fn swap_alpha_to_tao(netuid: NetUid, alpha: u64) -> (u64, u64) { let result = ::SwapInterface::swap( netuid.into(), OrderType::Sell, - alpha, + alpha.into(), ::SwapInterface::min_price(), true, ); diff --git a/pallets/subtensor/src/tests/move_stake.rs b/pallets/subtensor/src/tests/move_stake.rs index 34b03da6af..93d0f87eaf 100644 --- a/pallets/subtensor/src/tests/move_stake.rs +++ b/pallets/subtensor/src/tests/move_stake.rs @@ -62,7 +62,7 @@ fn test_do_move_success() { &coldkey, netuid ), - 0 + AlphaCurrency::ZERO ); assert_abs_diff_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( @@ -71,7 +71,7 @@ fn test_do_move_success() { netuid ), expected_alpha, - epsilon = 1000 + epsilon = 1000.into() ); }); } @@ -91,8 +91,16 @@ fn test_do_move_different_subnets() { let destination_hotkey = U256::from(3); let stake_amount = DefaultMinStake::::get() * 10; - mock::setup_reserves(origin_netuid, stake_amount * 100, stake_amount * 100); - mock::setup_reserves(destination_netuid, stake_amount * 100, stake_amount * 100); + mock::setup_reserves( + origin_netuid, + stake_amount * 100, + (stake_amount * 100).into(), + ); + mock::setup_reserves( + destination_netuid, + stake_amount * 100, + (stake_amount * 100).into(), + ); // Set up initial stake and subnets SubtensorModule::create_account_if_non_existent(&coldkey, &origin_hotkey); @@ -128,18 +136,20 @@ fn test_do_move_different_subnets() { &coldkey, origin_netuid ), - 0 + AlphaCurrency::ZERO + ); + let fee = ::SwapInterface::approx_fee_amount( + destination_netuid.into(), + alpha.into(), ); - let fee = - ::SwapInterface::approx_fee_amount(destination_netuid.into(), alpha); assert_abs_diff_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( &destination_hotkey, &coldkey, destination_netuid ), - alpha - (2 * fee), - epsilon = alpha / 1000 + alpha - (AlphaCurrency::from(2) * fee.into()), + epsilon = alpha / 1000.into() ); }); } @@ -160,7 +170,7 @@ fn test_do_move_nonexistent_subnet() { let stake_amount = 1_000_000; let reserve = stake_amount * 1000; - mock::setup_reserves(origin_netuid, reserve, reserve); + mock::setup_reserves(origin_netuid, reserve, reserve.into()); // Set up initial stake SubtensorModule::stake_into_subnet( @@ -223,7 +233,7 @@ fn test_do_move_nonexistent_origin_hotkey() { destination_hotkey, netuid, netuid, - 123 + 123.into() ), Error::::HotKeyAccountNotExists ); @@ -235,7 +245,7 @@ fn test_do_move_nonexistent_origin_hotkey() { &coldkey, netuid ), - 0 + AlphaCurrency::ZERO ); assert_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( @@ -243,7 +253,7 @@ fn test_do_move_nonexistent_origin_hotkey() { &coldkey, netuid ), - 0 + AlphaCurrency::ZERO ); }); } @@ -261,7 +271,7 @@ fn test_do_move_nonexistent_destination_hotkey() { let stake_amount = 1_000_000; let reserve = stake_amount * 1000; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); // Set up initial stake SubtensorModule::create_account_if_non_existent(&coldkey, &origin_hotkey); @@ -304,7 +314,7 @@ fn test_do_move_nonexistent_destination_hotkey() { &coldkey, netuid ), - 0 + AlphaCurrency::ZERO ); }); } @@ -323,7 +333,7 @@ fn test_do_move_all_stake() { let destination_hotkey = U256::from(3); let stake_amount = DefaultMinStake::::get() * 10; - mock::setup_reserves(netuid, stake_amount * 10, stake_amount * 10); + mock::setup_reserves(netuid, stake_amount * 10, (stake_amount * 10).into()); // Set up initial stake SubtensorModule::stake_into_subnet( @@ -359,17 +369,17 @@ fn test_do_move_all_stake() { &coldkey, netuid ), - 0 + AlphaCurrency::ZERO ); - let fee = ::SwapInterface::approx_fee_amount(netuid.into(), alpha); + let fee = ::SwapInterface::approx_fee_amount(netuid.into(), alpha.into()); assert_abs_diff_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( &destination_hotkey, &coldkey, netuid ), - alpha - (2 * fee), - epsilon = alpha / 1000 + alpha - (AlphaCurrency::from(2) * fee.into()), + epsilon = alpha / 1000.into() ); }); } @@ -384,7 +394,7 @@ fn test_do_move_half_stake() { let origin_hotkey = U256::from(2); let destination_hotkey = U256::from(3); let stake_amount = DefaultMinStake::::get() * 10; - mock::setup_reserves(netuid, stake_amount * 100, stake_amount * 100); + mock::setup_reserves(netuid, stake_amount * 100, (stake_amount * 100).into()); // Set up initial stake SubtensorModule::stake_into_subnet( @@ -410,7 +420,7 @@ fn test_do_move_half_stake() { destination_hotkey, netuid, netuid, - alpha / 2, + alpha / 2.into(), )); // Check that all stake was moved @@ -420,18 +430,18 @@ fn test_do_move_half_stake() { &coldkey, netuid ), - alpha / 2, - epsilon = alpha / 1000 + alpha / 2.into(), + epsilon = alpha / 1000.into() ); - let fee = ::SwapInterface::approx_fee_amount(netuid.into(), alpha); + let fee = ::SwapInterface::approx_fee_amount(netuid.into(), alpha.into()); assert_abs_diff_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( &destination_hotkey, &coldkey, netuid ), - alpha / 2 - fee, - epsilon = alpha / 1000 + alpha / 2.into() - fee.into(), + epsilon = alpha / 1000.into() ); }); } @@ -486,7 +496,7 @@ fn test_do_move_partial_stake() { &coldkey, netuid ), - 0 + AlphaCurrency::ZERO ); assert_abs_diff_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( @@ -495,7 +505,7 @@ fn test_do_move_partial_stake() { netuid ), expected_alpha, - epsilon = 1000 + epsilon = 1000.into() ); }); } @@ -527,7 +537,7 @@ fn test_do_move_multiple_times() { .unwrap(); // Move stake multiple times - let mut expected_alpha: u64 = 0; + let mut expected_alpha = AlphaCurrency::ZERO; for _ in 0..3 { let alpha1 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( &hotkey1, &coldkey, netuid, @@ -560,11 +570,11 @@ fn test_do_move_multiple_times() { assert_abs_diff_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey1, &coldkey, netuid), expected_alpha, - epsilon = 1000, + epsilon = 1000.into(), ); assert_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey2, &coldkey, netuid), - 0 + AlphaCurrency::ZERO ); }); } @@ -583,7 +593,7 @@ fn test_do_move_wrong_origin() { let stake_amount = DefaultMinStake::::get() * 10; let reserve = stake_amount * 1000; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); // Set up initial stake SubtensorModule::stake_into_subnet( @@ -631,7 +641,7 @@ fn test_do_move_wrong_origin() { &coldkey, netuid ), - 0 + AlphaCurrency::ZERO ); }); } @@ -793,7 +803,7 @@ fn test_do_move_storage_updates() { &coldkey, origin_netuid ), - 0 + AlphaCurrency::ZERO ); assert_abs_diff_eq!( @@ -803,7 +813,7 @@ fn test_do_move_storage_updates() { destination_netuid ), alpha2, - epsilon = 2 + epsilon = 2.into() ); }); } @@ -828,7 +838,7 @@ fn test_do_move_max_values() { // Add lots of liquidity to bypass low liquidity check let reserve = u64::MAX / 1000; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); SubtensorModule::stake_into_subnet( &origin_hotkey, @@ -862,9 +872,9 @@ fn test_do_move_max_values() { &coldkey, netuid ), - 0 + AlphaCurrency::ZERO ); - let alpha_after_fee = alpha - fee; + let alpha_after_fee = alpha - fee.into(); assert_abs_diff_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( &destination_hotkey, @@ -872,7 +882,7 @@ fn test_do_move_max_values() { netuid ), alpha_after_fee, - epsilon = alpha_after_fee / 100_000 + epsilon = alpha_after_fee / 100_000.into() ); }); } @@ -909,7 +919,7 @@ fn test_moving_too_little_unstakes() { hotkey_account_id, netuid, netuid2, - 1 + 1.into() ), Error::::AmountTooLow ); @@ -966,7 +976,7 @@ fn test_do_transfer_success() { &origin_coldkey, netuid ), - 0 + AlphaCurrency::ZERO ); assert_abs_diff_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( @@ -975,7 +985,7 @@ fn test_do_transfer_success() { netuid ), expected_alpha, - epsilon = 1000 + epsilon = 1000.into() ); }); } @@ -996,7 +1006,7 @@ fn test_do_transfer_nonexistent_subnet() { hotkey, nonexistent_netuid, nonexistent_netuid, - stake_amount + stake_amount.into() ), Error::::SubnetNotExists ); @@ -1021,7 +1031,7 @@ fn test_do_transfer_nonexistent_hotkey() { nonexistent_hotkey, netuid, netuid, - 100 + 100.into() ), Error::::HotKeyAccountNotExists ); @@ -1058,7 +1068,7 @@ fn test_do_transfer_insufficient_stake() { hotkey, netuid, netuid, - alpha + alpha.into() ), Error::::NotEnoughStakeToWithdraw ); @@ -1097,7 +1107,7 @@ fn test_do_transfer_wrong_origin() { hotkey, netuid, netuid, - stake_amount + stake_amount.into() ), Error::::NotEnoughStakeToWithdraw ); @@ -1133,7 +1143,7 @@ fn test_do_transfer_minimum_stake_check() { hotkey, netuid, netuid, - 1 + 1.into() ), Error::::AmountTooLow ); @@ -1198,7 +1208,7 @@ fn test_do_transfer_different_subnets() { &origin_coldkey, origin_netuid ), - 0 + AlphaCurrency::ZERO ); // 8. Verify stake ended up in destination subnet for destination coldkey. @@ -1209,7 +1219,7 @@ fn test_do_transfer_different_subnets() { destination_netuid, ), expected_alpha, - epsilon = 1000 + epsilon = 1000.into() ); }); } @@ -1257,7 +1267,7 @@ fn test_do_swap_success() { &coldkey, origin_netuid ), - 0 + AlphaCurrency::ZERO ); let alpha_after = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( @@ -1266,7 +1276,7 @@ fn test_do_swap_success() { destination_netuid, ); - assert_abs_diff_eq!(alpha_after, expected_alpha, epsilon = 1000); + assert_abs_diff_eq!(alpha_after, expected_alpha, epsilon = 1000.into()); }); } @@ -1287,7 +1297,7 @@ fn test_do_swap_nonexistent_subnet() { hotkey, nonexistent_netuid1, nonexistent_netuid2, - stake_amount + stake_amount.into() ), Error::::SubnetNotExists ); @@ -1312,7 +1322,7 @@ fn test_do_swap_nonexistent_hotkey() { nonexistent_hotkey, netuid1, netuid2, - stake_amount + stake_amount.into() ), Error::::HotKeyAccountNotExists ); @@ -1348,7 +1358,7 @@ fn test_do_swap_insufficient_stake() { hotkey, netuid1, netuid2, - attempted_swap + attempted_swap.into() ), Error::::NotEnoughStakeToWithdraw ); @@ -1384,7 +1394,7 @@ fn test_do_swap_wrong_origin() { hotkey, netuid1, netuid2, - stake_amount + stake_amount.into() ), Error::::NotEnoughStakeToWithdraw ); @@ -1420,7 +1430,7 @@ fn test_do_swap_minimum_stake_check() { hotkey, netuid1, netuid2, - swap_amount + swap_amount.into() ), Error::::AmountTooLow ); @@ -1490,7 +1500,7 @@ fn test_do_swap_partial_stake() { ) .unwrap(); - let swap_amount = total_stake / 2; + let swap_amount = AlphaCurrency::from(total_stake / 2); let (tao_equivalent, _) = mock::swap_alpha_to_tao(origin_netuid, swap_amount); let (expected_alpha, _) = mock::swap_tao_to_alpha(destination_netuid, tao_equivalent); assert_ok!(SubtensorModule::do_swap_stake( @@ -1508,7 +1518,7 @@ fn test_do_swap_partial_stake() { origin_netuid ), expected_alpha, - epsilon = 1000 + epsilon = 1000.into() ); }); } @@ -1556,7 +1566,7 @@ fn test_do_swap_storage_updates() { &coldkey, origin_netuid ), - 0 + AlphaCurrency::ZERO ); assert_abs_diff_eq!( @@ -1566,7 +1576,7 @@ fn test_do_swap_storage_updates() { destination_netuid ), expected_alpha, - epsilon = 1000 + epsilon = 1000.into() ); }); } @@ -1593,12 +1603,12 @@ fn test_do_swap_multiple_times() { ) .unwrap(); - let mut expected_alpha: u64 = 0; + let mut expected_alpha = AlphaCurrency::ZERO; for _ in 0..3 { let alpha1 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( &hotkey, &coldkey, netuid1, ); - if alpha1 > 0 { + if !alpha1.is_zero() { assert_ok!(SubtensorModule::do_swap_stake( RuntimeOrigin::signed(coldkey), hotkey, @@ -1610,7 +1620,7 @@ fn test_do_swap_multiple_times() { let alpha2 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( &hotkey, &coldkey, netuid2, ); - if alpha2 > 0 { + if !alpha2.is_zero() { let (tao_equivalent, _) = mock::swap_alpha_to_tao(netuid2, alpha2); // we do this in the loop, because we need the value before the swap expected_alpha = mock::swap_tao_to_alpha(netuid1, tao_equivalent).0; @@ -1627,11 +1637,11 @@ fn test_do_swap_multiple_times() { assert_abs_diff_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey, &coldkey, netuid1), expected_alpha, - epsilon = 1000 + epsilon = 1000.into() ); assert_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey, &coldkey, netuid2), - 0 + AlphaCurrency::ZERO ); }); } @@ -1692,8 +1702,8 @@ fn test_swap_stake_limit_validate() { let stake_amount = 100_000_000_000; let reserve = 1_000_000_000_000; - mock::setup_reserves(origin_netuid, reserve, reserve); - mock::setup_reserves(destination_netuid, reserve, reserve); + mock::setup_reserves(origin_netuid, reserve, reserve.into()); + mock::setup_reserves(destination_netuid, reserve, reserve.into()); SubtensorModule::create_account_if_non_existent(&coldkey, &hotkey); let unstake_amount = SubtensorModule::stake_into_subnet( @@ -1856,10 +1866,10 @@ fn test_move_stake_specific_stake_into_subnet_fail() { let existing_shares: U64F64 = U64F64::from_num(161_986_254).saturating_div(U64F64::from_num(u64::MAX)); - let existing_stake = 36_711_495_953; + let existing_stake = AlphaCurrency::from(36_711_495_953); let tao_in = 2_409_892_148_947; - let alpha_in = 15_358_708_513_716; + let alpha_in = AlphaCurrency::from(15_358_708_513_716); let tao_staked = 200_000_000; @@ -1901,7 +1911,7 @@ fn test_move_stake_specific_stake_into_subnet_fail() { ); // Setup Subnet pool for origin netuid - SubnetAlphaIn::::insert(origin_netuid, alpha_in + 10_000_000); + SubnetAlphaIn::::insert(origin_netuid, alpha_in + 10_000_000.into()); SubnetTAO::::insert(origin_netuid, tao_in + 10_000_000); // Add stake as new hotkey @@ -1936,7 +1946,7 @@ fn test_move_stake_specific_stake_into_subnet_fail() { &coldkey_account_id, origin_netuid ), - 0 + AlphaCurrency::ZERO ); assert_abs_diff_eq!( @@ -1946,7 +1956,7 @@ fn test_move_stake_specific_stake_into_subnet_fail() { netuid ), expected_value, - epsilon = 1000 + epsilon = 1000.into() ); }); } diff --git a/pallets/subtensor/src/tests/networks.rs b/pallets/subtensor/src/tests/networks.rs index ff14a641db..aa6a65918c 100644 --- a/pallets/subtensor/src/tests/networks.rs +++ b/pallets/subtensor/src/tests/networks.rs @@ -298,8 +298,8 @@ fn test_register_subnet_low_lock_cost() { assert!(SubtensorModule::if_subnet_exist(netuid)); // Ensure that both Subnet TAO and Subnet Alpha In equal to (actual) lock_cost - assert_eq!(SubnetTAO::::get(netuid), lock_cost,); - assert_eq!(SubnetAlphaIn::::get(netuid), lock_cost,); + assert_eq!(SubnetTAO::::get(netuid), lock_cost); + assert_eq!(SubnetAlphaIn::::get(netuid), lock_cost.into()); }) } @@ -322,7 +322,7 @@ fn test_register_subnet_high_lock_cost() { // Ensure that both Subnet TAO and Subnet Alpha In equal to 100 TAO assert_eq!(SubnetTAO::::get(netuid), lock_cost); - assert_eq!(SubnetAlphaIn::::get(netuid), lock_cost); + assert_eq!(SubnetAlphaIn::::get(netuid), lock_cost.into()); }) } diff --git a/pallets/subtensor/src/tests/recycle_alpha.rs b/pallets/subtensor/src/tests/recycle_alpha.rs index ef23d1807d..5ceaf86d13 100644 --- a/pallets/subtensor/src/tests/recycle_alpha.rs +++ b/pallets/subtensor/src/tests/recycle_alpha.rs @@ -1,6 +1,7 @@ use approx::assert_abs_diff_eq; use frame_support::{assert_noop, assert_ok, traits::Currency}; use sp_core::U256; +use subtensor_runtime_common::{Alpha as AlphaCurrency, Currency as CurrencyT}; use super::mock; use super::mock::*; @@ -34,7 +35,7 @@ fn test_recycle_success() { let initial_net_alpha = SubnetAlphaOut::::get(netuid); // amount to recycle - let recycle_amount = stake / 2; + let recycle_amount = AlphaCurrency::from(stake / 2); // recycle assert_ok!(SubtensorModule::recycle_alpha( @@ -94,7 +95,7 @@ fn test_recycle_two_stakers() { let initial_net_alpha = SubnetAlphaOut::::get(netuid); // amount to recycle - let recycle_amount = stake / 2; + let recycle_amount = AlphaCurrency::from(stake / 2); // recycle assert_ok!(SubtensorModule::recycle_alpha( @@ -108,7 +109,7 @@ fn test_recycle_two_stakers() { assert!(SubnetAlphaOut::::get(netuid) < initial_net_alpha); assert!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey, &coldkey, netuid) - < stake + < stake.into() ); // Make sure the other coldkey has no change assert_abs_diff_eq!( @@ -118,7 +119,7 @@ fn test_recycle_two_stakers() { netuid ), expected_alpha, - epsilon = 2 + epsilon = 2.into() ); assert!(System::events().iter().any(|e| { @@ -170,7 +171,7 @@ fn test_recycle_staker_is_nominator() { let initial_net_alpha = SubnetAlphaOut::::get(netuid); // amount to recycle - let recycle_amount = stake / 2; + let recycle_amount = AlphaCurrency::from(stake / 2); // recycle from nominator coldkey assert_ok!(SubtensorModule::recycle_alpha( @@ -187,13 +188,13 @@ fn test_recycle_staker_is_nominator() { &hotkey, &other_coldkey, netuid - ) < stake + ) < stake.into() ); // Make sure the other coldkey has no change assert_abs_diff_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey, &coldkey, netuid), expected_alpha, - epsilon = 2 + epsilon = 2.into() ); assert!(System::events().iter().any(|e| { @@ -239,7 +240,7 @@ fn test_burn_success() { assert_ok!(SubtensorModule::burn_alpha( RuntimeOrigin::signed(coldkey), hotkey, - burn_amount, + burn_amount.into(), netuid )); @@ -247,7 +248,7 @@ fn test_burn_success() { assert!(SubnetAlphaOut::::get(netuid) == initial_net_alpha); assert!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey, &coldkey, netuid) - < stake + < stake.into() ); assert!(System::events().iter().any(|e| { @@ -294,7 +295,7 @@ fn test_burn_staker_is_nominator() { let initial_net_alpha = SubnetAlphaOut::::get(netuid); // amount to recycle - let burn_amount = stake / 2; + let burn_amount = AlphaCurrency::from(stake / 2); // burn from nominator coldkey assert_ok!(SubtensorModule::burn_alpha( @@ -311,13 +312,13 @@ fn test_burn_staker_is_nominator() { &hotkey, &other_coldkey, netuid - ) < stake + ) < stake.into() ); // Make sure the other coldkey has no change assert_abs_diff_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey, &coldkey, netuid), expected_alpha, - epsilon = 2 + epsilon = 2.into() ); assert!(System::events().iter().any(|e| { @@ -363,7 +364,7 @@ fn test_burn_two_stakers() { let initial_net_alpha = SubnetAlphaOut::::get(netuid); // amount to recycle - let burn_amount = stake / 2; + let burn_amount = AlphaCurrency::from(stake / 2); // burn from coldkey assert_ok!(SubtensorModule::burn_alpha( @@ -377,7 +378,7 @@ fn test_burn_two_stakers() { assert!(SubnetAlphaOut::::get(netuid) == initial_net_alpha); assert!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey, &coldkey, netuid) - < stake + < stake.into() ); // Make sure the other coldkey has no change assert_abs_diff_eq!( @@ -387,7 +388,7 @@ fn test_burn_two_stakers() { netuid ), expected_alpha, - epsilon = 2 + epsilon = 2.into() ); assert!(System::events().iter().any(|e| { @@ -426,7 +427,7 @@ fn test_recycle_errors() { SubtensorModule::recycle_alpha( RuntimeOrigin::signed(coldkey), hotkey, - 100_000, + 100_000.into(), 99.into() // non-existent subnet ), Error::::SubNetworkDoesNotExist @@ -436,7 +437,7 @@ fn test_recycle_errors() { SubtensorModule::recycle_alpha( RuntimeOrigin::signed(coldkey), hotkey, - 100_000, + 100_000.into(), NetUid::ROOT, ), Error::::CannotBurnOrRecycleOnRootSubnet @@ -446,7 +447,7 @@ fn test_recycle_errors() { SubtensorModule::recycle_alpha( RuntimeOrigin::signed(coldkey), wrong_hotkey, - 100_000, + 100_000.into(), netuid ), Error::::HotKeyAccountNotExists @@ -456,7 +457,7 @@ fn test_recycle_errors() { SubtensorModule::recycle_alpha( RuntimeOrigin::signed(coldkey), hotkey, - 10_000_000_000, // too much + 10_000_000_000.into(), // too much netuid ), Error::::NotEnoughStakeToWithdraw @@ -466,14 +467,14 @@ fn test_recycle_errors() { TotalHotkeyAlpha::::set( hotkey, netuid, - SubnetAlphaOut::::get(netuid).saturating_mul(2), + SubnetAlphaOut::::get(netuid).saturating_mul(2.into()), ); assert_noop!( SubtensorModule::recycle_alpha( RuntimeOrigin::signed(coldkey), hotkey, - SubnetAlphaOut::::get(netuid) + 1, + SubnetAlphaOut::::get(netuid) + 1.into(), netuid ), Error::::InsufficientLiquidity @@ -508,7 +509,7 @@ fn test_burn_errors() { SubtensorModule::burn_alpha( RuntimeOrigin::signed(coldkey), hotkey, - 100_000, + 100_000.into(), 99.into() // non-existent subnet ), Error::::SubNetworkDoesNotExist @@ -518,7 +519,7 @@ fn test_burn_errors() { SubtensorModule::burn_alpha( RuntimeOrigin::signed(coldkey), hotkey, - 100_000, + 100_000.into(), NetUid::ROOT, ), Error::::CannotBurnOrRecycleOnRootSubnet @@ -528,7 +529,7 @@ fn test_burn_errors() { SubtensorModule::burn_alpha( RuntimeOrigin::signed(coldkey), wrong_hotkey, - 100_000, + 100_000.into(), netuid ), Error::::HotKeyAccountNotExists @@ -538,7 +539,7 @@ fn test_burn_errors() { SubtensorModule::burn_alpha( RuntimeOrigin::signed(coldkey), hotkey, - 10_000_000_000, // too much + 10_000_000_000.into(), // too much netuid ), Error::::NotEnoughStakeToWithdraw @@ -548,14 +549,14 @@ fn test_burn_errors() { TotalHotkeyAlpha::::set( hotkey, netuid, - SubnetAlphaOut::::get(netuid).saturating_mul(2), + SubnetAlphaOut::::get(netuid).saturating_mul(2.into()), ); assert_noop!( SubtensorModule::burn_alpha( RuntimeOrigin::signed(coldkey), hotkey, - SubnetAlphaOut::::get(netuid) + 1, + SubnetAlphaOut::::get(netuid) + 1.into(), netuid ), Error::::InsufficientLiquidity diff --git a/pallets/subtensor/src/tests/registration.rs b/pallets/subtensor/src/tests/registration.rs index 084eda0b66..8a39306315 100644 --- a/pallets/subtensor/src/tests/registration.rs +++ b/pallets/subtensor/src/tests/registration.rs @@ -8,7 +8,7 @@ use frame_support::{assert_err, assert_noop, assert_ok}; use frame_system::{Config, RawOrigin}; use sp_core::U256; use sp_runtime::traits::{DispatchInfoOf, TransactionExtension, TxBaseImplication}; -use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::{Alpha as AlphaCurrency, Currency as CurrencyT, NetUid}; use super::mock; use super::mock::*; @@ -153,7 +153,7 @@ fn test_registration_ok() { // Check if the balance of this hotkey account for this subnetwork == 0 assert_eq!( SubtensorModule::get_stake_for_uid_and_subnetwork(netuid, neuron_uid), - 0 + AlphaCurrency::ZERO ); }); } @@ -320,7 +320,7 @@ fn test_burned_registration_under_limit() { SubtensorModule::set_burn(netuid, burn_cost); let reserve = 1_000_000_000_000; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); add_network(netuid, 13, 0); // Add the network // Give it some TAO to the coldkey balance; more than the burn cost @@ -420,7 +420,7 @@ fn test_burned_registration_rate_allows_burn_adjustment() { SubtensorModule::set_burn(netuid, burn_cost); let reserve = 1_000_000_000_000; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); add_network(netuid, 13, 0); // Add the network // Give it some TAO to the coldkey balance; more than the burn cost @@ -477,7 +477,7 @@ fn test_burned_registration_ok() { add_network(netuid, tempo, 0); let reserve = 1_000_000_000_000; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); // Give it some $$$ in his coldkey balance SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, 10000); @@ -510,7 +510,7 @@ fn test_burned_registration_ok() { // Check if the balance of this hotkey account for this subnetwork == 0 assert_eq!( SubtensorModule::get_stake_for_uid_and_subnetwork(netuid, neuron_uid), - 0 + AlphaCurrency::ZERO ); }); } @@ -599,7 +599,7 @@ fn test_burn_adjustment() { ); let reserve = 1_000_000_000_000; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); // Register key 1. let hotkey_account_id_1 = U256::from(1); @@ -655,7 +655,7 @@ fn test_burn_registration_pruning_scenarios() { SubtensorModule::set_immunity_period(netuid, immunity_period); let reserve = 1_000_000_000_000; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); add_network(netuid, tempo, 0); @@ -1560,8 +1560,8 @@ fn test_burn_registration_increase_recycled_rao() { Balances::deposit_creating(&coldkey_account_id, Balance::from(1_000_000_000_000_u64)); let reserve = 1_000_000_000_000; - mock::setup_reserves(netuid, reserve, reserve); - mock::setup_reserves(netuid2, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid2, reserve, reserve.into()); add_network(netuid, 13, 0); assert_eq!(SubtensorModule::get_subnetwork_n(netuid), 0); diff --git a/pallets/subtensor/src/tests/senate.rs b/pallets/subtensor/src/tests/senate.rs index 3aeec0eb9a..be1a90ded4 100644 --- a/pallets/subtensor/src/tests/senate.rs +++ b/pallets/subtensor/src/tests/senate.rs @@ -76,7 +76,7 @@ fn test_senate_join_works() { SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, 10000); let reserve = 1_000_000_000; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); // Subscribe and check extrinsic output assert_ok!(SubtensorModule::burned_register( @@ -116,13 +116,13 @@ fn test_senate_join_works() { &staker_coldkey, netuid ), - stake, - epsilon = 1 + AlphaCurrency::from(stake), + epsilon = 1.into() ); assert_abs_diff_eq!( SubtensorModule::get_stake_for_hotkey_on_subnet(&hotkey_account_id, netuid), - stake, - epsilon = 1 + AlphaCurrency::from(stake), + epsilon = 1.into() ); assert_ok!(SubtensorModule::root_register( @@ -152,7 +152,7 @@ fn test_senate_vote_works() { SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, 10000); let reserve = 1_000_000_000_000; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); // Subscribe and check extrinsic output assert_ok!(SubtensorModule::burned_register( @@ -193,13 +193,13 @@ fn test_senate_vote_works() { &staker_coldkey, netuid ), - stake, - epsilon = 1 + AlphaCurrency::from(stake), + epsilon = 1.into() ); assert_abs_diff_eq!( SubtensorModule::get_stake_for_hotkey_on_subnet(&hotkey_account_id, netuid), - stake, - epsilon = 1 + AlphaCurrency::from(stake), + epsilon = 1.into() ); assert_ok!(SubtensorModule::root_register( @@ -268,7 +268,7 @@ fn test_senate_vote_not_member() { SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, 10000); let reserve = 1_000_000_000_000; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); // Subscribe and check extrinsic output assert_ok!(SubtensorModule::burned_register( @@ -332,7 +332,7 @@ fn test_senate_leave_works() { SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, 10000); let reserve = stake * 1000; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); // Subscribe and check extrinsic output assert_ok!(SubtensorModule::burned_register( @@ -372,13 +372,13 @@ fn test_senate_leave_works() { &staker_coldkey, netuid ), - stake, - epsilon = 1 + AlphaCurrency::from(stake), + epsilon = 1.into() ); assert_abs_diff_eq!( SubtensorModule::get_stake_for_hotkey_on_subnet(&hotkey_account_id, netuid), - stake, - epsilon = 1 + AlphaCurrency::from(stake), + epsilon = 1.into() ); assert_ok!(SubtensorModule::root_register( @@ -411,7 +411,7 @@ fn test_senate_leave_vote_removal() { SubtokenEnabled::::insert(netuid, true); let reserve = stake * 1000; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); // Subscribe and check extrinsic output assert_ok!(SubtensorModule::burned_register( @@ -451,13 +451,13 @@ fn test_senate_leave_vote_removal() { &staker_coldkey, netuid ), - stake, - epsilon = 1 + AlphaCurrency::from(stake), + epsilon = 1.into() ); assert_abs_diff_eq!( SubtensorModule::get_stake_for_hotkey_on_subnet(&hotkey_account_id, netuid), - stake, - epsilon = 1 + AlphaCurrency::from(stake), + epsilon = 1.into() ); assert_ok!(SubtensorModule::root_register( @@ -496,8 +496,8 @@ fn test_senate_leave_vote_removal() { SubtensorModule::set_target_registrations_per_interval(NetUid::ROOT, 1000); let reserve = 1_000_000_000_000; - mock::setup_reserves(other_netuid, reserve, reserve); - mock::setup_reserves(NetUid::ROOT, reserve, reserve); + mock::setup_reserves(other_netuid, reserve, reserve.into()); + mock::setup_reserves(NetUid::ROOT, reserve, reserve.into()); SubtokenEnabled::::insert(NetUid::ROOT, true); SubtokenEnabled::::insert(other_netuid, true); @@ -562,7 +562,7 @@ fn test_senate_not_leave_when_stake_removed() { SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, 10000); let reserve = 1_000_000_000_000; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); // Subscribe and check extrinsic output assert_ok!(SubtensorModule::burned_register( @@ -603,13 +603,13 @@ fn test_senate_not_leave_when_stake_removed() { &staker_coldkey, netuid ), - stake_amount, - epsilon = 1 + AlphaCurrency::from(stake_amount), + epsilon = 1.into() ); assert_abs_diff_eq!( SubtensorModule::get_stake_for_hotkey_on_subnet(&hotkey_account_id, netuid), - stake_amount, - epsilon = 1 + AlphaCurrency::from(stake_amount), + epsilon = 1.into() ); assert_ok!(SubtensorModule::root_register( @@ -624,7 +624,7 @@ fn test_senate_not_leave_when_stake_removed() { <::RuntimeOrigin>::signed(staker_coldkey), hotkey_account_id, netuid, - stake_amount - 1 + (stake_amount - 1).into() )); assert!(Senate::is_member(&hotkey_account_id)); }); @@ -649,7 +649,7 @@ fn test_senate_join_current_delegate() { SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, 10000); let reserve = 1_000_000_000_000; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); // Subscribe and check extrinsic output assert_ok!(SubtensorModule::burned_register( @@ -751,7 +751,7 @@ fn test_adjust_senate_events() { SubtokenEnabled::::insert(NetUid::ROOT, true); let reserve = 100_000_000_000_000; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); // Subscribe and check extrinsic output assert_ok!(SubtensorModule::burned_register( @@ -841,7 +841,7 @@ fn test_adjust_senate_events() { let stake = DefaultMinStake::::get() * 10; let reserve = 100_000_000_000_000; - mock::setup_reserves(NetUid::ROOT, reserve, reserve); + mock::setup_reserves(NetUid::ROOT, reserve, reserve.into()); let (_, fee) = mock::swap_tao_to_alpha(NetUid::ROOT, stake); @@ -857,16 +857,16 @@ fn test_adjust_senate_events() { &coldkey_account_id, NetUid::ROOT ), - stake - fee, - epsilon = stake / 1000 + AlphaCurrency::from(stake - fee), + epsilon = (stake / 1000).into() ); assert_abs_diff_eq!( SubtensorModule::get_stake_for_hotkey_on_subnet( &replacement_hotkey_account_id, NetUid::ROOT ), - stake - fee, - epsilon = stake / 1000 + AlphaCurrency::from(stake - fee), + epsilon = (stake / 1000).into() ); System::reset_events(); diff --git a/pallets/subtensor/src/tests/staking.rs b/pallets/subtensor/src/tests/staking.rs index bca880b01c..ffd5c1de31 100644 --- a/pallets/subtensor/src/tests/staking.rs +++ b/pallets/subtensor/src/tests/staking.rs @@ -14,7 +14,7 @@ use safe_math::FixedExt; use sp_core::{Get, H256, U256}; use substrate_fixed::traits::FromFixed; use substrate_fixed::types::{I96F32, I110F18, U64F64, U96F32}; -use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::{Alpha as AlphaCurrency, Currency as CurrencyT, NetUid}; use subtensor_swap_interface::{OrderType, SwapHandler}; use super::mock; @@ -57,7 +57,7 @@ fn test_add_stake_ok_no_emission() { //add network let netuid = add_dynamic_network(&hotkey_account_id, &coldkey_account_id); - mock::setup_reserves(netuid, amount * 1_000_000, amount * 10_000_000); + mock::setup_reserves(netuid, amount * 1_000_000, (amount * 10_000_000).into()); // Give it some $$$ in his coldkey balance SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, amount); @@ -136,7 +136,7 @@ fn test_dividends_with_run_to_block() { &neuron_src_hotkey_id, &coldkey_account_id, netuid, - initial_stake, + initial_stake.into(), ); // Check if the initial stake has arrived @@ -356,7 +356,7 @@ fn test_add_stake_total_issuance_no_change() { fn test_remove_stake_dispatch_info_ok() { new_test_ext(1).execute_with(|| { let hotkey = U256::from(0); - let amount_unstaked = 5000; + let amount_unstaked = AlphaCurrency::from(5000); let netuid = NetUid::from(1); let call = RuntimeCall::SubtensorModule(SubtensorCall::remove_stake { hotkey, @@ -403,7 +403,7 @@ fn test_remove_stake_ok_no_emission() { &hotkey_account_id, &coldkey_account_id, netuid, - amount, + amount.into(), ); assert_abs_diff_eq!( SubtensorModule::get_total_stake_for_hotkey(&hotkey_account_id), @@ -412,7 +412,7 @@ fn test_remove_stake_ok_no_emission() { ); // Add subnet TAO for the equivalent amount added at price - let (amount_tao, fee) = mock::swap_alpha_to_tao(netuid, amount); + let (amount_tao, fee) = mock::swap_alpha_to_tao(netuid, amount.into()); SubnetTAO::::mutate(netuid, |v| *v += amount_tao + fee); TotalStake::::mutate(|v| *v += amount_tao + fee); @@ -421,7 +421,7 @@ fn test_remove_stake_ok_no_emission() { RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, netuid, - amount + amount.into() )); // we do not expect the exact amount due to slippage @@ -466,7 +466,7 @@ fn test_remove_stake_amount_too_low() { &hotkey_account_id, &coldkey_account_id, netuid, - amount, + amount.into(), ); // Do the magic @@ -475,7 +475,7 @@ fn test_remove_stake_amount_too_low() { RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, netuid, - 0 + AlphaCurrency::ZERO ), Error::::AmountTooLow ); @@ -486,7 +486,7 @@ fn test_remove_stake_amount_too_low() { fn test_remove_stake_err_signature() { new_test_ext(1).execute_with(|| { let hotkey_account_id = U256::from(4968585); - let amount = 10000; // Amount to be removed + let amount = AlphaCurrency::from(10000); // Amount to be removed let netuid = NetUid::from(1); assert_err!( @@ -515,14 +515,14 @@ fn test_remove_stake_ok_hotkey_does_not_belong_to_coldkey() { &hotkey_id, &other_cold_key, netuid, - amount, + amount.into(), ); assert_ok!(SubtensorModule::remove_stake( RuntimeOrigin::signed(other_cold_key), hotkey_id, netuid, - amount, + amount.into(), )); }); } @@ -542,7 +542,7 @@ fn test_remove_stake_no_enough_stake() { RuntimeOrigin::signed(coldkey_id), hotkey_id, netuid, - amount, + amount.into(), ), Error::::NotEnoughStakeToWithdraw ); @@ -582,7 +582,7 @@ fn test_remove_stake_total_balance_no_change() { &hotkey_account_id, &coldkey_account_id, netuid, - amount, + amount.into(), ); // Add subnet TAO for the equivalent amount added at price @@ -596,7 +596,7 @@ fn test_remove_stake_total_balance_no_change() { RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, netuid, - amount + amount.into() )); let fee = ::SwapInterface::approx_fee_amount(netuid.into(), amount); @@ -636,7 +636,7 @@ fn test_add_stake_insufficient_liquidity() { // Set the liquidity at lowest possible value so that all staking requests fail let reserve = u64::from(mock::SwapMinimumReserve::get()) - 1; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); // Check the error assert_noop!( @@ -666,7 +666,7 @@ fn test_remove_stake_insufficient_liquidity() { // Simulate stake for hotkey let reserve = u64::MAX / 1000; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); let alpha = SubtensorModule::stake_into_subnet( &hotkey, @@ -679,7 +679,7 @@ fn test_remove_stake_insufficient_liquidity() { // Set the liquidity at lowest possible value so that all staking requests fail let reserve = u64::from(mock::SwapMinimumReserve::get()) - 1; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); // Check the error assert_noop!( @@ -689,7 +689,7 @@ fn test_remove_stake_insufficient_liquidity() { // Mock provided liquidity - remove becomes successful SubnetTaoProvided::::insert(netuid, amount_staked + 1); - SubnetAlphaInProvided::::insert(netuid, 1); + SubnetAlphaInProvided::::insert(netuid, AlphaCurrency::from(1)); assert_ok!(SubtensorModule::remove_stake( RuntimeOrigin::signed(coldkey), hotkey, @@ -716,7 +716,7 @@ fn test_remove_stake_total_issuance_no_change() { // Give it some $$$ in his coldkey balance SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, amount); - mock::setup_reserves(netuid, amount * 100, amount * 100); + mock::setup_reserves(netuid, amount * 100, (amount * 100).into()); // Some basic assertions assert_eq!( @@ -818,6 +818,8 @@ fn test_remove_prev_epoch_stake() { ] .into_iter() .for_each(|(amount_to_stake, alpha_divs, hotkey_alpha)| { + let alpha_divs = AlphaCurrency::from(alpha_divs); + let hotkey_alpha = AlphaCurrency::from(hotkey_alpha); let subnet_owner_coldkey = U256::from(1); let subnet_owner_hotkey = U256::from(2); let hotkey_account_id = U256::from(581337); @@ -831,7 +833,7 @@ fn test_remove_prev_epoch_stake() { AlphaDividendsPerSubnet::::insert(netuid, hotkey_account_id, alpha_divs); TotalHotkeyAlphaLastEpoch::::insert(hotkey_account_id, netuid, hotkey_alpha); let balance_before = SubtensorModule::get_coldkey_balance(&coldkey_account_id); - mock::setup_reserves(netuid, amount_to_stake * 10, amount_to_stake * 10); + mock::setup_reserves(netuid, amount_to_stake * 10, (amount_to_stake * 10).into()); // Stake to hotkey account, and check if the result is ok let (_, fee) = mock::swap_tao_to_alpha(netuid, amount); @@ -886,11 +888,11 @@ fn test_staking_sets_div_variables() { // Verify that divident variables are clear in the beginning assert_eq!( AlphaDividendsPerSubnet::::get(netuid, hotkey_account_id), - 0 + AlphaCurrency::ZERO ); assert_eq!( TotalHotkeyAlphaLastEpoch::::get(hotkey_account_id, netuid), - 0 + AlphaCurrency::ZERO ); // Stake to hotkey account, and check if the result is ok @@ -904,11 +906,11 @@ fn test_staking_sets_div_variables() { // Verify that divident variables are still clear in the beginning assert_eq!( AlphaDividendsPerSubnet::::get(netuid, hotkey_account_id), - 0 + AlphaCurrency::ZERO ); assert_eq!( TotalHotkeyAlphaLastEpoch::::get(hotkey_account_id, netuid), - 0 + AlphaCurrency::ZERO ); // Wait for 1 epoch @@ -921,11 +923,13 @@ fn test_staking_sets_div_variables() { netuid, ); - assert!(AlphaDividendsPerSubnet::::get(netuid, hotkey_account_id) > 0); + assert!( + AlphaDividendsPerSubnet::::get(netuid, hotkey_account_id) > AlphaCurrency::ZERO + ); assert_abs_diff_eq!( TotalHotkeyAlphaLastEpoch::::get(hotkey_account_id, netuid), stake, - epsilon = stake / 100_000 + epsilon = stake / 100_000.into() ); }); } @@ -984,7 +988,7 @@ fn test_add_stake_to_hotkey_account_ok() { &hotkey_id, &coldkey_id, netuid, - amount, + amount.into(), ); // The stake that is now in the account, should equal the amount @@ -1015,7 +1019,7 @@ fn test_remove_stake_from_hotkey_account() { &hotkey_id, &coldkey_id, netuid, - amount, + amount.into(), ); // Prelimiary checks @@ -1030,7 +1034,7 @@ fn test_remove_stake_from_hotkey_account() { &hotkey_id, &coldkey_id, netuid, - amount, + amount.into(), ); // The stake on the hotkey account should be 0 @@ -1063,16 +1067,16 @@ fn test_remove_stake_from_hotkey_account_registered_in_various_networks() { &hotkey_id, &coldkey_id, netuid, - amount, + amount.into(), ); assert_eq!( SubtensorModule::get_stake_for_uid_and_subnetwork(netuid, neuron_uid), - amount + amount.into() ); assert_eq!( SubtensorModule::get_stake_for_uid_and_subnetwork(netuid_ex, neuron_uid_ex), - 0 + AlphaCurrency::ZERO ); // Remove all stake @@ -1080,17 +1084,17 @@ fn test_remove_stake_from_hotkey_account_registered_in_various_networks() { &hotkey_id, &coldkey_id, netuid, - amount, + amount.into(), ); // assert_eq!( SubtensorModule::get_stake_for_uid_and_subnetwork(netuid, neuron_uid), - 0 + AlphaCurrency::ZERO ); assert_eq!( SubtensorModule::get_stake_for_uid_and_subnetwork(netuid_ex, neuron_uid_ex), - 0 + AlphaCurrency::ZERO ); }); } @@ -1239,7 +1243,7 @@ fn test_has_enough_stake_yes() { &hotkey_id, &coldkey_id, netuid, - intial_amount, + intial_amount.into(), ); assert_abs_diff_eq!( @@ -1253,13 +1257,13 @@ fn test_has_enough_stake_yes() { &coldkey_id, netuid ), - intial_amount + intial_amount.into() ); assert!(SubtensorModule::has_enough_stake_on_subnet( &hotkey_id, &coldkey_id, netuid, - intial_amount / 2 + (intial_amount / 2).into() )); }); } @@ -1275,7 +1279,7 @@ fn test_has_enough_stake_no() { &hotkey_id, &coldkey_id, netuid, - intial_amount, + intial_amount.into(), ); assert_abs_diff_eq!( @@ -1289,13 +1293,13 @@ fn test_has_enough_stake_no() { &coldkey_id, netuid ), - intial_amount + intial_amount.into() ); assert!(!SubtensorModule::has_enough_stake_on_subnet( &hotkey_id, &coldkey_id, netuid, - intial_amount * 2 + (intial_amount * 2).into() )); }); } @@ -1318,13 +1322,13 @@ fn test_has_enough_stake_no_for_zero() { &coldkey_id, netuid ), - intial_amount + intial_amount.into() ); assert!(!SubtensorModule::has_enough_stake_on_subnet( &hotkey_id, &coldkey_id, netuid, - 1_000 + 1_000.into() )); }); } @@ -1337,7 +1341,7 @@ fn test_non_existent_account() { &U256::from(0), &(U256::from(0)), netuid, - 10, + 10.into(), ); assert_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( @@ -1345,7 +1349,7 @@ fn test_non_existent_account() { &U256::from(0), netuid ), - 10 + 10.into() ); // No subnets => no iteration => zero total stake assert_eq!( @@ -1438,11 +1442,11 @@ fn test_clear_small_nominations() { hot1, netuid, SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hot1, &cold1, netuid) - - 100 + - 100.into() )); assert_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hot1, &cold1, netuid), - 100 + 100.into() ); // Add stake cold2 --> hot1 (is delegation.) @@ -1458,11 +1462,11 @@ fn test_clear_small_nominations() { hot1, netuid, SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hot1, &cold2, netuid) - - 100 + - 100.into() )); assert_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hot1, &cold2, netuid), - 100 + 100.into() ); // Add stake cold1 --> hot2 (non delegation.) @@ -1478,11 +1482,11 @@ fn test_clear_small_nominations() { hot2, netuid, SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hot2, &cold1, netuid) - - 100 + - 100.into() )); assert_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hot2, &cold1, netuid), - 100 + 100.into() ); let balance1_before_cleaning = Balances::free_balance(cold1); @@ -1499,33 +1503,36 @@ fn test_clear_small_nominations() { hot2, netuid, SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hot2, &cold2, netuid) - - 100 + - 100.into() )); assert_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hot2, &cold2, netuid), - 100 + 100.into() ); let balance2_before_cleaning = Balances::free_balance(cold2); // Run clear all small nominations when min stake is zero (noop) - SubtensorModule::set_nominator_min_required_stake(0); - assert_eq!(SubtensorModule::get_nominator_min_required_stake(), 0); + SubtensorModule::set_nominator_min_required_stake(AlphaCurrency::ZERO); + assert_eq!( + SubtensorModule::get_nominator_min_required_stake(), + AlphaCurrency::ZERO + ); SubtensorModule::clear_small_nominations(); assert_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hot1, &cold1, netuid), - 100 + 100.into() ); assert_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hot2, &cold1, netuid), - 100 + 100.into() ); assert_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hot1, &cold2, netuid), - 100 + 100.into() ); assert_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hot2, &cold2, netuid), - 100 + 100.into() ); // Set min nomination to 10 @@ -1534,25 +1541,25 @@ fn test_clear_small_nominations() { let total_hot1_stake_before = TotalHotkeyAlpha::::get(hot1, netuid); let total_hot2_stake_before = TotalHotkeyAlpha::::get(hot2, netuid); let total_stake_before = TotalStake::::get(); - SubtensorModule::set_nominator_min_required_stake(1000); + SubtensorModule::set_nominator_min_required_stake(1000.into()); // Run clear all small nominations (removes delegations under 10) SubtensorModule::clear_small_nominations(); assert_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hot1, &cold1, netuid), - 100 + 100.into() ); assert_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hot2, &cold1, netuid), - 0 + AlphaCurrency::ZERO ); assert_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hot1, &cold2, netuid), - 0 + AlphaCurrency::ZERO ); assert_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hot2, &cold2, netuid), - 100 + 100.into() ); // Balances have been added back into accounts. @@ -1563,13 +1570,13 @@ fn test_clear_small_nominations() { assert_abs_diff_eq!( TotalHotkeyAlpha::::get(hot2, netuid), - total_hot2_stake_before - 100, - epsilon = 1 + total_hot2_stake_before - 100.into(), + epsilon = 1.into() ); assert_abs_diff_eq!( TotalHotkeyAlpha::::get(hot1, netuid), - total_hot1_stake_before - 100, - epsilon = 1 + total_hot1_stake_before - 100.into(), + epsilon = 1.into() ); assert_eq!(TotalStake::::get(), total_stake_before - 200); }); @@ -1998,7 +2005,7 @@ fn test_get_total_delegated_stake_after_unstaking() { RuntimeOrigin::signed(delegator), delegate_hotkey, netuid, - unstake_amount + unstake_amount.into() )); // Calculate the expected delegated stake @@ -2369,7 +2376,7 @@ fn test_add_stake_fee_goes_to_subnet_tao() { )); // Calculate expected stake - let expected_alpha = tao_to_stake - existential_deposit - fee; + let expected_alpha = AlphaCurrency::from(tao_to_stake - existential_deposit - fee); let actual_alpha = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey, &coldkey, netuid); let subnet_tao_after = SubnetTAO::::get(netuid); @@ -2378,7 +2385,7 @@ fn test_add_stake_fee_goes_to_subnet_tao() { assert_abs_diff_eq!( actual_alpha, expected_alpha, - epsilon = expected_alpha / 1000 + epsilon = expected_alpha / 1000.into() ); // Subnet TAO should have increased by the full tao_to_stake amount @@ -2429,7 +2436,7 @@ fn test_remove_stake_fee_goes_to_subnet_tao() { assert_abs_diff_eq!( subnet_tao_before, subnet_tao_after, - epsilon = alpha_to_unstake / 1000 + epsilon = alpha_to_unstake.to_u64() / 1000 ); // User balance should decrease by 2x fee as a result of staking + unstaking @@ -2447,8 +2454,8 @@ fn test_remove_stake_fee_realistic_values() { let subnet_owner_hotkey = U256::from(1002); let hotkey = U256::from(2); let coldkey = U256::from(3); - let alpha_to_unstake = 111_180_000_000; - let alpha_divs = 2_816_190; + let alpha_to_unstake = AlphaCurrency::from(111_180_000_000); + let alpha_divs = AlphaCurrency::from(2_816_190); let netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); SubtensorModule::create_account_if_non_existent(&coldkey, &hotkey); @@ -2459,9 +2466,9 @@ fn test_remove_stake_fee_realistic_values() { // A hotkey has 111 Alpha stake and is unstaking all Alpha. // Alpha dividends of this hotkey are ~0.0028 // This makes fee be equal ~0.0028 Alpha ~= 84000 rao - let tao_reserve: U96F32 = U96F32::from_num(3_896_056_559_708_u64); - let alpha_in: U96F32 = U96F32::from_num(128_011_331_299_964_u64); - mock::setup_reserves(netuid, tao_reserve.to_num(), alpha_in.to_num()); + let tao_reserve = 3_896_056_559_708_u64; + let alpha_in = 128_011_331_299_964_u64; + mock::setup_reserves(netuid, tao_reserve, alpha_in.into()); AlphaDividendsPerSubnet::::insert(netuid, hotkey, alpha_divs); TotalHotkeyAlphaLastEpoch::::insert(hotkey, netuid, alpha_to_unstake); @@ -2608,10 +2615,10 @@ fn test_add_stake_limit_validate() { let netuid = add_dynamic_network(&hotkey, &coldkey); // Force-set alpha in and tao reserve to make price equal 1.5 - let tao_reserve: U96F32 = U96F32::from_num(150_000_000_000_u64); - let alpha_in: U96F32 = U96F32::from_num(100_000_000_000_u64); - SubnetTAO::::insert(netuid, tao_reserve.to_num::()); - SubnetAlphaIn::::insert(netuid, alpha_in.to_num::()); + let tao_reserve = 150_000_000_000_u64; + let alpha_in = AlphaCurrency::from(100_000_000_000); + SubnetTAO::::insert(netuid, tao_reserve); + SubnetAlphaIn::::insert(netuid, alpha_in); let current_price = ::SwapInterface::current_alpha_price(netuid.into()); assert_eq!(current_price, U96F32::from_num(1.5)); @@ -2665,7 +2672,7 @@ fn test_remove_stake_limit_validate() { let hotkey = U256::from(533453); let coldkey = U256::from(55453); let stake_amount = 300_000_000_000; - let unstake_amount = 150_000_000_000; + let unstake_amount = AlphaCurrency::from(150_000_000_000); // add network let netuid = add_dynamic_network(&hotkey, &coldkey); @@ -2675,14 +2682,14 @@ fn test_remove_stake_limit_validate() { &hotkey, &coldkey, netuid, - stake_amount, + stake_amount.into(), ); // Forse-set alpha in and tao reserve to make price equal 1.5 - let tao_reserve: U96F32 = U96F32::from_num(150_000_000_000_u64); - let alpha_in: U96F32 = U96F32::from_num(100_000_000_000_u64); - SubnetTAO::::insert(netuid, tao_reserve.to_num::()); - SubnetAlphaIn::::insert(netuid, alpha_in.to_num::()); + let tao_reserve = 150_000_000_000_u64; + let alpha_in = AlphaCurrency::from(100_000_000_000); + SubnetTAO::::insert(netuid, tao_reserve); + SubnetAlphaIn::::insert(netuid, alpha_in); let current_price = ::SwapInterface::current_alpha_price(netuid.into()); assert_eq!(current_price, U96F32::from_num(1.5)); @@ -2737,7 +2744,7 @@ fn test_stake_overflow() { SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, amount); // Setup liquidity with 21M TAO values - mock::setup_reserves(netuid, amount, amount); + mock::setup_reserves(netuid, amount, amount.into()); // Stake and check if the result is ok let (expected_alpha, _) = mock::swap_tao_to_alpha(netuid, amount); @@ -2782,7 +2789,7 @@ fn test_stake_low_liquidity_validate() { // Set the liquidity at lowest possible value so that all staking requests fail let reserve = u64::from(mock::SwapMinimumReserve::get()) - 1; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); // Add stake call let call = RuntimeCall::SubtensorModule(SubtensorCall::add_stake { @@ -2831,7 +2838,7 @@ fn test_unstake_low_liquidity_validate() { // Simulate stake for hotkey let reserve = u64::MAX / 1000; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); let alpha = SubtensorModule::stake_into_subnet( &hotkey, @@ -2844,7 +2851,7 @@ fn test_unstake_low_liquidity_validate() { // Set the liquidity at lowest possible value so that all staking requests fail let reserve = u64::from(mock::SwapMinimumReserve::get()) - 1; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); // Remove stake call let call = RuntimeCall::SubtensorModule(SubtensorCall::remove_stake { @@ -2893,7 +2900,7 @@ fn test_unstake_all_validate() { // Simulate stake for hotkey SubnetTAO::::insert(netuid, u64::MAX / 1000); - SubnetAlphaIn::::insert(netuid, u64::MAX / 1000); + SubnetAlphaIn::::insert(netuid, AlphaCurrency::from(u64::MAX / 1000)); SubtensorModule::stake_into_subnet( &hotkey, &coldkey, @@ -2905,7 +2912,7 @@ fn test_unstake_all_validate() { // Set the liquidity at lowest possible value so that all staking requests fail let reserve = u64::from(mock::SwapMinimumReserve::get()) - 1; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); // unstake_all call let call = RuntimeCall::SubtensorModule(SubtensorCall::unstake_all { hotkey }); @@ -3071,6 +3078,7 @@ fn test_max_amount_add_dynamic() { .into_iter() .for_each(|(tao_in, alpha_in, limit_price, expected_max_swappable)| { new_test_ext(0).execute_with(|| { + let alpha_in = AlphaCurrency::from(alpha_in); let subnet_owner_coldkey = U256::from(1001); let subnet_owner_hotkey = U256::from(1002); let netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); @@ -3082,7 +3090,7 @@ fn test_max_amount_add_dynamic() { // Force the swap to initialize SubtensorModule::swap_tao_for_alpha(netuid, 0, 1_000_000_000_000).unwrap(); - if alpha_in != 0 { + if !alpha_in.is_zero() { let expected_price = U96F32::from_num(tao_in) / U96F32::from_num(alpha_in); assert_abs_diff_eq!( ::SwapInterface::current_alpha_price(netuid.into()) @@ -3110,25 +3118,25 @@ fn test_max_amount_remove_root() { // 0 price on root => max is u64::MAX assert_eq!( SubtensorModule::get_max_amount_remove(NetUid::ROOT, 0), - Ok(u64::MAX) + Ok(AlphaCurrency::MAX) ); // 0.5 price on root => max is u64::MAX assert_eq!( SubtensorModule::get_max_amount_remove(NetUid::ROOT, 500_000_000), - Ok(u64::MAX) + Ok(AlphaCurrency::MAX) ); // 0.999999... price on root => max is u64::MAX assert_eq!( SubtensorModule::get_max_amount_remove(NetUid::ROOT, 999_999_999), - Ok(u64::MAX) + Ok(AlphaCurrency::MAX) ); // 1.0 price on root => max is u64::MAX assert_eq!( SubtensorModule::get_max_amount_remove(NetUid::ROOT, 1_000_000_000), - Ok(u64::MAX) + Ok(AlphaCurrency::MAX) ); // 1.000...001 price on root => max is 0 @@ -3154,19 +3162,19 @@ fn test_max_amount_remove_stable() { // 0 price => max is u64::MAX assert_eq!( SubtensorModule::get_max_amount_remove(netuid, 0), - Ok(u64::MAX) + Ok(AlphaCurrency::MAX) ); // 0.999999... price => max is u64::MAX assert_eq!( SubtensorModule::get_max_amount_remove(netuid, 999_999_999), - Ok(u64::MAX) + Ok(AlphaCurrency::MAX) ); // 1.0 price => max is u64::MAX assert_eq!( SubtensorModule::get_max_amount_remove(netuid, 1_000_000_000), - Ok(u64::MAX) + Ok(AlphaCurrency::MAX) ); // 1.000...001 price => max is 0 @@ -3289,11 +3297,12 @@ fn test_max_amount_remove_dynamic() { .iter() .for_each( |&(tao_in, alpha_in, limit_price, ref expected_max_swappable)| { + let alpha_in = AlphaCurrency::from(alpha_in); // Forse-set alpha in and tao reserve to achieve relative price of subnets SubnetTAO::::insert(netuid, tao_in); SubnetAlphaIn::::insert(netuid, alpha_in); - if alpha_in != 0 { + if !alpha_in.is_zero() { let expected_price = I96F32::from_num(tao_in) / I96F32::from_num(alpha_in); assert_eq!( ::SwapInterface::current_alpha_price(netuid.into()), @@ -3307,12 +3316,13 @@ fn test_max_amount_remove_dynamic() { Error::::ZeroMaxStakeAmount ), Ok(v) => { - let expected = v.saturating_add((*v as f64 * 0.003) as u64); + let expected = + AlphaCurrency::from(v.saturating_add((*v as f64 * 0.003) as u64)); assert_abs_diff_eq!( SubtensorModule::get_max_amount_remove(netuid, limit_price).unwrap(), expected, - epsilon = expected / 100 + epsilon = expected / 100.into() ); } } @@ -3328,25 +3338,25 @@ fn test_max_amount_move_root_root() { // 0 price on (root, root) exchange => max is u64::MAX assert_eq!( SubtensorModule::get_max_amount_move(NetUid::ROOT, NetUid::ROOT, 0), - Ok(u64::MAX) + Ok(AlphaCurrency::MAX) ); // 0.5 price on (root, root) => max is u64::MAX assert_eq!( SubtensorModule::get_max_amount_move(NetUid::ROOT, NetUid::ROOT, 500_000_000), - Ok(u64::MAX) + Ok(AlphaCurrency::MAX) ); // 0.999999... price on (root, root) => max is u64::MAX assert_eq!( SubtensorModule::get_max_amount_move(NetUid::ROOT, NetUid::ROOT, 999_999_999), - Ok(u64::MAX) + Ok(AlphaCurrency::MAX) ); // 1.0 price on (root, root) => max is u64::MAX assert_eq!( SubtensorModule::get_max_amount_move(NetUid::ROOT, NetUid::ROOT, 1_000_000_000), - Ok(u64::MAX) + Ok(AlphaCurrency::MAX) ); // 1.000...001 price on (root, root) => max is 0 @@ -3373,25 +3383,25 @@ fn test_max_amount_move_root_stable() { // 0 price on (root, stable) exchange => max is u64::MAX assert_eq!( SubtensorModule::get_max_amount_move(NetUid::ROOT, netuid, 0), - Ok(u64::MAX) + Ok(AlphaCurrency::MAX) ); // 0.5 price on (root, stable) => max is u64::MAX assert_eq!( SubtensorModule::get_max_amount_move(NetUid::ROOT, netuid, 500_000_000), - Ok(u64::MAX) + Ok(AlphaCurrency::MAX) ); // 0.999999... price on (root, stable) => max is u64::MAX assert_eq!( SubtensorModule::get_max_amount_move(NetUid::ROOT, netuid, 999_999_999), - Ok(u64::MAX) + Ok(AlphaCurrency::MAX) ); // 1.0 price on (root, stable) => max is u64::MAX assert_eq!( SubtensorModule::get_max_amount_move(NetUid::ROOT, netuid, 1_000_000_000), - Ok(u64::MAX) + Ok(AlphaCurrency::MAX) ); // 1.000...001 price on (root, stable) => max is 0 @@ -3422,10 +3432,10 @@ fn test_max_amount_move_stable_dynamic() { let dynamic_netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); // Force-set alpha in and tao reserve to make price equal 0.5 - let tao_reserve: U96F32 = U96F32::from_num(50_000_000_000_u64); - let alpha_in: U96F32 = U96F32::from_num(100_000_000_000_u64); - SubnetTAO::::insert(dynamic_netuid, tao_reserve.to_num::()); - SubnetAlphaIn::::insert(dynamic_netuid, alpha_in.to_num::()); + let tao_reserve = 50_000_000_000_u64; + let alpha_in = AlphaCurrency::from(100_000_000_000); + SubnetTAO::::insert(dynamic_netuid, tao_reserve); + SubnetAlphaIn::::insert(dynamic_netuid, alpha_in); let current_price = ::SwapInterface::current_alpha_price(dynamic_netuid.into()); assert_eq!(current_price, U96F32::from_num(0.5)); @@ -3435,7 +3445,7 @@ fn test_max_amount_move_stable_dynamic() { // 0 price => max is u64::MAX assert_eq!( SubtensorModule::get_max_amount_move(stable_netuid, dynamic_netuid, 0), - Ok(u64::MAX) + Ok(AlphaCurrency::MAX) ); // 2.0 price => max is 0 @@ -3451,12 +3461,11 @@ fn test_max_amount_move_stable_dynamic() { ); // 2x price => max is 1x TAO - let tao_reserve_u64 = tao_reserve.to_num::(); assert_abs_diff_eq!( SubtensorModule::get_max_amount_move(stable_netuid, dynamic_netuid, 500_000_000) .unwrap(), - tao_reserve_u64 + (tao_reserve_u64 as f64 * 0.003) as u64, - epsilon = tao_reserve_u64 / 100, + AlphaCurrency::from(tao_reserve + (tao_reserve as f64 * 0.003) as u64), + epsilon = AlphaCurrency::from(tao_reserve / 100), ); // Precision test: @@ -3464,7 +3473,7 @@ fn test_max_amount_move_stable_dynamic() { assert!( SubtensorModule::get_max_amount_move(stable_netuid, dynamic_netuid, 1_999_999_000) .unwrap() - > 0 + > AlphaCurrency::ZERO ); // Max price doesn't panic and returns something meaningful @@ -3497,10 +3506,10 @@ fn test_max_amount_move_dynamic_stable() { let dynamic_netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); // Forse-set alpha in and tao reserve to make price equal 1.5 - let tao_reserve: U96F32 = U96F32::from_num(150_000_000_000_u64); - let alpha_in: U96F32 = U96F32::from_num(100_000_000_000_u64); - SubnetTAO::::insert(dynamic_netuid, tao_reserve.to_num::()); - SubnetAlphaIn::::insert(dynamic_netuid, alpha_in.to_num::()); + let tao_reserve = 150_000_000_000_u64; + let alpha_in = 100_000_000_000_u64; + SubnetTAO::::insert(dynamic_netuid, tao_reserve); + SubnetAlphaIn::::insert(dynamic_netuid, AlphaCurrency::from(alpha_in)); let current_price = ::SwapInterface::current_alpha_price(dynamic_netuid.into()); assert_eq!(current_price, U96F32::from_num(1.5)); @@ -3510,18 +3519,21 @@ fn test_max_amount_move_dynamic_stable() { // 0 price => max is u64::MAX assert_eq!( SubtensorModule::get_max_amount_move(dynamic_netuid, stable_netuid, 0), - Ok(u64::MAX) + Ok(AlphaCurrency::MAX) ); // Low price values don't blow things up assert!( - SubtensorModule::get_max_amount_move(dynamic_netuid, stable_netuid, 1).unwrap() > 0 + SubtensorModule::get_max_amount_move(dynamic_netuid, stable_netuid, 1).unwrap() + > AlphaCurrency::ZERO ); assert!( - SubtensorModule::get_max_amount_move(dynamic_netuid, stable_netuid, 2).unwrap() > 0 + SubtensorModule::get_max_amount_move(dynamic_netuid, stable_netuid, 2).unwrap() + > AlphaCurrency::ZERO ); assert!( - SubtensorModule::get_max_amount_move(dynamic_netuid, stable_netuid, 3).unwrap() > 0 + SubtensorModule::get_max_amount_move(dynamic_netuid, stable_netuid, 3).unwrap() + > AlphaCurrency::ZERO ); // 1.5000...1 price => max is 0 @@ -3533,18 +3545,17 @@ fn test_max_amount_move_dynamic_stable() { // 1.5 price => max is 0 because of non-zero slippage assert_abs_diff_eq!( SubtensorModule::get_max_amount_move(dynamic_netuid, stable_netuid, 1_500_000_000) - .unwrap_or(0), - 0, - epsilon = 10_000 + .unwrap_or(AlphaCurrency::ZERO), + AlphaCurrency::ZERO, + epsilon = 10_000.into() ); // 1/4 price => max is 1x Alpha - let alpha_in_u64 = alpha_in.to_num::(); assert_abs_diff_eq!( SubtensorModule::get_max_amount_move(dynamic_netuid, stable_netuid, 375_000_000) .unwrap(), - alpha_in_u64 + (alpha_in_u64 as f64 * 0.003) as u64, - epsilon = alpha_in_u64 / 1000, + AlphaCurrency::from(alpha_in + (alpha_in as f64 * 0.003) as u64), + epsilon = AlphaCurrency::from(alpha_in) / 1000.into(), ); // Precision test: @@ -3552,24 +3563,24 @@ fn test_max_amount_move_dynamic_stable() { assert!( SubtensorModule::get_max_amount_move(dynamic_netuid, stable_netuid, 1_499_999_999) .unwrap() - > 0 + > AlphaCurrency::ZERO ); // Max price doesn't panic and returns something meaningful assert!( SubtensorModule::get_max_amount_move(dynamic_netuid, stable_netuid, u64::MAX) - .unwrap_or(0) - < 21_000_000_000_000_000 + .unwrap_or(AlphaCurrency::ZERO) + < 21_000_000_000_000_000.into() ); assert!( SubtensorModule::get_max_amount_move(dynamic_netuid, stable_netuid, u64::MAX - 1) - .unwrap_or(0) - < 21_000_000_000_000_000 + .unwrap_or(AlphaCurrency::ZERO) + < 21_000_000_000_000_000.into() ); assert!( SubtensorModule::get_max_amount_move(dynamic_netuid, stable_netuid, u64::MAX / 2) - .unwrap_or(0) - < 21_000_000_000_000_000 + .unwrap_or(AlphaCurrency::ZERO) + < 21_000_000_000_000_000.into() ); }); } @@ -3768,15 +3779,20 @@ fn test_max_amount_move_dynamic_dynamic() { expected_max_swappable, precision, )| { + let alpha_in_1 = AlphaCurrency::from(alpha_in_1); + let alpha_in_2 = AlphaCurrency::from(alpha_in_2); + let expected_max_swappable = AlphaCurrency::from(expected_max_swappable); // Forse-set alpha in and tao reserve to achieve relative price of subnets SubnetTAO::::insert(origin_netuid, tao_in_1); SubnetAlphaIn::::insert(origin_netuid, alpha_in_1); SubnetTAO::::insert(destination_netuid, tao_in_2); SubnetAlphaIn::::insert(destination_netuid, alpha_in_2); - if (alpha_in_1 != 0) && (alpha_in_2 != 0) { - let origin_price = I96F32::from_num(tao_in_1) / I96F32::from_num(alpha_in_1); - let dest_price = I96F32::from_num(tao_in_2) / I96F32::from_num(alpha_in_2); + if !alpha_in_1.is_zero() && !alpha_in_2.is_zero() { + let origin_price = + I96F32::from_num(tao_in_1) / I96F32::from_num(u64::from(alpha_in_1)); + let dest_price = + I96F32::from_num(tao_in_2) / I96F32::from_num(u64::from(alpha_in_2)); if dest_price != 0 { let expected_price = origin_price / dest_price; assert_eq!( @@ -3796,9 +3812,9 @@ fn test_max_amount_move_dynamic_dynamic() { destination_netuid, limit_price ) - .unwrap_or(0u64), + .unwrap_or(AlphaCurrency::ZERO), expected_max_swappable, - epsilon = precision + epsilon = precision.into() ); }, ); @@ -3817,8 +3833,8 @@ fn test_add_stake_limit_ok() { // Forse-set alpha in and tao reserve to make price equal 1.5 let tao_reserve = U96F32::from_num(150_000_000_000_u64); - let alpha_in = U96F32::from_num(100_000_000_000_u64); - mock::setup_reserves(netuid, tao_reserve.to_num(), alpha_in.to_num()); + let alpha_in = AlphaCurrency::from(100_000_000_000_u64); + mock::setup_reserves(netuid, tao_reserve.to_num(), alpha_in); let current_price = ::SwapInterface::current_alpha_price(netuid.into()); assert_eq!(current_price, U96F32::from_num(1.5)); @@ -3830,7 +3846,7 @@ fn test_add_stake_limit_ok() { // The amount that can be executed at this price is 450 TAO only // Alpha produced will be equal to 75 = 450*100/(450+150) let limit_price = 24_000_000_000; - let expected_executed_stake = 75_000_000_000; + let expected_executed_stake = AlphaCurrency::from(75_000_000_000); // Add stake with slippage safety and check if the result is ok assert_ok!(SubtensorModule::add_stake_limit( @@ -3850,7 +3866,7 @@ fn test_add_stake_limit_ok() { netuid ), expected_executed_stake, - epsilon = expected_executed_stake / 1000, + epsilon = expected_executed_stake / 1000.into(), ); // Check that 450 TAO less fees balance still remains free on coldkey @@ -3888,9 +3904,9 @@ fn test_add_stake_limit_fill_or_kill() { // Force-set alpha in and tao reserve to make price equal 1.5 let tao_reserve: U96F32 = U96F32::from_num(150_000_000_000_u64); - let alpha_in: U96F32 = U96F32::from_num(100_000_000_000_u64); + let alpha_in = AlphaCurrency::from(100_000_000_000_u64); SubnetTAO::::insert(netuid, tao_reserve.to_num::()); - SubnetAlphaIn::::insert(netuid, alpha_in.to_num::()); + SubnetAlphaIn::::insert(netuid, alpha_in); let current_price = ::SwapInterface::current_alpha_price(netuid.into()); // FIXME it's failing because in the swap pallet, the alpha price is set only after an @@ -3942,11 +3958,11 @@ fn test_add_stake_limit_partial_zero_max_stake_amount_error() { let amount = 19980000000; let limit_price = 26953618; let tao_reserve: U96F32 = U96F32::from_num(5_032_494_439_940_u64); - let alpha_in: U96F32 = U96F32::from_num(186_268_425_402_874_u64); + let alpha_in = AlphaCurrency::from(186_268_425_402_874); let netuid = add_dynamic_network(&hotkey_account_id, &coldkey_account_id); SubnetTAO::::insert(netuid, tao_reserve.to_num::()); - SubnetAlphaIn::::insert(netuid, alpha_in.to_num::()); + SubnetAlphaIn::::insert(netuid, alpha_in); SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, amount); @@ -3980,9 +3996,9 @@ fn test_remove_stake_limit_ok() { // Forse-set sufficient reserves let tao_reserve: U96F32 = U96F32::from_num(100_000_000_000_u64); - let alpha_in: U96F32 = U96F32::from_num(100_000_000_000_u64); + let alpha_in = AlphaCurrency::from(100_000_000_000); SubnetTAO::::insert(netuid, tao_reserve.to_num::()); - SubnetAlphaIn::::insert(netuid, alpha_in.to_num::()); + SubnetAlphaIn::::insert(netuid, alpha_in); // Stake to hotkey account, and check if the result is ok assert_ok!(SubtensorModule::add_stake( @@ -4003,7 +4019,7 @@ fn test_remove_stake_limit_ok() { let limit_price = (current_price.to_num::() * 990_000_000_f64) as u64; // Alpha unstaked - calculated using formula from delta_in() - let expected_alpha_reduction = (0.00138 * alpha_in.to_num::()) as u64; + let expected_alpha_reduction = (0.00138 * (alpha_in.to_u64() as f64)) as u64; let fee: u64 = (expected_alpha_reduction as f64 * 0.003) as u64; // Remove stake with slippage safety @@ -4011,7 +4027,7 @@ fn test_remove_stake_limit_ok() { RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, netuid, - alpha_before / 2, + alpha_before / 2.into(), limit_price, true )); @@ -4024,8 +4040,8 @@ fn test_remove_stake_limit_ok() { // Check if stake has decreased properly assert_abs_diff_eq!( alpha_before - alpha_after, - expected_alpha_reduction + fee, - epsilon = expected_alpha_reduction / 10, + AlphaCurrency::from(expected_alpha_reduction + fee), + epsilon = AlphaCurrency::from(expected_alpha_reduction / 10), ); }); } @@ -4035,8 +4051,8 @@ fn test_remove_stake_limit_fill_or_kill() { new_test_ext(1).execute_with(|| { let hotkey_account_id = U256::from(533453); let coldkey_account_id = U256::from(55453); - let stake_amount = 300_000_000_000; - let unstake_amount = 150_000_000_000; + let stake_amount = AlphaCurrency::from(300_000_000_000); + let unstake_amount = AlphaCurrency::from(150_000_000_000); // add network let netuid = add_dynamic_network(&hotkey_account_id, &coldkey_account_id); @@ -4051,9 +4067,9 @@ fn test_remove_stake_limit_fill_or_kill() { // Forse-set alpha in and tao reserve to make price equal 1.5 let tao_reserve: U96F32 = U96F32::from_num(150_000_000_000_u64); - let alpha_in: U96F32 = U96F32::from_num(100_000_000_000_u64); + let alpha_in = AlphaCurrency::from(100_000_000_000); SubnetTAO::::insert(netuid, tao_reserve.to_num::()); - SubnetAlphaIn::::insert(netuid, alpha_in.to_num::()); + SubnetAlphaIn::::insert(netuid, alpha_in); let current_price = ::SwapInterface::current_alpha_price(netuid.into()); assert_eq!(current_price, U96F32::from_num(1.5)); @@ -4079,7 +4095,7 @@ fn test_remove_stake_limit_fill_or_kill() { RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, netuid, - unstake_amount / 100, + unstake_amount / 100.into(), limit_price, false ),); @@ -4098,10 +4114,10 @@ fn test_add_stake_specific_stake_into_subnet_fail() { let existing_shares: U64F64 = U64F64::from_num(161_986_254).saturating_div(U64F64::from_num(u64::MAX)); - let existing_stake = 36_711_495_953; + let existing_stake = AlphaCurrency::from(36_711_495_953); let tao_in = 2_409_892_148_947; - let alpha_in = 15_358_708_513_716; + let alpha_in = AlphaCurrency::from(15_358_708_513_716); let tao_staked = 200_000_000; @@ -4138,15 +4154,17 @@ fn test_add_stake_specific_stake_into_subnet_fail() { ); // Add stake as new hotkey - let expected_alpha = ::SwapInterface::swap( - netuid.into(), - OrderType::Buy, - tao_staked, - ::SwapInterface::max_price(), - true, - ) - .map(|v| v.amount_paid_out) - .unwrap_or_default(); + let expected_alpha = AlphaCurrency::from( + ::SwapInterface::swap( + netuid.into(), + OrderType::Buy, + tao_staked, + ::SwapInterface::max_price(), + true, + ) + .map(|v| v.amount_paid_out) + .unwrap_or_default(), + ); assert_ok!(SubtensorModule::add_stake( RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, @@ -4155,7 +4173,7 @@ fn test_add_stake_specific_stake_into_subnet_fail() { )); // Check we have non-zero staked - assert!(expected_alpha > 0); + assert!(expected_alpha > AlphaCurrency::ZERO); assert_abs_diff_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( &hotkey_account_id, @@ -4163,7 +4181,7 @@ fn test_add_stake_specific_stake_into_subnet_fail() { netuid ), expected_alpha, - epsilon = expected_alpha / 1000 + epsilon = expected_alpha / 1000.into() ); }); } @@ -4197,7 +4215,9 @@ fn test_remove_99_9991_per_cent_stake_removes_all() { &coldkey_account_id, netuid, ); - let remove_amount = (U64F64::from_num(alpha) * U64F64::from_num(0.999991)).to_num::(); + let remove_amount = AlphaCurrency::from( + (U64F64::from_num(alpha) * U64F64::from_num(0.999991)).to_num::(), + ); // we expected the entire stake to be returned let (expected_balance, _) = mock::swap_alpha_to_tao(netuid, alpha); assert_ok!(SubtensorModule::remove_stake( @@ -4222,7 +4242,7 @@ fn test_remove_99_9991_per_cent_stake_removes_all() { &coldkey_account_id, netuid, ); - assert_eq!(new_alpha, 0); + assert!(new_alpha.is_zero()); }); } @@ -4256,12 +4276,15 @@ fn test_remove_99_9989_per_cent_stake_leaves_a_little() { &coldkey_account_id, netuid, ); - let fee = mock::swap_alpha_to_tao(netuid, (alpha as f64 * 0.99) as u64).1 + fee; + let fee = + mock::swap_alpha_to_tao(netuid, ((alpha.to_u64() as f64 * 0.99) as u64).into()).1 + fee; assert_ok!(SubtensorModule::remove_stake( RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, netuid, - (U64F64::from_num(alpha) * U64F64::from_num(0.99)).to_num::() + (U64F64::from_num(alpha.to_u64()) * U64F64::from_num(0.99)) + .to_num::() + .into() )); // Check that all alpha was unstaked and 99% TAO balance was returned (less fees) @@ -4281,7 +4304,11 @@ fn test_remove_99_9989_per_cent_stake_leaves_a_little() { &coldkey_account_id, netuid, ); - assert_abs_diff_eq!(new_alpha, (alpha as f64 * 0.01) as u64, epsilon = 10); + assert_abs_diff_eq!( + new_alpha, + AlphaCurrency::from((alpha.to_u64() as f64 * 0.01) as u64), + epsilon = 10.into() + ); }); } @@ -4292,8 +4319,8 @@ fn test_move_stake_limit_partial() { let subnet_owner_hotkey = U256::from(1002); let coldkey = U256::from(1); let hotkey = U256::from(2); - let stake_amount = 150_000_000_000; - let move_amount = 150_000_000_000; + let stake_amount = AlphaCurrency::from(150_000_000_000); + let move_amount = AlphaCurrency::from(150_000_000_000); // add network let origin_netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); @@ -4312,11 +4339,11 @@ fn test_move_stake_limit_partial() { // Forse-set alpha in and tao reserve to make price equal 1.5 on both origin and destination, // but there's much more liquidity on destination, so its price wouldn't go up when restaked let tao_reserve: U96F32 = U96F32::from_num(150_000_000_000_u64); - let alpha_in: U96F32 = U96F32::from_num(100_000_000_000_u64); + let alpha_in = AlphaCurrency::from(100_000_000_000); SubnetTAO::::insert(origin_netuid, tao_reserve.to_num::()); - SubnetAlphaIn::::insert(origin_netuid, alpha_in.to_num::()); + SubnetAlphaIn::::insert(origin_netuid, alpha_in); SubnetTAO::::insert(destination_netuid, (tao_reserve * 100_000).to_num::()); - SubnetAlphaIn::::insert(destination_netuid, (alpha_in * 100_000).to_num::()); + SubnetAlphaIn::::insert(destination_netuid, alpha_in * 100_000.into()); let current_price = ::SwapInterface::current_alpha_price(origin_netuid.into()); assert_eq!(current_price, U96F32::from_num(1.5)); @@ -4342,7 +4369,11 @@ fn test_move_stake_limit_partial() { origin_netuid, ); - assert_abs_diff_eq!(new_alpha, 149_000_000_000, epsilon = 100_000_000,); + assert_abs_diff_eq!( + new_alpha, + AlphaCurrency::from(149_000_000_000), + epsilon = 100_000_000.into() + ); }); } @@ -4354,7 +4385,7 @@ fn test_unstake_all_hits_liquidity_min() { let coldkey = U256::from(1); let hotkey = U256::from(2); - let stake_amount = 190_000_000_000; // 190 Alpha + let stake_amount = AlphaCurrency::from(190_000_000_000); // 190 Alpha let netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey); register_ok_neuron(netuid, hotkey, coldkey, 192213123); @@ -4369,14 +4400,18 @@ fn test_unstake_all_hits_liquidity_min() { // Setup the Alpha pool so that removing all the Alpha will bring liqudity below the minimum let remaining_tao = I96F32::from_num(u64::from(mock::SwapMinimumReserve::get()) - 1) .saturating_sub(I96F32::from(1)); - let alpha_reserves = I110F18::from(stake_amount + 10_000_000); + let alpha_reserves = I110F18::from(stake_amount.to_u64() + 10_000_000); let alpha = stake_amount; let k = I110F18::from_fixed(remaining_tao) - .saturating_mul(alpha_reserves.saturating_add(I110F18::from(alpha))); + .saturating_mul(alpha_reserves.saturating_add(I110F18::from(u64::from(alpha)))); let tao_reserves = k.safe_div(alpha_reserves); - mock::setup_reserves(netuid, tao_reserves.to_num(), alpha_reserves.to_num()); + mock::setup_reserves( + netuid, + tao_reserves.to_num(), + alpha_reserves.to_num::().into(), + ); // Try to unstake, but we reduce liquidity too far @@ -4388,7 +4423,7 @@ fn test_unstake_all_hits_liquidity_min() { // Expect nothing to be unstaked let new_alpha = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey, &coldkey, netuid); - assert_abs_diff_eq!(new_alpha, stake_amount, epsilon = 0,); + assert_abs_diff_eq!(new_alpha, stake_amount, epsilon = AlphaCurrency::ZERO); }); } @@ -4421,16 +4456,16 @@ fn test_unstake_all_alpha_hits_liquidity_min() { .saturating_sub(I96F32::from(1)); let alpha = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey, &coldkey, netuid); - let alpha_reserves = I110F18::from(alpha + 10_000_000); + let alpha_reserves = I110F18::from(u64::from(alpha) + 10_000_000); let k = I110F18::from_fixed(remaining_tao) - .saturating_mul(alpha_reserves.saturating_add(I110F18::from(alpha))); + .saturating_mul(alpha_reserves.saturating_add(I110F18::from(u64::from(alpha)))); let tao_reserves = k.safe_div(alpha_reserves); mock::setup_reserves( netuid, tao_reserves.to_num::() / 100_u64, - alpha_reserves.to_num(), + alpha_reserves.to_num::().into(), ); // Try to unstake, but we reduce liquidity too far @@ -4473,7 +4508,7 @@ fn test_unstake_all_alpha_works() { )); // Setup the pool so that removing all the TAO will keep liq above min - mock::setup_reserves(netuid, stake_amount * 10, stake_amount * 100); + mock::setup_reserves(netuid, stake_amount * 10, (stake_amount * 100).into()); // Unstake all alpha to root assert_ok!(SubtensorModule::unstake_all_alpha( @@ -4483,13 +4518,13 @@ fn test_unstake_all_alpha_works() { let new_alpha = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey, &coldkey, netuid); - assert_abs_diff_eq!(new_alpha, 0, epsilon = 1_000); + assert_abs_diff_eq!(new_alpha, AlphaCurrency::ZERO, epsilon = 1_000.into()); let new_root = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( &hotkey, &coldkey, NetUid::ROOT, ); - assert!(new_root > 100_000); + assert!(new_root > 100_000.into()); }); } @@ -4519,7 +4554,11 @@ fn test_unstake_all_works() { )); // Setup the pool so that removing all the TAO will keep liq above min - mock::setup_reserves(netuid, stake_amount * 10, stake_amount * 100); + mock::setup_reserves( + netuid, + stake_amount * 10, + AlphaCurrency::from(stake_amount * 100), + ); // Unstake all alpha to free balance assert_ok!(SubtensorModule::unstake_all( @@ -4529,7 +4568,7 @@ fn test_unstake_all_works() { let new_alpha = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey, &coldkey, netuid); - assert_abs_diff_eq!(new_alpha, 0, epsilon = 1_000); + assert_abs_diff_eq!(new_alpha, AlphaCurrency::ZERO, epsilon = 1_000.into()); let new_balance = SubtensorModule::get_coldkey_balance(&coldkey); assert!(new_balance > 100_000); }); @@ -4549,8 +4588,8 @@ fn test_stake_into_subnet_ok() { // Forse-set alpha in and tao reserve to make price equal 0.01 let tao_reserve = U96F32::from_num(100_000_000_000_u64); - let alpha_in = U96F32::from_num(1_000_000_000_000_u64); - mock::setup_reserves(netuid, tao_reserve.to_num(), alpha_in.to_num()); + let alpha_in = AlphaCurrency::from(1_000_000_000_000); + mock::setup_reserves(netuid, tao_reserve.to_num(), alpha_in); let current_price = ::SwapInterface::current_alpha_price(netuid.into()) .to_num::(); @@ -4577,7 +4616,7 @@ fn test_stake_into_subnet_ok() { // Check if stake has increased assert_abs_diff_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey, &coldkey, netuid) - as f64, + .to_u64() as f64, expected_stake, epsilon = expected_stake / 1000., ); @@ -4598,8 +4637,8 @@ fn test_stake_into_subnet_low_amount() { // Forse-set alpha in and tao reserve to make price equal 0.01 let tao_reserve = U96F32::from_num(100_000_000_000_u64); - let alpha_in = U96F32::from_num(1_000_000_000_000_u64); - mock::setup_reserves(netuid, tao_reserve.to_num(), alpha_in.to_num()); + let alpha_in = AlphaCurrency::from(1_000_000_000_000); + mock::setup_reserves(netuid, tao_reserve.to_num(), alpha_in); let current_price = ::SwapInterface::current_alpha_price(netuid.into()) .to_num::(); @@ -4621,14 +4660,13 @@ fn test_stake_into_subnet_low_amount() { amount, u64::MAX, )); - let expected_stake = ((amount as f64) * 0.997 / current_price) as u64; + let expected_stake = AlphaCurrency::from(((amount as f64) * 0.997 / current_price) as u64); // Check if stake has increased assert_abs_diff_eq!( - SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey, &coldkey, netuid) - as u64, + SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey, &coldkey, netuid), expected_stake, - epsilon = expected_stake / 100, + epsilon = expected_stake / 100.into() ); }); } @@ -4647,8 +4685,8 @@ fn test_unstake_from_subnet_low_amount() { // Forse-set alpha in and tao reserve to make price equal 0.01 let tao_reserve = U96F32::from_num(100_000_000_000_u64); - let alpha_in = U96F32::from_num(1_000_000_000_000_u64); - mock::setup_reserves(netuid, tao_reserve.to_num(), alpha_in.to_num()); + let alpha_in = AlphaCurrency::from(1_000_000_000_000); + mock::setup_reserves(netuid, tao_reserve.to_num(), alpha_in); // Initialize swap v3 assert_ok!(::SwapInterface::swap( @@ -4682,7 +4720,7 @@ fn test_unstake_from_subnet_low_amount() { // Check if stake is zero assert_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey, &coldkey, netuid), - 0, + AlphaCurrency::ZERO, ); }); } @@ -4701,8 +4739,8 @@ fn test_stake_into_subnet_prohibitive_limit() { // Forse-set alpha in and tao reserve to make price equal 0.01 let tao_reserve = U96F32::from_num(100_000_000_000_u64); - let alpha_in = U96F32::from_num(1_000_000_000_000_u64); - mock::setup_reserves(netuid, tao_reserve.to_num(), alpha_in.to_num()); + let alpha_in = AlphaCurrency::from(1_000_000_000_000); + mock::setup_reserves(netuid, tao_reserve.to_num(), alpha_in); // Initialize swap v3 assert_ok!(::SwapInterface::swap( @@ -4734,7 +4772,7 @@ fn test_stake_into_subnet_prohibitive_limit() { &coldkey, netuid ), - 0_u64 + AlphaCurrency::ZERO ); // Check if balance has NOT decreased @@ -4756,8 +4794,8 @@ fn test_unstake_from_subnet_prohibitive_limit() { // Forse-set alpha in and tao reserve to make price equal 0.01 let tao_reserve = U96F32::from_num(100_000_000_000_u64); - let alpha_in = U96F32::from_num(1_000_000_000_000_u64); - mock::setup_reserves(netuid, tao_reserve.to_num(), alpha_in.to_num()); + let alpha_in = AlphaCurrency::from(1_000_000_000_000); + mock::setup_reserves(netuid, tao_reserve.to_num(), alpha_in); // Initialize swap v3 assert_ok!(::SwapInterface::swap( @@ -4829,8 +4867,8 @@ fn test_unstake_full_amount() { // Forse-set alpha in and tao reserve to make price equal 0.01 let tao_reserve = U96F32::from_num(100_000_000_000_u64); - let alpha_in = U96F32::from_num(1_000_000_000_000_u64); - mock::setup_reserves(netuid, tao_reserve.to_num(), alpha_in.to_num()); + let alpha_in = AlphaCurrency::from(1_000_000_000_000); + mock::setup_reserves(netuid, tao_reserve.to_num(), alpha_in); // Initialize swap v3 assert_ok!(::SwapInterface::swap( @@ -4872,7 +4910,7 @@ fn test_unstake_full_amount() { &coldkey, netuid ), - 0 + AlphaCurrency::ZERO ); // Check if balance has increased accordingly @@ -4937,8 +4975,8 @@ fn test_swap_fees_tao_correctness() { // Forse-set alpha in and tao reserve to make price equal 0.25 let tao_reserve = U96F32::from_num(100_000_000_000_u64); - let alpha_in = U96F32::from_num(400_000_000_000_u64); - mock::setup_reserves(netuid, tao_reserve.to_num(), alpha_in.to_num()); + let alpha_in = AlphaCurrency::from(400_000_000_000); + mock::setup_reserves(netuid, tao_reserve.to_num(), alpha_in); // Check starting "total TAO" let total_tao_before = @@ -5029,7 +5067,7 @@ fn test_increase_stake_for_hotkey_and_coldkey_on_subnet_adds_to_staking_hotkeys_ &hotkey, &coldkey, netuid, - stake_amount, + stake_amount.into(), ); // Check entry exists in the staking hotkeys map @@ -5045,7 +5083,7 @@ fn test_increase_stake_for_hotkey_and_coldkey_on_subnet_adds_to_staking_hotkeys_ &hotkey, &coldkey1, netuid, - stake_amount, + stake_amount.into(), ); // Check entry exists in the staking hotkeys map for coldkey1 @@ -5079,8 +5117,8 @@ fn test_default_min_stake_sufficiency() { // 1% of TAO max supply // 0.01 Alpha price let tao_reserve = U96F32::from_num(210_000_000_000_000_u64); - let alpha_in = U96F32::from_num(21_000_000_000_000_000_u64); - mock::setup_reserves(netuid, tao_reserve.to_num(), alpha_in.to_num()); + let alpha_in = AlphaCurrency::from(21_000_000_000_000_000); + mock::setup_reserves(netuid, tao_reserve.to_num(), alpha_in); let current_price_before = ::SwapInterface::current_alpha_price(netuid.into()); @@ -5106,7 +5144,7 @@ fn test_default_min_stake_sufficiency() { netuid, user_alpha, )); - let fee_unstake = (fee_rate * user_alpha as f64) as u64; + let fee_unstake = (fee_rate * user_alpha.to_u64() as f64) as u64; let current_price_after_unstake = ::SwapInterface::current_alpha_price(netuid.into()); @@ -5138,8 +5176,8 @@ fn test_update_position_fees() { // Forse-set alpha in and tao reserve to make price equal 0.25 let tao_reserve = U96F32::from_num(100_000_000_000_u64); - let alpha_in = U96F32::from_num(400_000_000_000_u64); - mock::setup_reserves(netuid, tao_reserve.to_num(), alpha_in.to_num()); + let alpha_in = AlphaCurrency::from(400_000_000_000); + mock::setup_reserves(netuid, tao_reserve.to_num(), alpha_in); // Get alpha for owner assert_ok!(SubtensorModule::add_stake( @@ -5271,7 +5309,7 @@ fn setup_positions(netuid: NetUid) { &U256::from(hotkey), &U256::from(coldkey), netuid.into(), - 1_000_000_000_000_000, + 1_000_000_000_000_000.into(), ); let tick_low = price_to_tick(low_price); diff --git a/pallets/subtensor/src/tests/staking2.rs b/pallets/subtensor/src/tests/staking2.rs index 0c98a83bb1..b42b437ea2 100644 --- a/pallets/subtensor/src/tests/staking2.rs +++ b/pallets/subtensor/src/tests/staking2.rs @@ -6,6 +6,7 @@ use frame_support::{ weights::Weight, }; use sp_core::U256; +use subtensor_runtime_common::{Alpha as AlphaCurrency, Currency}; use subtensor_swap_interface::SwapHandler; use super::mock; @@ -24,7 +25,7 @@ fn test_stake_base_case() { // Initialize subnet with some existing TAO and Alpha let initial_subnet_tao = 10_000_000_000; // 10 TAO - let initial_subnet_alpha = 5_000_000_000; // 5 Alpha + let initial_subnet_alpha = AlphaCurrency::from(5_000_000_000); // 5 Alpha mock::setup_reserves(netuid, initial_subnet_tao, initial_subnet_alpha); SubnetAlphaOut::::insert(netuid, initial_subnet_alpha); @@ -33,13 +34,15 @@ fn test_stake_base_case() { // Perform swap let (alpha_expected, fee) = mock::swap_tao_to_alpha(netuid, tao_to_swap); - let alpha_received = SubtensorModule::swap_tao_for_alpha( - netuid, - tao_to_swap, - ::SwapInterface::max_price(), - ) - .unwrap() - .amount_paid_out; + let alpha_received = AlphaCurrency::from( + SubtensorModule::swap_tao_for_alpha( + netuid, + tao_to_swap, + ::SwapInterface::max_price(), + ) + .unwrap() + .amount_paid_out, + ); // Verify correct alpha calculation using constant product formula assert_eq!( @@ -85,7 +88,7 @@ fn test_share_based_staking() { let netuid = NetUid::from(1); let primary_hotkey = U256::from(1); let primary_coldkey = U256::from(2); - let stake_amount = 1_000_000_000; // 1 TAO + let stake_amount = AlphaCurrency::from(1_000_000_000); // 1 Alpha stake increase // Test Case 1: Initial Stake // The first stake should create shares 1:1 with the staked amount @@ -133,7 +136,9 @@ fn test_share_based_staking() { initial_stake + stake_amount ); assert!( - (stake_after_second as i64 - (initial_stake + stake_amount) as i64).abs() <= 1, + (stake_after_second.to_u64() as i64 - (initial_stake + stake_amount).to_u64() as i64) + .abs() + <= 1, "Total stake should double after second deposit (within rounding error)" ); @@ -153,7 +158,10 @@ fn test_share_based_staking() { stake_after_second + stake_amount ); assert!( - (stake_after_direct as i64 - (stake_after_second + stake_amount) as i64).abs() <= 1, + (stake_after_direct.to_u64() as i64 + - (stake_after_second + stake_amount).to_u64() as i64) + .abs() + <= 1, "Direct hotkey stake should be added to existing stake (within rounding error)" ); @@ -179,7 +187,7 @@ fn test_share_based_staking() { stake_amount ); assert!( - (secondary_stake as i64 - (stake_amount) as i64).abs() <= 1, + (secondary_stake.to_u64() as i64 - stake_amount.to_u64() as i64).abs() <= 1, "Secondary coldkey should receive full stake amount (within rounding error)" ); @@ -193,7 +201,10 @@ fn test_share_based_staking() { stake_after_direct + stake_amount ); assert!( - (total_hotkey_stake as i64 - (stake_after_direct + stake_amount) as i64).abs() <= 1, + (total_hotkey_stake.to_u64() as i64 + - (stake_after_direct + stake_amount).to_u64() as i64) + .abs() + <= 1, "Total hotkey stake should match sum of all coldkey stakes" ); @@ -212,10 +223,12 @@ fn test_share_based_staking() { ); // Calculate expected proportional distribution - let primary_expected = stake_after_direct as f64 - + stake_amount as f64 * (stake_after_direct as f64 / total_hotkey_stake as f64); - let secondary_expected = secondary_stake as f64 - + stake_amount as f64 * (secondary_stake as f64 / total_hotkey_stake as f64); + let primary_expected = stake_after_direct.to_u64() as f64 + + stake_amount.to_u64() as f64 + * (stake_after_direct.to_u64() as f64 / total_hotkey_stake.to_u64() as f64); + let secondary_expected = secondary_stake.to_u64() as f64 + + stake_amount.to_u64() as f64 + * (secondary_stake.to_u64() as f64 / total_hotkey_stake.to_u64() as f64); log::info!( "Primary final stake: {} (expected: {})", @@ -229,11 +242,11 @@ fn test_share_based_staking() { ); assert!( - (primary_final_stake as f64 - primary_expected).abs() <= 1.0, + (primary_final_stake.to_u64() as f64 - primary_expected).abs() <= 1.0, "Primary stake should increase proportionally" ); assert!( - (secondary_final_stake as f64 - secondary_expected).abs() <= 1.0, + (secondary_final_stake.to_u64() as f64 - secondary_expected).abs() <= 1.0, "Secondary stake should increase proportionally" ); @@ -258,7 +271,10 @@ fn test_share_based_staking() { primary_final_stake - stake_amount ); assert!( - (primary_after_removal as i64 - (primary_final_stake - stake_amount) as i64).abs() <= 1, + (primary_after_removal.to_u64() as i64 + - (primary_final_stake - stake_amount).to_u64() as i64) + .abs() + <= 1, "Stake removal should decrease balance by exact amount" ); @@ -281,7 +297,9 @@ fn test_share_based_staking() { secondary_final_stake - stake_amount ); assert!( - (secondary_after_removal as i64 - (secondary_final_stake - stake_amount) as i64).abs() + (secondary_after_removal.to_u64() as i64 + - (secondary_final_stake - stake_amount).to_u64() as i64) + .abs() <= 1, "Stake removal should decrease balance by exact amount" ); @@ -297,7 +315,9 @@ fn test_share_based_staking() { primary_after_removal + secondary_after_removal ); assert!( - (final_total as i64 - (primary_after_removal + secondary_after_removal) as i64).abs() + (final_total.to_u64() as i64 + - (primary_after_removal + secondary_after_removal).to_u64() as i64) + .abs() <= 1, "Final total should match sum of remaining stakes" ); @@ -309,7 +329,7 @@ fn test_share_based_staking() { &primary_hotkey, &primary_coldkey, netuid, - 0, + AlphaCurrency::ZERO, ); let zero_stake = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( &primary_hotkey, @@ -327,7 +347,7 @@ fn test_share_based_staking() { &primary_coldkey, netuid, ); - let excessive_amount = available_stake + 1000; + let excessive_amount = available_stake + 1000.into(); log::info!( "Attempting to remove excessive stake: {} + 1000 = {}", available_stake, @@ -386,7 +406,7 @@ fn test_share_based_staking() { netuid, ); assert!( - non_existent_coldkey_stake == 0, + non_existent_coldkey_stake.is_zero(), "Removing stake from non-existent coldkey should not change the stake" ); }); @@ -410,8 +430,8 @@ fn test_share_based_staking_denominator_precision() { let netuid = NetUid::from(1); let hotkey1 = U256::from(1); let coldkey1 = U256::from(2); - let stake_amount = test_case.0; - let unstake_amount = test_case.1; + let stake_amount = AlphaCurrency::from(test_case.0); + let unstake_amount = AlphaCurrency::from(test_case.1); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &hotkey1, @@ -420,8 +440,10 @@ fn test_share_based_staking_denominator_precision() { stake_amount, ); assert_eq!( - Alpha::::get((hotkey1, coldkey1, netuid)), - stake_amount + stake_amount, + Alpha::::get((hotkey1, coldkey1, netuid)) + .to_num::() + .into(), ); SubtensorModule::decrease_stake_for_hotkey_and_coldkey_on_subnet( &hotkey1, @@ -433,13 +455,15 @@ fn test_share_based_staking_denominator_precision() { let stake1 = SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( &hotkey1, &coldkey1, netuid, ); - let expected_remaining_stake = - if (stake_amount as f64 - unstake_amount as f64) / (stake_amount as f64) <= 0.00001 - { - 0 - } else { - stake_amount - unstake_amount - }; + let expected_remaining_stake = if (stake_amount.to_u64() as f64 + - unstake_amount.to_u64() as f64) + / (stake_amount.to_u64() as f64) + <= 0.00001 + { + AlphaCurrency::ZERO + } else { + stake_amount - unstake_amount + }; assert_eq!(stake1, expected_remaining_stake); }); }); @@ -465,9 +489,9 @@ fn test_share_based_staking_stake_unstake_inject() { let hotkey1 = U256::from(1); let coldkey1 = U256::from(2); let coldkey2 = U256::from(3); - let stake_amount = test_case.0; - let unstake_amount = test_case.1; - let inject_amount = test_case.2; + let stake_amount = AlphaCurrency::from(test_case.0); + let unstake_amount = AlphaCurrency::from(test_case.1); + let inject_amount = AlphaCurrency::from(test_case.2); let tolerance = test_case.3; SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( @@ -504,14 +528,16 @@ fn test_share_based_staking_stake_unstake_inject() { ); assert!( - (stake1 as i64 - - (stake_amount as i64 - unstake_amount as i64 + (inject_amount / 2) as i64)) + (stake1.to_u64() as i64 + - (stake_amount.to_u64() as i64 - unstake_amount.to_u64() as i64 + + (inject_amount.to_u64() / 2) as i64)) .abs() <= tolerance ); assert!( - (stake2 as i64 - - (stake_amount as i64 - unstake_amount as i64 + (inject_amount / 2) as i64)) + (stake2.to_u64() as i64 + - (stake_amount.to_u64() as i64 - unstake_amount.to_u64() as i64 + + (inject_amount.to_u64() / 2) as i64)) .abs() <= tolerance ); @@ -535,9 +561,9 @@ fn test_share_based_staking_stake_inject_stake_new() { let hotkey1 = U256::from(1); let coldkey1 = U256::from(2); let coldkey2 = U256::from(3); - let stake_amount = test_case.0; - let inject_amount = test_case.1; - let stake_amount_2 = test_case.2; + let stake_amount = AlphaCurrency::from(test_case.0); + let inject_amount = AlphaCurrency::from(test_case.1); + let stake_amount_2 = AlphaCurrency::from(test_case.2); let tolerance = test_case.3; SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( @@ -561,8 +587,12 @@ fn test_share_based_staking_stake_inject_stake_new() { &hotkey1, &coldkey2, netuid, ); - assert!((stake1 as i64 - (stake_amount + inject_amount) as i64).abs() <= tolerance); - assert!((stake2 as i64 - stake_amount_2 as i64).abs() <= tolerance); + assert!( + (stake1.to_u64() as i64 - (stake_amount.to_u64() + inject_amount.to_u64()) as i64) + .abs() + <= tolerance + ); + assert!((stake2.to_u64() as i64 - stake_amount_2.to_u64() as i64).abs() <= tolerance); }); }); } @@ -641,19 +671,19 @@ fn test_stake_fee_api() { let netuid1 = NetUid::from(2); let root_netuid = NetUid::ROOT; - let alpha_divs = 100_000_000_000; - let total_hotkey_alpha = 100_000_000_000; + let alpha_divs = AlphaCurrency::from(100_000_000_000); + let total_hotkey_alpha = AlphaCurrency::from(100_000_000_000); let tao_in = 100_000_000_000; // 100 TAO let reciprocal_price = 2; // 1 / price let stake_amount = 100_000_000_000; // Setup alpha out - SubnetAlphaOut::::insert(netuid0, 100_000_000_000); - SubnetAlphaOut::::insert(netuid1, 100_000_000_000); + SubnetAlphaOut::::insert(netuid0, AlphaCurrency::from(100_000_000_000)); + SubnetAlphaOut::::insert(netuid1, AlphaCurrency::from(100_000_000_000)); // Set pools using price - SubnetAlphaIn::::insert(netuid0, tao_in * reciprocal_price); + SubnetAlphaIn::::insert(netuid0, AlphaCurrency::from(tao_in * reciprocal_price)); SubnetTAO::::insert(netuid0, tao_in); - SubnetAlphaIn::::insert(netuid1, tao_in * reciprocal_price); + SubnetAlphaIn::::insert(netuid1, AlphaCurrency::from(tao_in * reciprocal_price)); SubnetTAO::::insert(netuid1, tao_in); // Setup alpha divs for hotkey1 @@ -787,8 +817,8 @@ fn test_stake_fee_calculation() { SubnetMechanism::::insert(netuid0, 1); SubnetMechanism::::insert(netuid1, 1); - let alpha_divs = 100_000_000_000; - let total_hotkey_alpha = 100_000_000_000; + let alpha_divs = AlphaCurrency::from(100_000_000_000); + let total_hotkey_alpha = AlphaCurrency::from(100_000_000_000); let tao_in = 100_000_000_000; // 100 TAO let reciprocal_price = 2; // 1 / price let stake_amount = 100_000_000_000_u64; @@ -796,11 +826,19 @@ fn test_stake_fee_calculation() { let default_fee = 0; // FIXME: DefaultStakingFee is deprecated // Setup alpha out - SubnetAlphaOut::::insert(netuid0, 100_000_000_000); - SubnetAlphaOut::::insert(netuid1, 100_000_000_000); + SubnetAlphaOut::::insert(netuid0, AlphaCurrency::from(100_000_000_000)); + SubnetAlphaOut::::insert(netuid1, AlphaCurrency::from(100_000_000_000)); // Set pools using price - mock::setup_reserves(netuid0, tao_in, tao_in * reciprocal_price); - mock::setup_reserves(netuid1, tao_in, tao_in * reciprocal_price); + mock::setup_reserves( + netuid0, + tao_in, + AlphaCurrency::from(tao_in * reciprocal_price), + ); + mock::setup_reserves( + netuid1, + tao_in, + AlphaCurrency::from(tao_in * reciprocal_price), + ); // Setup alpha divs for hotkey1 AlphaDividendsPerSubnet::::insert(netuid0, hotkey1, alpha_divs); diff --git a/pallets/subtensor/src/tests/subnet.rs b/pallets/subtensor/src/tests/subnet.rs index ebac3e786d..8234e2a2d5 100644 --- a/pallets/subtensor/src/tests/subnet.rs +++ b/pallets/subtensor/src/tests/subnet.rs @@ -1,6 +1,7 @@ use frame_support::{assert_noop, assert_ok}; use frame_system::Config; use sp_core::U256; +use subtensor_runtime_common::Alpha as AlphaCurrency; use super::mock; use super::mock::*; @@ -19,7 +20,7 @@ fn test_do_start_call_ok() { add_network_without_emission_block(netuid, tempo, 0); assert_eq!(FirstEmissionBlockNumber::::get(netuid), None); - mock::setup_reserves(netuid, 1_000_000_000, 1_000_000_000); + mock::setup_reserves(netuid, 1_000_000_000, 1_000_000_000.into()); // account 0 is the default owner for any subnet assert_eq!(SubnetOwner::::get(netuid), coldkey_account_id); @@ -65,7 +66,7 @@ fn test_do_start_call_fail_not_owner() { //add network SubtensorModule::set_burn(netuid, burn_cost); add_network_without_emission_block(netuid, tempo, 0); - mock::setup_reserves(netuid, 1_000_000_000, 1_000_000_000); + mock::setup_reserves(netuid, 1_000_000_000, 1_000_000_000.into()); // Give it some $$$ in his coldkey balance SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, 10000); @@ -95,7 +96,7 @@ fn test_do_start_call_fail_with_cannot_start_call_now() { //add network SubtensorModule::set_burn(netuid, burn_cost); add_network_without_emission_block(netuid, tempo, 0); - mock::setup_reserves(netuid, 1_000_000_000, 1_000_000_000); + mock::setup_reserves(netuid, 1_000_000_000, 1_000_000_000.into()); // Give it some $$$ in his coldkey balance SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, 10000); @@ -126,7 +127,7 @@ fn test_do_start_call_fail_for_set_again() { add_network_without_emission_block(netuid, tempo, 0); assert_eq!(FirstEmissionBlockNumber::::get(netuid), None); - mock::setup_reserves(netuid, 1_000_000_000, 1_000_000_000); + mock::setup_reserves(netuid, 1_000_000_000, 1_000_000_000.into()); // Give it some $$$ in his coldkey balance SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id, 10000); @@ -167,7 +168,7 @@ fn test_do_start_call_ok_with_same_block_number_after_coinbase() { add_network_without_emission_block(netuid, tempo, 0); assert_eq!(FirstEmissionBlockNumber::::get(netuid), None); - mock::setup_reserves(netuid, 1_000_000_000, 1_000_000_000); + mock::setup_reserves(netuid, 1_000_000_000, 1_000_000_000.into()); assert_eq!(SubnetOwner::::get(netuid), coldkey_account_id); @@ -287,7 +288,7 @@ fn test_subtoken_enable_reject_trading_before_enable() { let hotkey_account_2_id: U256 = U256::from(3); let amount = DefaultMinStake::::get() * 10; - let stake_bal = 10_000_000_000; // 10 Alpha + let stake_bal = AlphaCurrency::from(10_000_000_000); // 10 Alpha let limit_price = 1_000_000_000; // not important @@ -299,7 +300,7 @@ fn test_subtoken_enable_reject_trading_before_enable() { // Set liq high enough to not trigger other errors SubnetTAO::::set(netuid, 20_000_000_000); - SubnetAlphaIn::::set(netuid, 20_000_000_000); + SubnetAlphaIn::::set(netuid, AlphaCurrency::from(20_000_000_000)); // Register so staking *could* work register_ok_neuron(netuid, hotkey_account_id, coldkey_account_id, 0); @@ -378,7 +379,7 @@ fn test_subtoken_enable_reject_trading_before_enable() { RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, netuid, - amount, + amount.into(), limit_price, false, ) @@ -389,7 +390,7 @@ fn test_subtoken_enable_reject_trading_before_enable() { RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, netuid, - amount + amount.into() ), Error::::SubtokenDisabled ); @@ -398,7 +399,7 @@ fn test_subtoken_enable_reject_trading_before_enable() { SubtensorModule::recycle_alpha( RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, - amount, + amount.into(), netuid ), Error::::SubtokenDisabled @@ -408,7 +409,7 @@ fn test_subtoken_enable_reject_trading_before_enable() { SubtensorModule::burn_alpha( RuntimeOrigin::signed(coldkey_account_id), hotkey_account_id, - amount, + amount.into(), netuid ), Error::::SubtokenDisabled @@ -421,7 +422,7 @@ fn test_subtoken_enable_reject_trading_before_enable() { hotkey_account_2_id, netuid, netuid2, - amount, + amount.into(), ), Error::::SubtokenDisabled ); @@ -433,7 +434,7 @@ fn test_subtoken_enable_reject_trading_before_enable() { hotkey_account_2_id, netuid, netuid2, - amount, + amount.into(), ), Error::::SubtokenDisabled ); @@ -444,7 +445,7 @@ fn test_subtoken_enable_reject_trading_before_enable() { hotkey_account_id, netuid, netuid2, - amount, + amount.into(), ), Error::::SubtokenDisabled ); @@ -463,16 +464,16 @@ fn test_subtoken_enable_trading_ok_with_enable() { // stake big enough let stake_amount = DefaultMinStake::::get() * 10000; // unstake, transfer, swap just very little - let unstake_amount = DefaultMinStake::::get() * 10; + let unstake_amount = AlphaCurrency::from(DefaultMinStake::::get() * 10); add_network(netuid, 10, 0); add_network(netuid2, 10, 0); let reserve = stake_amount * 1000; - mock::setup_reserves(netuid, reserve, reserve); - mock::setup_reserves(netuid2, reserve, reserve); - SubnetAlphaOut::::insert(netuid, reserve); - SubnetAlphaOut::::insert(netuid2, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid2, reserve, reserve.into()); + SubnetAlphaOut::::insert(netuid, AlphaCurrency::from(reserve)); + SubnetAlphaOut::::insert(netuid2, AlphaCurrency::from(reserve)); // Register so staking works register_ok_neuron(netuid, hotkey_account_id, coldkey_account_id, 0); diff --git a/pallets/subtensor/src/tests/swap_coldkey.rs b/pallets/subtensor/src/tests/swap_coldkey.rs index c58091a7ec..e82205eb50 100644 --- a/pallets/subtensor/src/tests/swap_coldkey.rs +++ b/pallets/subtensor/src/tests/swap_coldkey.rs @@ -12,7 +12,7 @@ use frame_system::{Config, RawOrigin}; use sp_core::{Get, H256, U256}; use sp_runtime::{DispatchError, traits::TxBaseImplication}; use substrate_fixed::types::U96F32; -use subtensor_runtime_common::SubnetInfo; +use subtensor_runtime_common::{Alpha as AlphaCurrency, Currency, SubnetInfo}; use subtensor_swap_interface::{OrderType, SwapHandler}; use super::mock; @@ -91,7 +91,7 @@ fn test_swap_total_coldkey_stake() { register_ok_neuron(netuid, other_hotkey, other_coldkey, 1001000); let reserve = stake * 10; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); assert_ok!(SubtensorModule::add_stake( <::RuntimeOrigin>::signed(old_coldkey), @@ -299,7 +299,7 @@ fn test_swap_idempotency() { let stake = DefaultMinStake::::get() * 10; let reserve = stake * 10; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); // Add a network add_network(netuid, 1, 0); @@ -369,8 +369,8 @@ fn test_swap_with_max_values() { SubtensorModule::add_balance_to_coldkey_account(&old_coldkey2, max_stake + 1_000); let reserve = max_stake * 10; - mock::setup_reserves(netuid, reserve, reserve); - mock::setup_reserves(netuid2, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid2, reserve, reserve.into()); // Stake to hotkey on each subnet. assert_ok!(SubtensorModule::add_stake( @@ -415,8 +415,8 @@ fn test_swap_with_max_values() { ); assert_abs_diff_eq!( SubtensorModule::get_total_stake_for_coldkey(&new_coldkey), - expected_stake1, - epsilon = expected_stake1 / 1000 + expected_stake1.to_u64(), + epsilon = expected_stake1.to_u64() / 1000 ); assert_eq!( SubtensorModule::get_total_stake_for_coldkey(&old_coldkey2), @@ -424,8 +424,8 @@ fn test_swap_with_max_values() { ); assert_abs_diff_eq!( SubtensorModule::get_total_stake_for_coldkey(&new_coldkey2), - expected_stake2, - epsilon = expected_stake2 / 1000 + expected_stake2.to_u64(), + epsilon = expected_stake2.to_u64() / 1000 ); }); } @@ -446,7 +446,7 @@ fn test_swap_with_non_existent_new_coldkey() { SubtensorModule::add_balance_to_coldkey_account(&old_coldkey, stake + 1_000); let reserve = stake * 10; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); // Stake to hotkey. assert_ok!(SubtensorModule::add_stake( @@ -481,7 +481,7 @@ fn test_swap_with_non_existent_new_coldkey() { assert_abs_diff_eq!( actual_stake, expected_stake, - epsilon = expected_stake / 1000 + epsilon = expected_stake / 1000.into() ); }); } @@ -581,7 +581,7 @@ fn test_swap_concurrent_modifications() { let additional_stake = 500_000_000_000; let reserve = (initial_stake + additional_stake) * 1000; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); // Setup initial state add_network(netuid, 1, 1); @@ -682,7 +682,7 @@ fn test_do_swap_coldkey_success() { let free_balance_old = 12345u64 + swap_cost; let reserve = (stake_amount1 + stake_amount2) * 10; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); // Setup initial state add_network(netuid, 13, 0); @@ -874,7 +874,7 @@ fn test_swap_stake_for_coldkey() { ); let reserve = (stake_amount1 + stake_amount2 + stake_amount3) * 10; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); // Stake to hotkeys assert_ok!(SubtensorModule::add_stake( @@ -967,7 +967,7 @@ fn test_swap_stake_for_coldkey() { &old_coldkey, netuid ), - 0 + AlphaCurrency::ZERO ); assert_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( @@ -975,7 +975,7 @@ fn test_swap_stake_for_coldkey() { &old_coldkey, netuid ), - 0 + AlphaCurrency::ZERO ); // Verify TotalHotkeyStake remains unchanged @@ -1028,7 +1028,7 @@ fn test_swap_staking_hotkeys_for_coldkey() { register_ok_neuron(netuid, hotkey2, other_coldkey, 0); let reserve = (stake_amount1 + stake_amount2) * 10; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); // Stake to hotkeys assert_ok!(SubtensorModule::add_stake( @@ -1087,7 +1087,7 @@ fn test_swap_delegated_stake_for_coldkey() { register_ok_neuron(netuid, hotkey2, other_coldkey, 0); let reserve = (stake_amount1 + stake_amount2) * 10; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); // Notice hotkey1 and hotkey2 are Owned by other_coldkey // old_coldkey and new_coldkey therefore delegates stake to them @@ -1122,7 +1122,7 @@ fn test_swap_delegated_stake_for_coldkey() { &old_coldkey, netuid, ); - let fee = (expected_stake_alpha2 as f64 * 0.003) as u64; + let fee = (expected_stake_alpha2.to_u64() as f64 * 0.003) as u64; // Record initial values let initial_total_issuance = SubtensorModule::get_total_issuance(); @@ -1167,7 +1167,7 @@ fn test_swap_delegated_stake_for_coldkey() { &old_coldkey, netuid ), - 0 + AlphaCurrency::ZERO ); assert_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( @@ -1175,7 +1175,7 @@ fn test_swap_delegated_stake_for_coldkey() { &old_coldkey, netuid ), - 0 + AlphaCurrency::ZERO ); // Verify TotalColdkeyStake @@ -1317,9 +1317,9 @@ fn test_coldkey_swap_total() { SubtensorModule::add_balance_to_coldkey_account(&nominator3, stake * 2); let reserve = stake * 10; - mock::setup_reserves(netuid1, reserve, reserve); - mock::setup_reserves(netuid2, reserve, reserve); - mock::setup_reserves(netuid3, reserve, reserve); + mock::setup_reserves(netuid1, reserve, reserve.into()); + mock::setup_reserves(netuid2, reserve, reserve.into()); + mock::setup_reserves(netuid3, reserve, reserve.into()); // Setup initial state add_network(netuid1, 13, 0); @@ -1664,8 +1664,8 @@ fn test_coldkey_delegations() { let stake = DefaultMinStake::::get() * 10; let reserve = stake * 1000; - mock::setup_reserves(netuid, reserve, reserve); - mock::setup_reserves(netuid2, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); + mock::setup_reserves(netuid2, reserve, reserve.into()); add_network(netuid, 13, 0); // root add_network(netuid2, 13, 0); @@ -1719,14 +1719,18 @@ fn test_coldkey_delegations() { epsilon = approx_total_stake / 100 ); assert_eq!( - Alpha::::get((delegate, new_coldkey, netuid)).to_num::(), - expected_stake + expected_stake, + Alpha::::get((delegate, new_coldkey, netuid)) + .to_num::() + .into(), ); assert_eq!(Alpha::::get((delegate, coldkey, netuid)), 0); assert_eq!( - Alpha::::get((delegate, new_coldkey, netuid2)).to_num::(), expected_stake, + Alpha::::get((delegate, new_coldkey, netuid2)) + .to_num::() + .into() ); assert_eq!(Alpha::::get((delegate, coldkey, netuid2)), 0); }); @@ -1810,7 +1814,7 @@ fn test_schedule_swap_coldkey_execution() { let stake_amount = DefaultMinStake::::get() * 10; let reserve = stake_amount * 10; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); add_network(netuid, 13, 0); register_ok_neuron(netuid, hotkey, old_coldkey, 0); @@ -2021,7 +2025,7 @@ fn test_coldkey_swap_delegate_identity_updated() { add_network(netuid, tempo, 0); SubtensorModule::add_balance_to_coldkey_account(&old_coldkey, 100_000_000_000); - mock::setup_reserves(netuid, 1_000_000_000_000, 1_000_000_000_000); + mock::setup_reserves(netuid, 1_000_000_000_000, 1_000_000_000_000.into()); assert_ok!(SubtensorModule::burned_register( <::RuntimeOrigin>::signed(old_coldkey), @@ -2074,7 +2078,7 @@ fn test_coldkey_swap_no_identity_no_changes() { add_network(netuid, tempo, 0); SubtensorModule::add_balance_to_coldkey_account(&old_coldkey, 100_000_000_000); - mock::setup_reserves(netuid, 1_000_000_000_000, 1_000_000_000_000); + mock::setup_reserves(netuid, 1_000_000_000_000, 1_000_000_000_000.into()); assert_ok!(SubtensorModule::burned_register( <::RuntimeOrigin>::signed(old_coldkey), @@ -2111,7 +2115,7 @@ fn test_coldkey_swap_no_identity_no_changes_newcoldkey_exists() { SubtensorModule::set_burn(netuid, burn_cost); add_network(netuid, tempo, 0); SubtensorModule::add_balance_to_coldkey_account(&old_coldkey, 100_000_000_000); - mock::setup_reserves(netuid, 1_000_000_000_000, 1_000_000_000_000); + mock::setup_reserves(netuid, 1_000_000_000_000, 1_000_000_000_000.into()); assert_ok!(SubtensorModule::burned_register( <::RuntimeOrigin>::signed(old_coldkey), @@ -2185,7 +2189,7 @@ fn test_coldkey_in_swap_schedule_prevents_funds_usage() { let stake = 100_000_000_000; let reserve = stake * 100; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); let who = coldkey; // The coldkey signs this transaction @@ -2289,7 +2293,7 @@ fn test_coldkey_in_swap_schedule_prevents_funds_usage() { hotkey, origin_netuid: netuid, destination_netuid: netuid, - alpha_amount: stake, + alpha_amount: stake.into(), }); let result = extension.validate( RawOrigin::Signed(who).into(), @@ -2312,7 +2316,7 @@ fn test_coldkey_in_swap_schedule_prevents_funds_usage() { hotkey, origin_netuid: netuid, destination_netuid: netuid, - alpha_amount: stake, + alpha_amount: stake.into(), limit_price: stake, allow_partial: false, }); @@ -2338,7 +2342,7 @@ fn test_coldkey_in_swap_schedule_prevents_funds_usage() { destination_hotkey: hotkey, origin_netuid: netuid, destination_netuid: netuid, - alpha_amount: stake, + alpha_amount: stake.into(), }); let result = extension.validate( RawOrigin::Signed(who).into(), @@ -2362,7 +2366,7 @@ fn test_coldkey_in_swap_schedule_prevents_funds_usage() { hotkey, origin_netuid: netuid, destination_netuid: netuid, - alpha_amount: stake, + alpha_amount: stake.into(), }); let result = extension.validate( RawOrigin::Signed(who).into(), @@ -2465,7 +2469,7 @@ fn test_coldkey_in_swap_schedule_prevents_funds_usage() { let call = RuntimeCall::SubtensorModule(SubtensorCall::remove_stake { hotkey, netuid, - amount_unstaked: 1_000_000, + amount_unstaked: 1_000_000.into(), }); let result = extension.validate( RawOrigin::Signed(who).into(), @@ -2483,7 +2487,7 @@ fn test_coldkey_in_swap_schedule_prevents_funds_usage() { let call = RuntimeCall::SubtensorModule(SubtensorCall::remove_stake_limit { hotkey, netuid, - amount_unstaked: 1_000_000, + amount_unstaked: 1_000_000.into(), limit_price: 123456789, // should be low enough allow_partial: true, }); @@ -2518,7 +2522,7 @@ fn test_coldkey_in_swap_schedule_prevents_critical_calls() { let stake = 100_000_000_000; let reserve = stake * 10; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); let who = coldkey; // The coldkey signs this transaction diff --git a/pallets/subtensor/src/tests/swap_hotkey.rs b/pallets/subtensor/src/tests/swap_hotkey.rs index 05e095292a..b58b49b916 100644 --- a/pallets/subtensor/src/tests/swap_hotkey.rs +++ b/pallets/subtensor/src/tests/swap_hotkey.rs @@ -8,6 +8,7 @@ use frame_system::{Config, RawOrigin}; use sp_core::{Get, H256, U256}; use sp_runtime::SaturatedConversion; use substrate_fixed::types::U64F64; +use subtensor_runtime_common::Alpha as AlphaCurrency; use subtensor_swap_interface::SwapHandler; use super::mock; @@ -72,14 +73,14 @@ fn test_swap_total_hotkey_stake() { //add network let netuid = add_dynamic_network(&old_hotkey, &coldkey); - mock::setup_reserves(netuid, amount * 100, amount * 100); + mock::setup_reserves(netuid, amount * 100, (amount * 100).into()); // Give it some $$$ in his coldkey balance SubtensorModule::add_balance_to_coldkey_account(&coldkey, amount); // Add stake let (expected_alpha, _) = mock::swap_tao_to_alpha(netuid, amount); - assert!(expected_alpha > 0); + assert!(!expected_alpha.is_zero()); assert_ok!(SubtensorModule::add_stake( RuntimeOrigin::signed(coldkey), old_hotkey, @@ -614,8 +615,8 @@ fn test_swap_hotkey_with_multiple_coldkeys_and_subnets() { register_ok_neuron(netuid1, old_hotkey, coldkey1, 1234); register_ok_neuron(netuid2, old_hotkey, coldkey1, 1234); - mock::setup_reserves(netuid1, stake * 100, stake * 100); - mock::setup_reserves(netuid2, stake * 100, stake * 100); + mock::setup_reserves(netuid1, stake * 100, (stake * 100).into()); + mock::setup_reserves(netuid2, stake * 100, (stake * 100).into()); // Add balance to both coldkeys SubtensorModule::add_balance_to_coldkey_account(&coldkey1, stake + 1_000); @@ -647,8 +648,8 @@ fn test_swap_hotkey_with_multiple_coldkeys_and_subnets() { &coldkey2, netuid2, ); - assert!(ck1_stake > 0); - assert!(ck2_stake > 0); + assert!(!ck1_stake.is_zero()); + assert!(!ck2_stake.is_zero()); let total_hk_stake = SubtensorModule::get_total_stake_for_hotkey(&old_hotkey); assert!(total_hk_stake > 0); @@ -689,7 +690,7 @@ fn test_swap_hotkey_with_multiple_coldkeys_and_subnets() { &coldkey1, netuid1 ), - 0 + AlphaCurrency::ZERO ); assert_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( @@ -697,7 +698,7 @@ fn test_swap_hotkey_with_multiple_coldkeys_and_subnets() { &coldkey2, netuid2 ), - 0 + AlphaCurrency::ZERO ); // Check subnet membership transfer @@ -884,11 +885,15 @@ fn test_swap_stake_success() { let mut weight = Weight::zero(); // Initialize staking variables for old_hotkey - TotalHotkeyAlpha::::insert(old_hotkey, netuid, amount); - TotalHotkeyAlphaLastEpoch::::insert(old_hotkey, netuid, amount * 2); - TotalHotkeyShares::::insert(old_hotkey, netuid, U64F64::from_num(shares)); + TotalHotkeyAlpha::::insert(old_hotkey, netuid, AlphaCurrency::from(amount)); + TotalHotkeyAlphaLastEpoch::::insert( + old_hotkey, + netuid, + AlphaCurrency::from(amount * 2), + ); + TotalHotkeyShares::::insert(old_hotkey, netuid, shares); Alpha::::insert((old_hotkey, coldkey, netuid), U64F64::from_num(amount)); - AlphaDividendsPerSubnet::::insert(netuid, old_hotkey, amount); + AlphaDividendsPerSubnet::::insert(netuid, old_hotkey, AlphaCurrency::from(amount)); TaoDividendsPerSubnet::::insert(netuid, old_hotkey, amount); // Perform the swap @@ -900,15 +905,21 @@ fn test_swap_stake_success() { ); // Verify the swap - assert_eq!(TotalHotkeyAlpha::::get(old_hotkey, netuid), 0); - assert_eq!(TotalHotkeyAlpha::::get(new_hotkey, netuid), amount); + assert_eq!( + TotalHotkeyAlpha::::get(old_hotkey, netuid), + AlphaCurrency::ZERO + ); + assert_eq!( + TotalHotkeyAlpha::::get(new_hotkey, netuid), + amount.into() + ); assert_eq!( TotalHotkeyAlphaLastEpoch::::get(old_hotkey, netuid), - 0 + AlphaCurrency::ZERO ); assert_eq!( TotalHotkeyAlphaLastEpoch::::get(new_hotkey, netuid), - amount * 2 + AlphaCurrency::from(amount * 2) ); assert_eq!( TotalHotkeyShares::::get(old_hotkey, netuid), @@ -926,10 +937,13 @@ fn test_swap_stake_success() { Alpha::::get((new_hotkey, coldkey, netuid)), U64F64::from_num(amount) ); - assert_eq!(AlphaDividendsPerSubnet::::get(netuid, old_hotkey), 0); + assert_eq!( + AlphaDividendsPerSubnet::::get(netuid, old_hotkey), + AlphaCurrency::ZERO + ); assert_eq!( AlphaDividendsPerSubnet::::get(netuid, new_hotkey), - amount + amount.into() ); assert_eq!(TaoDividendsPerSubnet::::get(netuid, old_hotkey), 0); assert_eq!( diff --git a/pallets/subtensor/src/tests/swap_hotkey_with_subnet.rs b/pallets/subtensor/src/tests/swap_hotkey_with_subnet.rs index 5654498011..4a16de1e71 100644 --- a/pallets/subtensor/src/tests/swap_hotkey_with_subnet.rs +++ b/pallets/subtensor/src/tests/swap_hotkey_with_subnet.rs @@ -5,6 +5,7 @@ use codec::Encode; use frame_support::weights::Weight; use frame_support::{assert_err, assert_noop, assert_ok}; use frame_system::{Config, RawOrigin}; +use subtensor_runtime_common::{Alpha as AlphaCurrency, Currency}; use super::mock::*; use crate::*; @@ -672,8 +673,8 @@ fn test_swap_hotkey_with_multiple_coldkeys_and_subnets() { &coldkey2, netuid2, ); - assert!(ck1_stake > 0); - assert!(ck2_stake > 0); + assert!(!ck1_stake.is_zero()); + assert!(!ck2_stake.is_zero()); let total_hk_stake = SubtensorModule::get_total_stake_for_hotkey(&old_hotkey); assert!(total_hk_stake > 0); System::set_block_number(System::block_number() + HotkeySwapOnSubnetInterval::get()); @@ -728,7 +729,7 @@ fn test_swap_hotkey_with_multiple_coldkeys_and_subnets() { &coldkey1, netuid1 ), - 0 + AlphaCurrency::ZERO ); assert_eq!( SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet( @@ -736,7 +737,7 @@ fn test_swap_hotkey_with_multiple_coldkeys_and_subnets() { &coldkey2, netuid2 ), - 0 + AlphaCurrency::ZERO ); // Check subnet membership transfer @@ -937,11 +938,15 @@ fn test_swap_stake_success() { let shares = U64F64::from_num(123456); // Initialize staking variables for old_hotkey - TotalHotkeyAlpha::::insert(old_hotkey, netuid, amount); - TotalHotkeyAlphaLastEpoch::::insert(old_hotkey, netuid, amount * 2); + TotalHotkeyAlpha::::insert(old_hotkey, netuid, AlphaCurrency::from(amount)); + TotalHotkeyAlphaLastEpoch::::insert( + old_hotkey, + netuid, + AlphaCurrency::from(amount * 2), + ); TotalHotkeyShares::::insert(old_hotkey, netuid, U64F64::from_num(shares)); Alpha::::insert((old_hotkey, coldkey, netuid), U64F64::from_num(amount)); - AlphaDividendsPerSubnet::::insert(netuid, old_hotkey, amount); + AlphaDividendsPerSubnet::::insert(netuid, old_hotkey, AlphaCurrency::from(amount)); TaoDividendsPerSubnet::::insert(netuid, old_hotkey, amount); // Perform the swap @@ -954,15 +959,21 @@ fn test_swap_stake_success() { ),); // Verify the swap - assert_eq!(TotalHotkeyAlpha::::get(old_hotkey, netuid), 0); - assert_eq!(TotalHotkeyAlpha::::get(new_hotkey, netuid), amount); + assert_eq!( + TotalHotkeyAlpha::::get(old_hotkey, netuid), + AlphaCurrency::ZERO + ); + assert_eq!( + TotalHotkeyAlpha::::get(new_hotkey, netuid), + AlphaCurrency::from(amount) + ); assert_eq!( TotalHotkeyAlphaLastEpoch::::get(old_hotkey, netuid), - 0 + AlphaCurrency::ZERO ); assert_eq!( TotalHotkeyAlphaLastEpoch::::get(new_hotkey, netuid), - amount * 2 + AlphaCurrency::from(amount * 2) ); assert_eq!( TotalHotkeyShares::::get(old_hotkey, netuid), @@ -980,10 +991,13 @@ fn test_swap_stake_success() { Alpha::::get((new_hotkey, coldkey, netuid)), U64F64::from_num(amount) ); - assert_eq!(AlphaDividendsPerSubnet::::get(netuid, old_hotkey), 0); + assert_eq!( + AlphaDividendsPerSubnet::::get(netuid, old_hotkey), + AlphaCurrency::ZERO + ); assert_eq!( AlphaDividendsPerSubnet::::get(netuid, new_hotkey), - amount + AlphaCurrency::from(amount) ); assert_eq!(TaoDividendsPerSubnet::::get(netuid, old_hotkey), 0); assert_eq!( diff --git a/pallets/subtensor/src/tests/uids.rs b/pallets/subtensor/src/tests/uids.rs index 49233f105c..38e3e23478 100644 --- a/pallets/subtensor/src/tests/uids.rs +++ b/pallets/subtensor/src/tests/uids.rs @@ -5,6 +5,7 @@ use crate::*; use frame_support::{assert_err, assert_ok}; use frame_system::Config; use sp_core::U256; +use subtensor_runtime_common::Alpha as AlphaCurrency; /******************************************** tests for uids.rs file @@ -57,7 +58,7 @@ fn test_replace_neuron() { SubtensorModule::set_element_at(v, neuron_uid as usize, 5u16) }); Emission::::mutate(netuid, |v| { - SubtensorModule::set_element_at(v, neuron_uid as usize, 5u64) + SubtensorModule::set_element_at(v, neuron_uid as usize, 5.into()) }); Consensus::::mutate(netuid, |v| { SubtensorModule::set_element_at(v, neuron_uid as usize, 5u16) @@ -120,7 +121,10 @@ fn test_replace_neuron() { // Check trust, emission, consensus, incentive, dividends have been reset to 0. assert_eq!(SubtensorModule::get_trust_for_uid(netuid, neuron_uid), 0); - assert_eq!(SubtensorModule::get_emission_for_uid(netuid, neuron_uid), 0); + assert_eq!( + SubtensorModule::get_emission_for_uid(netuid, neuron_uid), + AlphaCurrency::ZERO + ); assert_eq!( SubtensorModule::get_consensus_for_uid(netuid, neuron_uid), 0 diff --git a/pallets/subtensor/src/tests/weights.rs b/pallets/subtensor/src/tests/weights.rs index 3e1c2f7557..35b7de12e9 100644 --- a/pallets/subtensor/src/tests/weights.rs +++ b/pallets/subtensor/src/tests/weights.rs @@ -232,7 +232,7 @@ fn test_commit_weights_validate() { let min_stake = 500_000_000_000; let reserve = min_stake * 1000; - mock::setup_reserves(netuid, reserve, reserve); + mock::setup_reserves(netuid, reserve, reserve.into()); // Stake some TAO and read what get_total_stake_for_hotkey it gets // It will be a different value due to the slippage @@ -355,7 +355,7 @@ fn test_set_weights_validate() { // Create netuid add_network(netuid, 1, 0); - mock::setup_reserves(netuid, 1_000_000_000_000, 1_000_000_000_000); + mock::setup_reserves(netuid, 1_000_000_000_000, 1_000_000_000_000.into()); // Register the hotkey SubtensorModule::append_neuron(netuid, &hotkey, 0); crate::Owner::::insert(hotkey, coldkey); @@ -764,7 +764,7 @@ fn test_weights_err_setting_weights_too_fast() { &hotkey_account_id, &(U256::from(66)), netuid, - 1, + 1.into(), ); SubtensorModule::set_weights_set_rate_limit(netuid, 10); assert_eq!(SubtensorModule::get_weights_set_rate_limit(netuid), 10); @@ -857,7 +857,7 @@ fn test_weights_err_has_duplicate_ids() { &hotkey_account_id, &(U256::from(77)), netuid, - 1, + 1.into(), ); // uid 1 @@ -1048,7 +1048,7 @@ fn test_set_weights_err_invalid_uid() { &hotkey_account_id, &(U256::from(66)), netuid, - 1, + 1.into(), ); let weight_keys: Vec = vec![9999]; // Does not exist let weight_values: Vec = vec![88]; // random value @@ -1085,7 +1085,7 @@ fn test_set_weight_not_enough_values() { &account_id, &(U256::from(2)), netuid, - 1, + 1.into(), ); register_ok_neuron(netuid, U256::from(3), U256::from(4), 300000); @@ -1196,7 +1196,7 @@ fn test_set_weights_sum_larger_than_u16_max() { &(U256::from(1)), &(U256::from(2)), netuid, - 1, + 1.into(), ); register_ok_neuron(1.into(), U256::from(3), U256::from(4), 300_000); @@ -1696,13 +1696,13 @@ fn test_commit_reveal_weights_ok() { &(U256::from(0)), &(U256::from(0)), netuid, - 1, + 1.into(), ); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &(U256::from(1)), &(U256::from(1)), netuid, - 1, + 1.into(), ); // Commit at block 0 @@ -1764,13 +1764,13 @@ fn test_commit_reveal_tempo_interval() { &(U256::from(0)), &(U256::from(0)), netuid, - 1, + 1.into(), ); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &(U256::from(1)), &(U256::from(1)), netuid, - 1, + 1.into(), ); // Commit at block 0 @@ -1899,13 +1899,13 @@ fn test_commit_reveal_hash() { &(U256::from(0)), &(U256::from(0)), netuid, - 1, + 1.into(), ); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &(U256::from(1)), &(U256::from(1)), netuid, - 1, + 1.into(), ); SubtensorModule::set_commit_reveal_weights_enabled(netuid, true); @@ -1999,13 +1999,13 @@ fn test_commit_reveal_disabled_or_enabled() { &(U256::from(0)), &(U256::from(0)), netuid, - 1, + 1.into(), ); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &(U256::from(1)), &(U256::from(1)), netuid, - 1, + 1.into(), ); // Disable commit/reveal @@ -2076,13 +2076,13 @@ fn test_toggle_commit_reveal_weights_and_set_weights() { &(U256::from(0)), &(U256::from(0)), netuid, - 1, + 1.into(), ); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &(U256::from(1)), &(U256::from(1)), netuid, - 1, + 1.into(), ); // Enable commit/reveal @@ -2162,13 +2162,13 @@ fn test_tempo_change_during_commit_reveal_process() { &(U256::from(0)), &(U256::from(0)), netuid, - 1, + 1.into(), ); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &(U256::from(1)), &(U256::from(1)), netuid, - 1, + 1.into(), ); assert_ok!(SubtensorModule::commit_weights( @@ -2311,13 +2311,13 @@ fn test_commit_reveal_multiple_commits() { &(U256::from(0)), &(U256::from(0)), netuid, - 1, + 1.into(), ); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &(U256::from(1)), &(U256::from(1)), netuid, - 1, + 1.into(), ); // 1. Commit 10 times successfully @@ -2714,13 +2714,13 @@ fn test_expired_commits_handling_in_commit_and_reveal() { &(U256::from(0)), &(U256::from(0)), netuid, - 1, + 1.into(), ); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &(U256::from(1)), &(U256::from(1)), netuid, - 1, + 1.into(), ); // 1. Commit 5 times in epoch 0 @@ -2912,13 +2912,13 @@ fn test_reveal_at_exact_epoch() { &(U256::from(0)), &(U256::from(0)), netuid, - 1, + 1.into(), ); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &(U256::from(1)), &(U256::from(1)), netuid, - 1, + 1.into(), ); let reveal_periods: Vec = vec![0, 1, 2, 7, 40, 86, 100]; @@ -3076,13 +3076,13 @@ fn test_tempo_and_reveal_period_change_during_commit_reveal_process() { &(U256::from(0)), &(U256::from(0)), netuid, - 1, + 1.into(), ); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &(U256::from(1)), &(U256::from(1)), netuid, - 1, + 1.into(), ); // Step 1: Commit weights @@ -3266,13 +3266,13 @@ fn test_commit_reveal_order_enforcement() { &(U256::from(0)), &(U256::from(0)), netuid, - 1, + 1.into(), ); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &(U256::from(1)), &(U256::from(1)), netuid, - 1, + 1.into(), ); // Commit three times: A, B, C @@ -3538,13 +3538,13 @@ fn test_successful_batch_reveal() { &(U256::from(0)), &(U256::from(0)), netuid, - 1, + 1.into(), ); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &(U256::from(1)), &(U256::from(1)), netuid, - 1, + 1.into(), ); // 1. Commit multiple times @@ -3616,13 +3616,13 @@ fn test_batch_reveal_with_expired_commits() { &(U256::from(0)), &(U256::from(0)), netuid, - 1, + 1.into(), ); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &(U256::from(1)), &(U256::from(1)), netuid, - 1, + 1.into(), ); let mut commit_info = Vec::new(); @@ -4033,13 +4033,13 @@ fn test_batch_reveal_with_out_of_order_commits() { &(U256::from(0)), &(U256::from(0)), netuid, - 1, + 1.into(), ); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &(U256::from(1)), &(U256::from(1)), netuid, - 1, + 1.into(), ); // 1. Commit multiple times (A, B, C) @@ -4438,13 +4438,13 @@ fn test_get_reveal_blocks() { &(U256::from(0)), &(U256::from(0)), netuid, - 1, + 1.into(), ); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &(U256::from(1)), &(U256::from(1)), netuid, - 1, + 1.into(), ); // **6. Commit Weights at Block 0** @@ -4572,13 +4572,13 @@ fn test_commit_weights_rate_limit() { &(U256::from(0)), &(U256::from(0)), netuid, - 1, + 1.into(), ); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &(U256::from(1)), &(U256::from(1)), netuid, - 1, + 1.into(), ); let neuron_uid = @@ -4762,13 +4762,13 @@ fn test_reveal_crv3_commits_success() { &hotkey1, &(U256::from(3)), netuid, - 1, + 1.into(), ); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( &hotkey2, &(U256::from(4)), netuid, - 1, + 1.into(), ); let version_key = SubtensorModule::get_weights_version_key(netuid); diff --git a/pallets/subtensor/src/utils/misc.rs b/pallets/subtensor/src/utils/misc.rs index 9641cfb0ee..8a680d94ed 100644 --- a/pallets/subtensor/src/utils/misc.rs +++ b/pallets/subtensor/src/utils/misc.rs @@ -8,7 +8,7 @@ use sp_core::Get; use sp_core::U256; use sp_runtime::Saturating; use substrate_fixed::types::{I32F32, U96F32}; -use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::{Alpha as AlphaCurrency, NetUid}; impl Pallet { pub fn ensure_subnet_owner_or_root( @@ -92,7 +92,7 @@ impl Pallet { pub fn get_active(netuid: NetUid) -> Vec { Active::::get(netuid) } - pub fn get_emission(netuid: NetUid) -> Vec { + pub fn get_emission(netuid: NetUid) -> Vec { Emission::::get(netuid) } pub fn get_consensus(netuid: NetUid) -> Vec { @@ -171,9 +171,9 @@ impl Pallet { let vec = Trust::::get(netuid); vec.get(uid as usize).copied().unwrap_or(0) } - pub fn get_emission_for_uid(netuid: NetUid, uid: u16) -> u64 { + pub fn get_emission_for_uid(netuid: NetUid, uid: u16) -> AlphaCurrency { let vec = Emission::::get(netuid); - vec.get(uid as usize).copied().unwrap_or(0) + vec.get(uid as usize).copied().unwrap_or_default() } pub fn get_active_for_uid(netuid: NetUid, uid: u16) -> bool { let vec = Active::::get(netuid); @@ -217,7 +217,7 @@ impl Pallet { pub fn get_tempo(netuid: NetUid) -> u16 { Tempo::::get(netuid) } - pub fn get_pending_emission(netuid: NetUid) -> u64 { + pub fn get_pending_emission(netuid: NetUid) -> AlphaCurrency { PendingEmission::::get(netuid) } pub fn get_last_adjustment_block(netuid: NetUid) -> u64 { @@ -667,11 +667,11 @@ impl Pallet { SubnetOwner::::iter_values().any(|owner| *address == owner) } - pub fn get_nominator_min_required_stake() -> u64 { + pub fn get_nominator_min_required_stake() -> AlphaCurrency { NominatorMinRequiredStake::::get() } - pub fn set_nominator_min_required_stake(min_stake: u64) { + pub fn set_nominator_min_required_stake(min_stake: AlphaCurrency) { NominatorMinRequiredStake::::put(min_stake); } diff --git a/pallets/swap-interface/src/lib.rs b/pallets/swap-interface/src/lib.rs index f09928a2b2..7d164b37fa 100644 --- a/pallets/swap-interface/src/lib.rs +++ b/pallets/swap-interface/src/lib.rs @@ -2,7 +2,7 @@ use frame_support::pallet_prelude::*; use substrate_fixed::types::U96F32; -use subtensor_runtime_common::NetUid; +use subtensor_runtime_common::{Alpha, NetUid}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum OrderType { @@ -44,7 +44,7 @@ pub struct SwapResult { #[derive(Debug, PartialEq)] pub struct UpdateLiquidityResult { pub tao: u64, - pub alpha: u64, + pub alpha: Alpha, pub fee_tao: u64, - pub fee_alpha: u64, + pub fee_alpha: Alpha, } diff --git a/pallets/swap/src/mock.rs b/pallets/swap/src/mock.rs index 36e8797031..57fb79d121 100644 --- a/pallets/swap/src/mock.rs +++ b/pallets/swap/src/mock.rs @@ -14,7 +14,7 @@ use sp_runtime::{ BuildStorage, traits::{BlakeTwo256, IdentityLookup}, }; -use subtensor_runtime_common::{BalanceOps, NetUid, SubnetInfo}; +use subtensor_runtime_common::{Alpha, BalanceOps, NetUid, SubnetInfo}; use crate::pallet::EnabledUserLiquidity; @@ -95,11 +95,11 @@ impl SubnetInfo for MockLiquidityProvider { } } - fn alpha_reserve(netuid: NetUid) -> u64 { + fn alpha_reserve(netuid: NetUid) -> Alpha { match netuid.into() { - 123u16 => 10_000, - WRAPPING_FEES_NETUID => 400_000_000_000, - _ => 4_000_000_000_000, + 123u16 => 10_000.into(), + WRAPPING_FEES_NETUID => 400_000_000_000.into(), + _ => 4_000_000_000_000.into(), } } @@ -132,7 +132,7 @@ impl BalanceOps for MockBalanceOps { _: NetUid, coldkey_account_id: &AccountId, hotkey_account_id: &AccountId, - ) -> u64 { + ) -> Alpha { match (coldkey_account_id, hotkey_account_id) { (&OK_COLDKEY_ACCOUNT_ID, &OK_HOTKEY_ACCOUNT_ID) => 100_000_000_000_000, (&OK_COLDKEY_ACCOUNT_ID_2, &OK_HOTKEY_ACCOUNT_ID_2) => 100_000_000_000_000, @@ -141,6 +141,7 @@ impl BalanceOps for MockBalanceOps { } _ => 1_000_000_000, } + .into() } fn increase_balance(_coldkey: &AccountId, _tao: u64) {} @@ -153,7 +154,7 @@ impl BalanceOps for MockBalanceOps { _coldkey: &AccountId, _hotkey: &AccountId, _netuid: NetUid, - _alpha: u64, + _alpha: Alpha, ) -> Result<(), DispatchError> { Ok(()) } @@ -162,15 +163,15 @@ impl BalanceOps for MockBalanceOps { _coldkey: &AccountId, _hotkey: &AccountId, _netuid: NetUid, - alpha: u64, - ) -> Result { + alpha: Alpha, + ) -> Result { Ok(alpha) } fn increase_provided_tao_reserve(_netuid: NetUid, _tao: u64) {} fn decrease_provided_tao_reserve(_netuid: NetUid, _tao: u64) {} - fn increase_provided_alpha_reserve(_netuid: NetUid, _alpha: u64) {} - fn decrease_provided_alpha_reserve(_netuid: NetUid, _alpha: u64) {} + fn increase_provided_alpha_reserve(_netuid: NetUid, _alpha: Alpha) {} + fn decrease_provided_alpha_reserve(_netuid: NetUid, _alpha: Alpha) {} } impl crate::pallet::Config for Test { diff --git a/pallets/swap/src/pallet/impls.rs b/pallets/swap/src/pallet/impls.rs index 3f54dbfd74..545e61de56 100644 --- a/pallets/swap/src/pallet/impls.rs +++ b/pallets/swap/src/pallet/impls.rs @@ -7,7 +7,7 @@ use safe_math::*; use sp_arithmetic::helpers_128bit; use sp_runtime::traits::AccountIdConversion; use substrate_fixed::types::{I64F64, U64F64, U96F32}; -use subtensor_runtime_common::{BalanceOps, NetUid, SubnetInfo}; +use subtensor_runtime_common::{Alpha, BalanceOps, Currency, NetUid, SubnetInfo}; use subtensor_swap_interface::{SwapHandler, SwapResult, UpdateLiquidityResult}; use super::pallet::*; @@ -264,7 +264,7 @@ impl Pallet { } else { let tao_reserve = T::SubnetInfo::tao_reserve(netuid.into()); let alpha_reserve = T::SubnetInfo::alpha_reserve(netuid.into()); - if alpha_reserve > 0 { + if !alpha_reserve.is_zero() { U96F32::saturating_from_num(tao_reserve) .saturating_div(U96F32::saturating_from_num(alpha_reserve)) } else { @@ -307,9 +307,9 @@ impl Pallet { // Set initial (protocol owned) liquidity and positions // Protocol liquidity makes one position from TickIndex::MIN to TickIndex::MAX // We are using the sp_arithmetic sqrt here, which works for u128 - let liquidity = - helpers_128bit::sqrt((tao_reserve as u128).saturating_mul(alpha_reserve as u128)) - as u64; + let liquidity = helpers_128bit::sqrt( + (tao_reserve as u128).saturating_mul(u64::from(alpha_reserve) as u128), + ) as u64; let protocol_account_id = Self::protocol_account_id(); let (position, _, _) = Self::add_liquidity_not_insert( @@ -330,9 +330,9 @@ impl Pallet { // Get updated reserves, calculate liquidity let tao_reserve = ::SubnetInfo::tao_reserve(netuid.into()); let alpha_reserve = ::SubnetInfo::alpha_reserve(netuid.into()); - let liquidity = - helpers_128bit::sqrt((tao_reserve as u128).saturating_mul(alpha_reserve as u128)) - as u64; + let liquidity = helpers_128bit::sqrt( + (tao_reserve as u128).saturating_mul(u64::from(alpha_reserve) as u128), + ) as u64; // Update protocol position with new liquidity let protocol_account_id = Self::protocol_account_id(); @@ -392,7 +392,7 @@ impl Pallet { // Check if reserves are overused if let Ok(ref swap_result) = result { let checked_reserve = match order_type { - OrderType::Buy => alpha_reserve, + OrderType::Buy => u64::from(alpha_reserve), OrderType::Sell => tao_reserve, }; @@ -414,7 +414,8 @@ impl Pallet { ) -> Result> { ensure!( T::SubnetInfo::tao_reserve(netuid.into()) >= T::MinimumReserve::get().get() - && T::SubnetInfo::alpha_reserve(netuid.into()) >= T::MinimumReserve::get().get(), + && u64::from(T::SubnetInfo::alpha_reserve(netuid.into())) + >= T::MinimumReserve::get().get(), Error::::ReservesTooLow ); @@ -763,7 +764,7 @@ impl Pallet { netuid.into(), coldkey_account_id, hotkey_account_id - ) >= alpha, + ) >= Alpha::from(alpha), Error::::InsufficientBalance ); @@ -852,9 +853,9 @@ impl Pallet { Ok(UpdateLiquidityResult { tao, - alpha, + alpha: alpha.into(), fee_tao, - fee_alpha, + fee_alpha: fee_alpha.into(), }) } @@ -922,7 +923,7 @@ impl Pallet { ensure!( T::BalanceOps::tao_balance(coldkey_account_id) >= tao && T::BalanceOps::alpha_balance(netuid, coldkey_account_id, hotkey_account_id) - >= alpha, + >= Alpha::from(alpha.saturating_to_num::()), Error::::InsufficientBalance ); } else { @@ -966,9 +967,9 @@ impl Pallet { Ok(UpdateLiquidityResult { tao: tao.saturating_to_num::(), - alpha: alpha.saturating_to_num::(), + alpha: alpha.saturating_to_num::().into(), fee_tao, - fee_alpha, + fee_alpha: fee_alpha.into(), }) } diff --git a/pallets/swap/src/pallet/mod.rs b/pallets/swap/src/pallet/mod.rs index 3a0e00bc8d..ca0a8cadb7 100644 --- a/pallets/swap/src/pallet/mod.rs +++ b/pallets/swap/src/pallet/mod.rs @@ -3,7 +3,7 @@ use core::num::NonZeroU64; use frame_support::{PalletId, pallet_prelude::*, traits::Get}; use frame_system::pallet_prelude::*; use substrate_fixed::types::U64F64; -use subtensor_runtime_common::{BalanceOps, NetUid, SubnetInfo}; +use subtensor_runtime_common::{Alpha, BalanceOps, Currency, NetUid, SubnetInfo}; use crate::{ position::{Position, PositionId}, @@ -164,7 +164,7 @@ mod pallet { /// The amount of TAO tokens committed to the position tao: u64, /// The amount of Alpha tokens committed to the position - alpha: u64, + alpha: Alpha, }, /// Event emitted when liquidity is removed from a subnet's liquidity pool. @@ -178,11 +178,11 @@ mod pallet { /// The amount of TAO tokens returned to the user tao: u64, /// The amount of Alpha tokens returned to the user - alpha: u64, + alpha: Alpha, /// The amount of TAO fees earned from the position fee_tao: u64, /// The amount of Alpha fees earned from the position - fee_alpha: u64, + fee_alpha: Alpha, }, } @@ -332,6 +332,7 @@ mod pallet { tick_high, liquidity, )?; + let alpha = Alpha::from(alpha); // Remove TAO and Alpha balances or fail transaction if they can't be removed exactly let tao_provided = T::BalanceOps::decrease_balance(&coldkey, tao)?; @@ -486,7 +487,7 @@ mod pallet { if result.fee_tao > 0 { T::BalanceOps::increase_balance(&coldkey, result.fee_tao); } - if result.fee_alpha > 0 { + if !result.fee_alpha.is_zero() { T::BalanceOps::increase_stake( &coldkey, &hotkey.clone(), diff --git a/pallets/swap/src/pallet/tests.rs b/pallets/swap/src/pallet/tests.rs index 07d1c63b89..0d35a96a53 100644 --- a/pallets/swap/src/pallet/tests.rs +++ b/pallets/swap/src/pallet/tests.rs @@ -176,7 +176,7 @@ fn test_swap_initialization() { // Calculate expected liquidity let expected_liquidity = - helpers_128bit::sqrt((tao as u128).saturating_mul(alpha as u128)) as u64; + helpers_128bit::sqrt((tao as u128).saturating_mul(u64::from(alpha) as u128)) as u64; // Get the protocol account let protocol_account_id = Pallet::::protocol_account_id(); @@ -504,9 +504,13 @@ fn test_remove_liquidity_basic() { Pallet::::do_remove_liquidity(netuid, &OK_COLDKEY_ACCOUNT_ID, position_id) .unwrap(); assert_abs_diff_eq!(remove_result.tao, tao, epsilon = tao / 1000); - assert_abs_diff_eq!(remove_result.alpha, alpha, epsilon = alpha / 1000); + assert_abs_diff_eq!( + u64::from(remove_result.alpha), + alpha, + epsilon = alpha / 1000 + ); assert_eq!(remove_result.fee_tao, 0); - assert_eq!(remove_result.fee_alpha, 0); + assert_eq!(remove_result.fee_alpha, 0.into()); // Liquidity position is removed assert_eq!( @@ -628,9 +632,13 @@ fn test_modify_position_basic() { -((liquidity / 10) as i64), ) .unwrap(); - assert_abs_diff_eq!(modify_result.alpha, alpha / 10, epsilon = alpha / 1000); + assert_abs_diff_eq!( + u64::from(modify_result.alpha), + alpha / 10, + epsilon = alpha / 1000 + ); assert!(modify_result.fee_tao > 0); - assert_eq!(modify_result.fee_alpha, 0); + assert_eq!(modify_result.fee_alpha, 0.into()); // Liquidity position is reduced assert_eq!( @@ -658,9 +666,13 @@ fn test_modify_position_basic() { ) .unwrap(); - assert_abs_diff_eq!(modify_result.alpha, alpha / 100, epsilon = alpha / 1000); + assert_abs_diff_eq!( + u64::from(modify_result.alpha), + alpha / 100, + epsilon = alpha / 1000 + ); assert_eq!(modify_result.fee_tao, 0); - assert_eq!(modify_result.fee_alpha, 0); + assert_eq!(modify_result.fee_alpha, 0.into()); }); }); } @@ -766,7 +778,8 @@ fn test_swap_basic() { position.liquidity, helpers_128bit::sqrt( MockLiquidityProvider::tao_reserve(netuid.into()) as u128 - * MockLiquidityProvider::alpha_reserve(netuid.into()) as u128 + * u64::from(MockLiquidityProvider::alpha_reserve(netuid.into())) + as u128 ) as u64 ); assert_eq!(position.tick_low, tick_low); @@ -875,7 +888,8 @@ fn test_swap_single_position() { // Initialize pool and add the user position assert_ok!(Pallet::::maybe_initialize_v3(netuid)); let tao_reserve = MockLiquidityProvider::tao_reserve(netuid.into()); - let alpha_reserve = MockLiquidityProvider::alpha_reserve(netuid.into()); + let alpha_reserve = + u64::from(MockLiquidityProvider::alpha_reserve(netuid.into())); let protocol_liquidity = (tao_reserve as f64 * alpha_reserve as f64).sqrt(); // Add liquidity @@ -1177,7 +1191,7 @@ fn test_swap_multiple_positions() { ); let tao_reserve = MockLiquidityProvider::tao_reserve(netuid.into()); - let alpha_reserve = MockLiquidityProvider::alpha_reserve(netuid.into()); + let alpha_reserve = u64::from(MockLiquidityProvider::alpha_reserve(netuid.into())); let output_amount = output_amount as u64; assert!(output_amount > 0); diff --git a/precompiles/src/alpha.rs b/precompiles/src/alpha.rs index 3a4a36fb79..6621854d33 100644 --- a/precompiles/src/alpha.rs +++ b/precompiles/src/alpha.rs @@ -51,25 +51,19 @@ where #[precompile::public("getAlphaInPool(uint16)")] #[precompile::view] fn get_alpha_in_pool(_handle: &mut impl PrecompileHandle, netuid: u16) -> EvmResult { - Ok(pallet_subtensor::SubnetAlphaIn::::get(NetUid::from( - netuid, - ))) + Ok(pallet_subtensor::SubnetAlphaIn::::get(NetUid::from(netuid)).into()) } #[precompile::public("getAlphaOutPool(uint16)")] #[precompile::view] fn get_alpha_out_pool(_handle: &mut impl PrecompileHandle, netuid: u16) -> EvmResult { - Ok(pallet_subtensor::SubnetAlphaOut::::get(NetUid::from( - netuid, - ))) + Ok(pallet_subtensor::SubnetAlphaOut::::get(NetUid::from(netuid)).into()) } #[precompile::public("getAlphaIssuance(uint16)")] #[precompile::view] fn get_alpha_issuance(_handle: &mut impl PrecompileHandle, netuid: u16) -> EvmResult { - Ok(pallet_subtensor::Pallet::::get_alpha_issuance( - netuid.into(), - )) + Ok(pallet_subtensor::Pallet::::get_alpha_issuance(netuid.into()).into()) } #[precompile::public("getTaoWeight()")] diff --git a/precompiles/src/metagraph.rs b/precompiles/src/metagraph.rs index 05f7a5bf79..a508dd7c02 100644 --- a/precompiles/src/metagraph.rs +++ b/precompiles/src/metagraph.rs @@ -94,10 +94,7 @@ where #[precompile::public("getEmission(uint16,uint16)")] #[precompile::view] fn get_emission(_: &mut impl PrecompileHandle, netuid: u16, uid: u16) -> EvmResult { - Ok(pallet_subtensor::Pallet::::get_emission_for_uid( - netuid.into(), - uid, - )) + Ok(pallet_subtensor::Pallet::::get_emission_for_uid(netuid.into(), uid).into()) } #[precompile::public("getVtrust(uint16,uint16)")] diff --git a/precompiles/src/staking.rs b/precompiles/src/staking.rs index f26506b14c..df71e362d3 100644 --- a/precompiles/src/staking.rs +++ b/precompiles/src/staking.rs @@ -111,11 +111,11 @@ where let account_id = handle.caller_account_id::(); let hotkey = R::AccountId::from(address.0); let netuid = try_u16_from_u256(netuid)?; - let amount_unstaked = amount_alpha.unique_saturated_into(); + let amount_unstaked: u64 = amount_alpha.unique_saturated_into(); let call = pallet_subtensor::Call::::remove_stake { hotkey, netuid: netuid.into(), - amount_unstaked, + amount_unstaked: amount_unstaked.into(), }; handle.try_dispatch_runtime_call::(call, RawOrigin::Signed(account_id)) @@ -135,13 +135,13 @@ where let destination_hotkey = R::AccountId::from(destination_hotkey.0); let origin_netuid = try_u16_from_u256(origin_netuid)?; let destination_netuid = try_u16_from_u256(destination_netuid)?; - let alpha_amount = amount_alpha.unique_saturated_into(); + let alpha_amount: u64 = amount_alpha.unique_saturated_into(); let call = pallet_subtensor::Call::::move_stake { origin_hotkey, destination_hotkey, origin_netuid: origin_netuid.into(), destination_netuid: destination_netuid.into(), - alpha_amount, + alpha_amount: alpha_amount.into(), }; handle.try_dispatch_runtime_call::(call, RawOrigin::Signed(account_id)) @@ -161,13 +161,13 @@ where let hotkey = R::AccountId::from(hotkey.0); let origin_netuid = try_u16_from_u256(origin_netuid)?; let destination_netuid = try_u16_from_u256(destination_netuid)?; - let alpha_amount = amount_alpha.unique_saturated_into(); + let alpha_amount: u64 = amount_alpha.unique_saturated_into(); let call = pallet_subtensor::Call::::transfer_stake { destination_coldkey, hotkey, origin_netuid: origin_netuid.into(), destination_netuid: destination_netuid.into(), - alpha_amount, + alpha_amount: alpha_amount.into(), }; handle.try_dispatch_runtime_call::(call, RawOrigin::Signed(account_id)) @@ -214,7 +214,7 @@ where netuid.into(), ); - Ok(stake.into()) + Ok(u64::from(stake).into()) } #[precompile::public("getAlphaStakedValidators(bytes32,uint256)")] @@ -250,7 +250,7 @@ where let stake = pallet_subtensor::Pallet::::get_stake_for_hotkey_on_subnet(&hotkey, netuid.into()); - Ok(stake.into()) + Ok(u64::from(stake).into()) } #[precompile::public("addProxy(bytes32)")] @@ -318,12 +318,12 @@ where let account_id = handle.caller_account_id::(); let hotkey = R::AccountId::from(address.0); let netuid = try_u16_from_u256(netuid)?; - let amount_unstaked = amount_alpha.unique_saturated_into(); + let amount_unstaked: u64 = amount_alpha.unique_saturated_into(); let limit_price = limit_price_rao.unique_saturated_into(); let call = pallet_subtensor::Call::::remove_stake_limit { hotkey, netuid: netuid.into(), - amount_unstaked, + amount_unstaked: amount_unstaked.into(), limit_price, allow_partial, }; @@ -413,7 +413,7 @@ where let call = pallet_subtensor::Call::::remove_stake { hotkey, netuid: netuid.into(), - amount_unstaked, + amount_unstaked: amount_unstaked.into(), }; handle.try_dispatch_runtime_call::(call, RawOrigin::Signed(account_id)) @@ -473,7 +473,7 @@ where &coldkey, netuid.into(), ); - let stake: SubstrateBalance = stake.into(); + let stake: SubstrateBalance = u64::from(stake).into(); let stake = ::BalanceConverter::into_evm_balance(stake) .map(|amount| amount.into_u256()) .ok_or(ExitError::InvalidRange)?; diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index 8adf4b6c55..a9cb997deb 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -67,7 +67,7 @@ use sp_std::prelude::*; use sp_version::NativeVersion; use sp_version::RuntimeVersion; use subtensor_precompiles::Precompiles; -use subtensor_runtime_common::{time::*, *}; +use subtensor_runtime_common::{Alpha as AlphaCurrency, time::*, *}; // A few exports that help ease life for downstream crates. pub use frame_support::{ @@ -754,7 +754,7 @@ impl InstanceFilter for ProxyType { RuntimeCall::SubtensorModule(pallet_subtensor::Call::transfer_stake { alpha_amount, .. - }) => *alpha_amount < SMALL_TRANSFER_LIMIT, + }) => *alpha_amount < SMALL_TRANSFER_LIMIT.into(), _ => false, }, ProxyType::Owner => { @@ -2233,7 +2233,7 @@ impl_runtime_apis! { SubtensorModule::get_delegate(delegate_account) } - fn get_delegated(delegatee_account: AccountId32) -> Vec<(DelegateInfo, (Compact, Compact))> { + fn get_delegated(delegatee_account: AccountId32) -> Vec<(DelegateInfo, (Compact, Compact))> { SubtensorModule::get_delegated(delegatee_account) } } From 34ac22e989bbf87360ae0f93303f50072fc195c2 Mon Sep 17 00:00:00 2001 From: Aliaksandr Tsurko Date: Wed, 16 Jul 2025 12:56:29 +0300 Subject: [PATCH 4/7] Fix linter --- common/src/currency.rs | 10 ++++++++++ pallets/subtensor/src/staking/stake_utils.rs | 3 ++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/common/src/currency.rs b/common/src/currency.rs index 9f7f1e5be6..f1b5ef9a31 100644 --- a/common/src/currency.rs +++ b/common/src/currency.rs @@ -115,6 +115,7 @@ pub trait Currency: ToFixed + Into + From + Clone + Copy { Into::::into(*self).saturating_add(rhv.into()).into() } + #[allow(clippy::arithmetic_side_effects)] fn saturating_div(&self, rhv: Self) -> Self { Into::::into(*self).saturating_div(rhv.into()).into() } @@ -133,6 +134,7 @@ macro_rules! impl_arithmetic_operators { impl Add for $currency_type { type Output = Self; + #[allow(clippy::arithmetic_side_effects)] fn add(self, rhs: Self) -> Self::Output { let lhs_u64: u64 = self.into(); let rhs_u64: u64 = rhs.into(); @@ -143,6 +145,7 @@ macro_rules! impl_arithmetic_operators { impl Sub for $currency_type { type Output = Self; + #[allow(clippy::arithmetic_side_effects)] fn sub(self, rhs: Self) -> Self::Output { let lhs_u64: u64 = self.into(); let rhs_u64: u64 = rhs.into(); @@ -153,6 +156,7 @@ macro_rules! impl_arithmetic_operators { impl Mul for $currency_type { type Output = Self; + #[allow(clippy::arithmetic_side_effects)] fn mul(self, rhs: Self) -> Self::Output { let lhs_u64: u64 = self.into(); let rhs_u64: u64 = rhs.into(); @@ -163,6 +167,7 @@ macro_rules! impl_arithmetic_operators { impl Div for $currency_type { type Output = Self; + #[allow(clippy::arithmetic_side_effects)] fn div(self, rhs: Self) -> Self::Output { let lhs_u64: u64 = self.into(); let rhs_u64: u64 = rhs.into(); @@ -171,24 +176,28 @@ macro_rules! impl_arithmetic_operators { } impl AddAssign for $currency_type { + #[allow(clippy::arithmetic_side_effects)] fn add_assign(&mut self, rhs: Self) { *self = *self + rhs; } } impl SubAssign for $currency_type { + #[allow(clippy::arithmetic_side_effects)] fn sub_assign(&mut self, rhs: Self) { *self = *self - rhs; } } impl MulAssign for $currency_type { + #[allow(clippy::arithmetic_side_effects)] fn mul_assign(&mut self, rhs: Self) { *self = *self * rhs; } } impl DivAssign for $currency_type { + #[allow(clippy::arithmetic_side_effects)] fn div_assign(&mut self, rhs: Self) { *self = *self / rhs; } @@ -207,6 +216,7 @@ macro_rules! impl_approx { fn default_epsilon() -> Self::Epsilon { u64::default_epsilon().into() } + fn abs_diff_eq(&self, other: &Self, epsilon: Self::Epsilon) -> bool { u64::abs_diff_eq(&u64::from(*self), &u64::from(*other), epsilon.into()) } diff --git a/pallets/subtensor/src/staking/stake_utils.rs b/pallets/subtensor/src/staking/stake_utils.rs index 70d80f288a..ad0d773101 100644 --- a/pallets/subtensor/src/staking/stake_utils.rs +++ b/pallets/subtensor/src/staking/stake_utils.rs @@ -641,7 +641,8 @@ impl Pallet { false, false, )?; - let alpha_decrease = AlphaCurrency::from(swap_result.alpha_reserve_delta.abs() as u64); + let alpha_decrease = + AlphaCurrency::from(swap_result.alpha_reserve_delta.unsigned_abs()); // Decrease Alpha reserves. Self::decrease_provided_alpha_reserve(netuid.into(), alpha_decrease); From a9d0b7914b6d7bd7c369aaee466a4a5bd9701d3e Mon Sep 17 00:00:00 2001 From: Aliaksandr Tsurko Date: Wed, 16 Jul 2025 13:32:34 +0300 Subject: [PATCH 5/7] Clean up --- pallets/subtensor/src/coinbase/run_coinbase.rs | 6 +++--- pallets/subtensor/src/staking/stake_utils.rs | 2 +- pallets/subtensor/src/subnets/uids.rs | 2 +- pallets/subtensor/src/tests/children.rs | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/pallets/subtensor/src/coinbase/run_coinbase.rs b/pallets/subtensor/src/coinbase/run_coinbase.rs index 9ebeac07b0..8f2384e6d7 100644 --- a/pallets/subtensor/src/coinbase/run_coinbase.rs +++ b/pallets/subtensor/src/coinbase/run_coinbase.rs @@ -233,7 +233,7 @@ impl Pallet { // Get and drain the subnet pending emission. let pending_alpha = PendingEmission::::get(netuid); - PendingEmission::::insert(netuid, AlphaCurrency::from(0)); + PendingEmission::::insert(netuid, AlphaCurrency::ZERO); // Get and drain the subnet pending root divs. let pending_tao: u64 = PendingRootDivs::::get(netuid); @@ -241,11 +241,11 @@ impl Pallet { // Get this amount as alpha that was swapped for pending root divs. let pending_swapped = PendingAlphaSwapped::::get(netuid); - PendingAlphaSwapped::::insert(netuid, AlphaCurrency::from(0)); + PendingAlphaSwapped::::insert(netuid, AlphaCurrency::ZERO); // Get owner cut and drain. let owner_cut = PendingOwnerCut::::get(netuid); - PendingOwnerCut::::insert(netuid, AlphaCurrency::from(0)); + PendingOwnerCut::::insert(netuid, AlphaCurrency::ZERO); // Drain pending root divs, alpha emission, and owner cut. Self::drain_pending_emission( diff --git a/pallets/subtensor/src/staking/stake_utils.rs b/pallets/subtensor/src/staking/stake_utils.rs index ad0d773101..6a28b846ed 100644 --- a/pallets/subtensor/src/staking/stake_utils.rs +++ b/pallets/subtensor/src/staking/stake_utils.rs @@ -1194,7 +1194,7 @@ impl Pallet { if carry_over.is_zero() { SubnetAlphaInProvided::::set(netuid, remainder); } else { - SubnetAlphaInProvided::::set(netuid, AlphaCurrency::from(0)); + SubnetAlphaInProvided::::set(netuid, AlphaCurrency::ZERO); SubnetAlphaIn::::set(netuid, subnet_alpha.saturating_sub(carry_over)); } } diff --git a/pallets/subtensor/src/subnets/uids.rs b/pallets/subtensor/src/subnets/uids.rs index fa22fddf4f..67c0a24c29 100644 --- a/pallets/subtensor/src/subnets/uids.rs +++ b/pallets/subtensor/src/subnets/uids.rs @@ -155,7 +155,7 @@ impl Pallet { if let Ok(hotkey) = Self::get_hotkey_for_net_and_uid(netuid, neuron_uid) { Self::get_stake_for_hotkey_on_subnet(&hotkey, netuid) } else { - 0.into() + AlphaCurrency::ZERO } } diff --git a/pallets/subtensor/src/tests/children.rs b/pallets/subtensor/src/tests/children.rs index ea7325ad30..f873b98a9b 100644 --- a/pallets/subtensor/src/tests/children.rs +++ b/pallets/subtensor/src/tests/children.rs @@ -3112,7 +3112,7 @@ fn test_parent_child_chain_emission() { let emission: U96F32 = U96F32::from_num(SubtensorModule::get_block_emission().unwrap_or(0)); // Set pending emission to 0 - PendingEmission::::insert(netuid, AlphaCurrency::from(0)); + PendingEmission::::insert(netuid, AlphaCurrency::ZERO); // Run epoch with emission value SubtensorModule::run_coinbase(emission); @@ -3175,7 +3175,7 @@ fn test_parent_child_chain_emission() { ); let hotkeys = [hotkey_a, hotkey_b, hotkey_c]; - let mut total_stake_now = AlphaCurrency::from(0); + let mut total_stake_now = AlphaCurrency::ZERO; for (hotkey, netuid, stake) in TotalHotkeyAlpha::::iter() { if hotkeys.contains(&hotkey) { total_stake_now += stake; From 5c9d1277693c6ac8a092805c6d11d31e37773a9e Mon Sep 17 00:00:00 2001 From: Aliaksandr Tsurko Date: Wed, 16 Jul 2025 16:34:34 +0300 Subject: [PATCH 6/7] Rename Alpha to AlphaCurrency --- common/src/currency.rs | 28 ++++----- common/src/lib.rs | 14 ++--- pallets/subtensor/runtime-api/src/lib.rs | 2 +- pallets/subtensor/src/benchmarks.rs | 2 +- pallets/subtensor/src/coinbase/root.rs | 2 +- .../subtensor/src/coinbase/run_coinbase.rs | 2 +- pallets/subtensor/src/epoch/run_epoch.rs | 2 +- pallets/subtensor/src/lib.rs | 4 +- .../subtensor/src/migrations/migrate_rao.rs | 2 +- .../subtensor/src/rpc_info/delegate_info.rs | 2 +- .../subtensor/src/rpc_info/dynamic_info.rs | 14 ++--- pallets/subtensor/src/rpc_info/metagraph.rs | 57 ++++++++++--------- pallets/subtensor/src/rpc_info/neuron_info.rs | 2 +- pallets/subtensor/src/rpc_info/show_subnet.rs | 16 +++--- pallets/subtensor/src/rpc_info/stake_info.rs | 8 +-- pallets/subtensor/src/staking/move_stake.rs | 2 +- .../subtensor/src/staking/recycle_alpha.rs | 2 +- pallets/subtensor/src/staking/remove_stake.rs | 2 +- pallets/subtensor/src/staking/stake_utils.rs | 2 +- pallets/subtensor/src/subnets/leasing.rs | 2 +- pallets/subtensor/src/tests/children.rs | 2 +- pallets/subtensor/src/tests/coinbase.rs | 2 +- pallets/subtensor/src/tests/epoch.rs | 2 +- pallets/subtensor/src/tests/leasing.rs | 2 +- pallets/subtensor/src/tests/recycle_alpha.rs | 2 +- pallets/subtensor/src/tests/registration.rs | 2 +- pallets/subtensor/src/tests/staking.rs | 2 +- pallets/subtensor/src/tests/staking2.rs | 2 +- pallets/subtensor/src/tests/subnet.rs | 2 +- pallets/subtensor/src/tests/swap_coldkey.rs | 2 +- pallets/subtensor/src/tests/swap_hotkey.rs | 2 +- .../src/tests/swap_hotkey_with_subnet.rs | 2 +- pallets/subtensor/src/tests/uids.rs | 2 +- pallets/subtensor/src/utils/misc.rs | 2 +- pallets/swap-interface/src/lib.rs | 4 +- pallets/swap/src/mock.rs | 16 +++--- pallets/swap/src/pallet/impls.rs | 22 ++++--- pallets/swap/src/pallet/mod.rs | 12 ++-- runtime/src/lib.rs | 2 +- 39 files changed, 128 insertions(+), 123 deletions(-) diff --git a/common/src/currency.rs b/common/src/currency.rs index f1b5ef9a31..f50e2bc9a1 100644 --- a/common/src/currency.rs +++ b/common/src/currency.rs @@ -10,7 +10,7 @@ use serde::{Deserialize, Serialize}; use substrate_fixed::traits::{Fixed, ToFixed}; use subtensor_macros::freeze_struct; -#[freeze_struct("597e376f01cf675a")] +#[freeze_struct("b21dcd0434b67c67")] #[repr(transparent)] #[derive( Deserialize, @@ -28,22 +28,22 @@ use subtensor_macros::freeze_struct; PartialOrd, RuntimeDebug, )] -pub struct Alpha(u64); +pub struct AlphaCurrency(u64); -impl TypeInfo for Alpha { +impl TypeInfo for AlphaCurrency { type Identity = ::Identity; fn type_info() -> scale_info::Type { ::type_info() } } -impl Display for Alpha { +impl Display for AlphaCurrency { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { Display::fmt(&self.0, f) } } -impl CompactAs for Alpha { +impl CompactAs for AlphaCurrency { type As = u64; fn encode_as(&self) -> &Self::As { @@ -55,25 +55,25 @@ impl CompactAs for Alpha { } } -impl From> for Alpha { - fn from(c: Compact) -> Self { +impl From> for AlphaCurrency { + fn from(c: Compact) -> Self { c.0 } } -impl From for u64 { - fn from(val: Alpha) -> Self { +impl From for u64 { + fn from(val: AlphaCurrency) -> Self { val.0 } } -impl From for Alpha { +impl From for AlphaCurrency { fn from(value: u64) -> Self { Self(value) } } -impl ToFixed for Alpha { +impl ToFixed for AlphaCurrency { fn to_fixed(self) -> F { self.0.to_fixed() } @@ -94,7 +94,7 @@ impl ToFixed for Alpha { } } -impl Currency for Alpha { +impl Currency for AlphaCurrency { const MAX: Self = Self(u64::MAX); const ZERO: Self = Self(0); } @@ -205,7 +205,7 @@ macro_rules! impl_arithmetic_operators { }; } -impl_arithmetic_operators!(Alpha); +impl_arithmetic_operators!(AlphaCurrency); macro_rules! impl_approx { ($currency_type:ident) => { @@ -228,4 +228,4 @@ macro_rules! impl_approx { }; } -impl_approx!(Alpha); +impl_approx!(AlphaCurrency); diff --git a/common/src/lib.rs b/common/src/lib.rs index a8a3911619..44b7fb879a 100644 --- a/common/src/lib.rs +++ b/common/src/lib.rs @@ -155,7 +155,7 @@ impl Default for ProxyType { pub trait SubnetInfo { fn tao_reserve(netuid: NetUid) -> u64; - fn alpha_reserve(netuid: NetUid) -> Alpha; + fn alpha_reserve(netuid: NetUid) -> AlphaCurrency; fn exists(netuid: NetUid) -> bool; fn mechanism(netuid: NetUid) -> u16; fn is_owner(account_id: &AccountId, netuid: NetUid) -> bool; @@ -163,25 +163,25 @@ pub trait SubnetInfo { pub trait BalanceOps { fn tao_balance(account_id: &AccountId) -> u64; - fn alpha_balance(netuid: NetUid, coldkey: &AccountId, hotkey: &AccountId) -> Alpha; + fn alpha_balance(netuid: NetUid, coldkey: &AccountId, hotkey: &AccountId) -> AlphaCurrency; fn increase_balance(coldkey: &AccountId, tao: u64); fn decrease_balance(coldkey: &AccountId, tao: u64) -> Result; fn increase_stake( coldkey: &AccountId, hotkey: &AccountId, netuid: NetUid, - alpha: Alpha, + alpha: AlphaCurrency, ) -> Result<(), DispatchError>; fn decrease_stake( coldkey: &AccountId, hotkey: &AccountId, netuid: NetUid, - alpha: Alpha, - ) -> Result; + alpha: AlphaCurrency, + ) -> Result; fn increase_provided_tao_reserve(netuid: NetUid, tao: u64); fn decrease_provided_tao_reserve(netuid: NetUid, tao: u64); - fn increase_provided_alpha_reserve(netuid: NetUid, alpha: Alpha); - fn decrease_provided_alpha_reserve(netuid: NetUid, alpha: Alpha); + fn increase_provided_alpha_reserve(netuid: NetUid, alpha: AlphaCurrency); + fn decrease_provided_alpha_reserve(netuid: NetUid, alpha: AlphaCurrency); } pub mod time { diff --git a/pallets/subtensor/runtime-api/src/lib.rs b/pallets/subtensor/runtime-api/src/lib.rs index 42ac17dec8..aa85aeffa8 100644 --- a/pallets/subtensor/runtime-api/src/lib.rs +++ b/pallets/subtensor/runtime-api/src/lib.rs @@ -12,7 +12,7 @@ use pallet_subtensor::rpc_info::{ subnet_info::{SubnetHyperparams, SubnetHyperparamsV2, SubnetInfo, SubnetInfov2}, }; use sp_runtime::AccountId32; -use subtensor_runtime_common::{Alpha as AlphaCurrency, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, NetUid}; // Here we declare the runtime API. It is implemented it the `impl` block in // src/neuron_info.rs, src/subnet_info.rs, and src/delegate_info.rs diff --git a/pallets/subtensor/src/benchmarks.rs b/pallets/subtensor/src/benchmarks.rs index 8c8326d949..b239adb70e 100644 --- a/pallets/subtensor/src/benchmarks.rs +++ b/pallets/subtensor/src/benchmarks.rs @@ -15,7 +15,7 @@ use sp_runtime::{ traits::{BlakeTwo256, Hash}, }; use sp_std::vec; -use subtensor_runtime_common::{Alpha as AlphaCurrency, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, NetUid}; #[frame_benchmarking::v2::benchmarks] mod pallet_benchmarks { diff --git a/pallets/subtensor/src/coinbase/root.rs b/pallets/subtensor/src/coinbase/root.rs index 4d6c9068ce..279132e938 100644 --- a/pallets/subtensor/src/coinbase/root.rs +++ b/pallets/subtensor/src/coinbase/root.rs @@ -22,7 +22,7 @@ use frame_support::weights::Weight; use safe_math::*; use sp_core::Get; use substrate_fixed::types::I64F64; -use subtensor_runtime_common::{Alpha as AlphaCurrency, Currency, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, Currency, NetUid}; impl Pallet { /// Fetches the total count of root network validators diff --git a/pallets/subtensor/src/coinbase/run_coinbase.rs b/pallets/subtensor/src/coinbase/run_coinbase.rs index 8f2384e6d7..aaccb1f749 100644 --- a/pallets/subtensor/src/coinbase/run_coinbase.rs +++ b/pallets/subtensor/src/coinbase/run_coinbase.rs @@ -2,7 +2,7 @@ use super::*; use alloc::collections::BTreeMap; use safe_math::*; use substrate_fixed::types::U96F32; -use subtensor_runtime_common::{Alpha as AlphaCurrency, Currency, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, Currency, NetUid}; use subtensor_swap_interface::SwapHandler; // Distribute dividends to each hotkey diff --git a/pallets/subtensor/src/epoch/run_epoch.rs b/pallets/subtensor/src/epoch/run_epoch.rs index 4614d26752..e9c747ab11 100644 --- a/pallets/subtensor/src/epoch/run_epoch.rs +++ b/pallets/subtensor/src/epoch/run_epoch.rs @@ -4,7 +4,7 @@ use frame_support::IterableStorageDoubleMap; use safe_math::*; use sp_std::vec; use substrate_fixed::types::{I32F32, I64F64, I96F32}; -use subtensor_runtime_common::{Alpha as AlphaCurrency, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, NetUid}; impl Pallet { /// Calculates reward consensus and returns the emissions for uids/hotkeys in a given `netuid`. diff --git a/pallets/subtensor/src/lib.rs b/pallets/subtensor/src/lib.rs index 1d7fdf584c..56dfa300ef 100644 --- a/pallets/subtensor/src/lib.rs +++ b/pallets/subtensor/src/lib.rs @@ -32,7 +32,7 @@ use sp_runtime::{ transaction_validity::{TransactionValidity, TransactionValidityError}, }; use sp_std::marker::PhantomData; -use subtensor_runtime_common::{Alpha as AlphaCurrency, Currency, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, Currency, NetUid}; // ============================ // ==== Benchmark Imports ===== @@ -92,7 +92,7 @@ pub mod pallet { use sp_std::vec::Vec; use substrate_fixed::types::{I96F32, U64F64}; use subtensor_macros::freeze_struct; - use subtensor_runtime_common::{Alpha as AlphaCurrency, NetUid}; + use subtensor_runtime_common::{AlphaCurrency, NetUid}; #[cfg(not(feature = "std"))] use alloc::boxed::Box; diff --git a/pallets/subtensor/src/migrations/migrate_rao.rs b/pallets/subtensor/src/migrations/migrate_rao.rs index 3cbca1c0ae..d529e77098 100644 --- a/pallets/subtensor/src/migrations/migrate_rao.rs +++ b/pallets/subtensor/src/migrations/migrate_rao.rs @@ -2,7 +2,7 @@ use alloc::{format, string::String}; use frame_support::IterableStorageMap; use frame_support::{traits::Get, weights::Weight}; -use subtensor_runtime_common::{Alpha as AlphaCurrency, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, NetUid}; use super::*; diff --git a/pallets/subtensor/src/rpc_info/delegate_info.rs b/pallets/subtensor/src/rpc_info/delegate_info.rs index 5395b331cf..bf6dafd332 100644 --- a/pallets/subtensor/src/rpc_info/delegate_info.rs +++ b/pallets/subtensor/src/rpc_info/delegate_info.rs @@ -6,7 +6,7 @@ use substrate_fixed::types::U64F64; extern crate alloc; use alloc::collections::BTreeMap; use codec::Compact; -use subtensor_runtime_common::{Alpha as AlphaCurrency, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, NetUid}; #[freeze_struct("1fafc4fcf28cba7a")] #[derive(Decode, Encode, PartialEq, Eq, Clone, Debug, TypeInfo)] diff --git a/pallets/subtensor/src/rpc_info/dynamic_info.rs b/pallets/subtensor/src/rpc_info/dynamic_info.rs index b8b2f8aa59..b4394bc68c 100644 --- a/pallets/subtensor/src/rpc_info/dynamic_info.rs +++ b/pallets/subtensor/src/rpc_info/dynamic_info.rs @@ -4,9 +4,9 @@ use codec::Compact; use frame_support::pallet_prelude::{Decode, Encode}; use substrate_fixed::types::I96F32; use subtensor_macros::freeze_struct; -use subtensor_runtime_common::{Alpha, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, NetUid}; -#[freeze_struct("a21076dce0494dfa")] +#[freeze_struct("944ecd330621c61e")] #[derive(Decode, Encode, PartialEq, Eq, Clone, Debug, TypeInfo)] pub struct DynamicInfo { netuid: Compact, @@ -18,13 +18,13 @@ pub struct DynamicInfo { last_step: Compact, blocks_since_last_step: Compact, emission: Compact, - alpha_in: Compact, - alpha_out: Compact, + alpha_in: Compact, + alpha_out: Compact, tao_in: Compact, - alpha_out_emission: Compact, - alpha_in_emission: Compact, + alpha_out_emission: Compact, + alpha_in_emission: Compact, tao_in_emission: Compact, - pending_alpha_emission: Compact, + pending_alpha_emission: Compact, pending_root_emission: Compact, subnet_volume: Compact, network_registered_at: Compact, diff --git a/pallets/subtensor/src/rpc_info/metagraph.rs b/pallets/subtensor/src/rpc_info/metagraph.rs index 2c93092542..3f48c9ad45 100644 --- a/pallets/subtensor/src/rpc_info/metagraph.rs +++ b/pallets/subtensor/src/rpc_info/metagraph.rs @@ -7,9 +7,9 @@ use frame_support::pallet_prelude::{Decode, Encode}; use substrate_fixed::types::I64F64; use substrate_fixed::types::I96F32; use subtensor_macros::freeze_struct; -use subtensor_runtime_common::{Alpha, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, NetUid}; -#[freeze_struct("e1d9ed0a752ab014")] +#[freeze_struct("c25c5560ffd47ccb")] #[derive(Decode, Encode, PartialEq, Eq, Clone, Debug, TypeInfo)] pub struct Metagraph { // Subnet index @@ -32,17 +32,17 @@ pub struct Metagraph { blocks_since_last_step: Compact, // blocks since last epoch. // Subnet emission terms - subnet_emission: Compact, // subnet emission via stao - alpha_in: Compact, // amount of alpha in reserve - alpha_out: Compact, // amount of alpha outstanding - tao_in: Compact, // amount of tao injected per block - alpha_out_emission: Compact, // amount injected in alpha reserves per block - alpha_in_emission: Compact, // amount injected outstanding per block - tao_in_emission: Compact, // amount of tao injected per block - pending_alpha_emission: Compact, // pending alpha to be distributed - pending_root_emission: Compact, // panding tao for root divs to be distributed - subnet_volume: Compact, // volume of the subnet in TAO - moving_price: I96F32, // subnet moving price. + subnet_emission: Compact, // subnet emission via stao + alpha_in: Compact, // amount of alpha in reserve + alpha_out: Compact, // amount of alpha outstanding + tao_in: Compact, // amount of tao injected per block + alpha_out_emission: Compact, // amount injected in alpha reserves per block + alpha_in_emission: Compact, // amount injected outstanding per block + tao_in_emission: Compact, // amount of tao injected per block + pending_alpha_emission: Compact, // pending alpha to be distributed + pending_root_emission: Compact, // panding tao for root divs to be distributed + subnet_volume: Compact, // volume of the subnet in TAO + moving_price: I96F32, // subnet moving price. // Hparams for epoch rho: Compact, // subnet rho param @@ -93,7 +93,7 @@ pub struct Metagraph { validator_permit: Vec, // Val permit per UID pruning_score: Vec>, // Pruning per UID last_update: Vec>, // Last update per UID - emission: Vec>, // Emission per UID + emission: Vec>, // Emission per UID dividends: Vec>, // Dividends per UID incentives: Vec>, // Mining incentives per UID consensus: Vec>, // Consensus per UID @@ -106,10 +106,10 @@ pub struct Metagraph { // Dividend break down. tao_dividends_per_hotkey: Vec<(AccountId, Compact)>, // List of dividend payouts in tao via root. - alpha_dividends_per_hotkey: Vec<(AccountId, Compact)>, // List of dividend payout in alpha via subnet. + alpha_dividends_per_hotkey: Vec<(AccountId, Compact)>, // List of dividend payout in alpha via subnet. } -#[freeze_struct("c8959e499ea19040")] +#[freeze_struct("2fa92e896b40a104")] #[derive(Decode, Encode, PartialEq, Eq, Clone, Debug, TypeInfo)] pub struct SelectiveMetagraph { // Subnet index @@ -133,16 +133,16 @@ pub struct SelectiveMetagraph { // Subnet emission terms subnet_emission: Option>, // subnet emission via stao - alpha_in: Option>, // amount of alpha in reserve - alpha_out: Option>, // amount of alpha outstanding + alpha_in: Option>, // amount of alpha in reserve + alpha_out: Option>, // amount of alpha outstanding tao_in: Option>, // amount of tao injected per block - alpha_out_emission: Option>, // amount injected in alpha reserves per block - alpha_in_emission: Option>, // amount injected outstanding per block - tao_in_emission: Option>, // amount of tao injected per block - pending_alpha_emission: Option>, // pending alpha to be distributed + alpha_out_emission: Option>, // amount injected in alpha reserves per block + alpha_in_emission: Option>, // amount injected outstanding per block + tao_in_emission: Option>, // amount of tao injected per block + pending_alpha_emission: Option>, // pending alpha to be distributed pending_root_emission: Option>, // panding tao for root divs to be distributed - subnet_volume: Option>, // volume of the subnet in TAO - moving_price: Option, // subnet moving price. + subnet_volume: Option>, // volume of the subnet in TAO + moving_price: Option, // subnet moving price. // Hparams for epoch rho: Option>, // subnet rho param @@ -193,7 +193,7 @@ pub struct SelectiveMetagraph { validator_permit: Option>, // Val permit per UID pruning_score: Option>>, // Pruning per UID last_update: Option>>, // Last update per UID - emission: Option>>, // Emission per UID + emission: Option>>, // Emission per UID dividends: Option>>, // Dividends per UID incentives: Option>>, // Mining incentives per UID consensus: Option>>, // Consensus per UID @@ -206,7 +206,7 @@ pub struct SelectiveMetagraph { // Dividend break down. tao_dividends_per_hotkey: Option)>>, // List of dividend payouts in tao via root. - alpha_dividends_per_hotkey: Option)>>, // List of dividend payout in alpha via subnet. + alpha_dividends_per_hotkey: Option)>>, // List of dividend payout in alpha via subnet. // validators validators: Option>>, // List of validators @@ -633,7 +633,7 @@ impl Pallet { axons.push(Self::get_axon_info(netuid, &hotkey)); } let mut tao_dividends_per_hotkey: Vec<(T::AccountId, Compact)> = vec![]; - let mut alpha_dividends_per_hotkey: Vec<(T::AccountId, Compact)> = vec![]; + let mut alpha_dividends_per_hotkey: Vec<(T::AccountId, Compact)> = vec![]; for hotkey in hotkeys.clone() { let tao_divs = TaoDividendsPerSubnet::::get(netuid, hotkey.clone()); let alpha_divs = AlphaDividendsPerSubnet::::get(netuid, hotkey.clone()); @@ -1345,7 +1345,8 @@ impl Pallet { } } Some(SelectiveMetagraphIndex::AlphaDividendsPerHotkey) => { - let mut alpha_dividends_per_hotkey: Vec<(T::AccountId, Compact)> = vec![]; + let mut alpha_dividends_per_hotkey: Vec<(T::AccountId, Compact)> = + vec![]; let n: u16 = Self::get_subnetwork_n(netuid); let mut hotkeys: Vec = vec![]; diff --git a/pallets/subtensor/src/rpc_info/neuron_info.rs b/pallets/subtensor/src/rpc_info/neuron_info.rs index ff9fc3f5b4..8eae264c6e 100644 --- a/pallets/subtensor/src/rpc_info/neuron_info.rs +++ b/pallets/subtensor/src/rpc_info/neuron_info.rs @@ -2,7 +2,7 @@ use super::*; use frame_support::pallet_prelude::{Decode, Encode}; extern crate alloc; use codec::Compact; -use subtensor_runtime_common::{Alpha as AlphaCurrency, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, NetUid}; #[freeze_struct("9e5a291e7e71482d")] #[derive(Decode, Encode, PartialEq, Eq, Clone, Debug, TypeInfo)] diff --git a/pallets/subtensor/src/rpc_info/show_subnet.rs b/pallets/subtensor/src/rpc_info/show_subnet.rs index cf65552e6d..4c39542ace 100644 --- a/pallets/subtensor/src/rpc_info/show_subnet.rs +++ b/pallets/subtensor/src/rpc_info/show_subnet.rs @@ -4,9 +4,9 @@ use crate::epoch::math::*; use codec::Compact; use frame_support::pallet_prelude::{Decode, Encode}; use substrate_fixed::types::I64F64; -use subtensor_runtime_common::{Alpha, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, NetUid}; -#[freeze_struct("d6326208b0c72fc3")] +#[freeze_struct("c990700ae235dee9")] #[derive(Decode, Encode, PartialEq, Eq, Clone, Debug, TypeInfo)] pub struct SubnetState { netuid: Compact, @@ -16,7 +16,7 @@ pub struct SubnetState { validator_permit: Vec, pruning_score: Vec>, last_update: Vec>, - emission: Vec>, + emission: Vec>, dividends: Vec>, incentives: Vec>, consensus: Vec>, @@ -26,7 +26,7 @@ pub struct SubnetState { alpha_stake: Vec>, tao_stake: Vec>, total_stake: Vec>, - emission_history: Vec>>, + emission_history: Vec>>, // identities: Vec, // tao_stake: Compact, // incentive: Compact, @@ -51,12 +51,12 @@ impl Pallet { /// # Returns /// /// * `Vec>>` - A vector of vectors containing the emission history for each hotkey across all subnets. - pub fn get_emissions_history(hotkeys: Vec) -> Vec>> { - let mut result: Vec>> = vec![]; + pub fn get_emissions_history(hotkeys: Vec) -> Vec>> { + let mut result: Vec>> = vec![]; for netuid in Self::get_all_subnet_netuids() { - let mut hotkeys_emissions: Vec> = vec![]; + let mut hotkeys_emissions: Vec> = vec![]; for hotkey in hotkeys.clone() { - let last_emission: Compact = + let last_emission: Compact = LastHotkeyEmissionOnNetuid::::get(hotkey.clone(), netuid).into(); hotkeys_emissions.push(last_emission); } diff --git a/pallets/subtensor/src/rpc_info/stake_info.rs b/pallets/subtensor/src/rpc_info/stake_info.rs index 1e281e5ce7..7e3779c571 100644 --- a/pallets/subtensor/src/rpc_info/stake_info.rs +++ b/pallets/subtensor/src/rpc_info/stake_info.rs @@ -2,20 +2,20 @@ extern crate alloc; use codec::Compact; use frame_support::pallet_prelude::{Decode, Encode}; -use subtensor_runtime_common::{Alpha, Currency, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, Currency, NetUid}; use subtensor_swap_interface::SwapHandler; use super::*; -#[freeze_struct("b8e0d5baa7dacb94")] +#[freeze_struct("cff08b08c64eb867")] #[derive(Decode, Encode, PartialEq, Eq, Clone, Debug, TypeInfo)] pub struct StakeInfo { hotkey: AccountId, coldkey: AccountId, netuid: Compact, - stake: Compact, + stake: Compact, locked: Compact, - emission: Compact, + emission: Compact, tao_emission: Compact, drain: Compact, is_registered: bool, diff --git a/pallets/subtensor/src/staking/move_stake.rs b/pallets/subtensor/src/staking/move_stake.rs index 4c6bb37813..ec778e4d64 100644 --- a/pallets/subtensor/src/staking/move_stake.rs +++ b/pallets/subtensor/src/staking/move_stake.rs @@ -2,7 +2,7 @@ use super::*; use safe_math::*; use sp_core::Get; use substrate_fixed::types::U64F64; -use subtensor_runtime_common::{Alpha as AlphaCurrency, Currency, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, Currency, NetUid}; use subtensor_swap_interface::SwapHandler; impl Pallet { diff --git a/pallets/subtensor/src/staking/recycle_alpha.rs b/pallets/subtensor/src/staking/recycle_alpha.rs index ca418ca9b9..2fbbfb3b06 100644 --- a/pallets/subtensor/src/staking/recycle_alpha.rs +++ b/pallets/subtensor/src/staking/recycle_alpha.rs @@ -1,6 +1,6 @@ use super::*; use crate::{Error, system::ensure_signed}; -use subtensor_runtime_common::{Alpha as AlphaCurrency, Currency, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, Currency, NetUid}; impl Pallet { /// Recycles alpha from a cold/hot key pair, reducing AlphaOut on a subnet diff --git a/pallets/subtensor/src/staking/remove_stake.rs b/pallets/subtensor/src/staking/remove_stake.rs index 9a3579cad6..afe9d19308 100644 --- a/pallets/subtensor/src/staking/remove_stake.rs +++ b/pallets/subtensor/src/staking/remove_stake.rs @@ -1,7 +1,7 @@ use subtensor_swap_interface::{OrderType, SwapHandler}; use super::*; -use subtensor_runtime_common::{Alpha as AlphaCurrency, Currency, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, Currency, NetUid}; impl Pallet { /// ---- The implementation for the extrinsic remove_stake: Removes stake from a hotkey account and adds it onto a coldkey. diff --git a/pallets/subtensor/src/staking/stake_utils.rs b/pallets/subtensor/src/staking/stake_utils.rs index 6a28b846ed..52c6224f06 100644 --- a/pallets/subtensor/src/staking/stake_utils.rs +++ b/pallets/subtensor/src/staking/stake_utils.rs @@ -3,7 +3,7 @@ use safe_math::*; use share_pool::{SharePool, SharePoolDataOperations}; use sp_std::ops::Neg; use substrate_fixed::types::{I64F64, I96F32, U64F64, U96F32}; -use subtensor_runtime_common::{Alpha as AlphaCurrency, Currency, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, Currency, NetUid}; use subtensor_swap_interface::{OrderType, SwapHandler, SwapResult}; impl Pallet { diff --git a/pallets/subtensor/src/subnets/leasing.rs b/pallets/subtensor/src/subnets/leasing.rs index ee31750ece..9cb84c571f 100644 --- a/pallets/subtensor/src/subnets/leasing.rs +++ b/pallets/subtensor/src/subnets/leasing.rs @@ -7,7 +7,7 @@ use frame_system::pallet_prelude::*; use sp_core::blake2_256; use sp_runtime::{Percent, traits::TrailingZeroInput}; use substrate_fixed::types::U64F64; -use subtensor_runtime_common::{Alpha as AlphaCurrency, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, NetUid}; use subtensor_swap_interface::SwapHandler; pub type LeaseId = u32; diff --git a/pallets/subtensor/src/tests/children.rs b/pallets/subtensor/src/tests/children.rs index f873b98a9b..12991094e5 100644 --- a/pallets/subtensor/src/tests/children.rs +++ b/pallets/subtensor/src/tests/children.rs @@ -6,7 +6,7 @@ use super::mock::*; use approx::assert_abs_diff_eq; use frame_support::{assert_err, assert_noop, assert_ok}; use substrate_fixed::types::{I64F64, I96F32, U96F32}; -use subtensor_runtime_common::Alpha as AlphaCurrency; +use subtensor_runtime_common::AlphaCurrency; use subtensor_swap_interface::SwapHandler; use crate::{utils::rate_limiting::TransactionType, *}; diff --git a/pallets/subtensor/src/tests/coinbase.rs b/pallets/subtensor/src/tests/coinbase.rs index 9f69d39e05..03fdf4227e 100644 --- a/pallets/subtensor/src/tests/coinbase.rs +++ b/pallets/subtensor/src/tests/coinbase.rs @@ -9,7 +9,7 @@ use frame_support::assert_ok; use pallet_subtensor_swap::position::PositionId; use sp_core::U256; use substrate_fixed::types::{I64F64, I96F32, U96F32}; -use subtensor_runtime_common::Alpha as AlphaCurrency; +use subtensor_runtime_common::AlphaCurrency; #[allow(clippy::arithmetic_side_effects)] fn close(value: u64, target: u64, eps: u64) { diff --git a/pallets/subtensor/src/tests/epoch.rs b/pallets/subtensor/src/tests/epoch.rs index db8ff881f5..4b07455f46 100644 --- a/pallets/subtensor/src/tests/epoch.rs +++ b/pallets/subtensor/src/tests/epoch.rs @@ -11,7 +11,7 @@ use frame_support::{assert_err, assert_ok}; use rand::{Rng, SeedableRng, distributions::Uniform, rngs::StdRng, seq::SliceRandom, thread_rng}; use sp_core::{Get, U256}; use substrate_fixed::types::I32F32; -use subtensor_runtime_common::Alpha as AlphaCurrency; +use subtensor_runtime_common::AlphaCurrency; use subtensor_swap_interface::SwapHandler; use super::mock::*; diff --git a/pallets/subtensor/src/tests/leasing.rs b/pallets/subtensor/src/tests/leasing.rs index f580757279..ac27347055 100644 --- a/pallets/subtensor/src/tests/leasing.rs +++ b/pallets/subtensor/src/tests/leasing.rs @@ -9,7 +9,7 @@ use frame_support::{StorageDoubleMap, assert_err, assert_ok}; use sp_core::U256; use sp_runtime::Percent; use substrate_fixed::types::U64F64; -use subtensor_runtime_common::Alpha as AlphaCurrency; +use subtensor_runtime_common::AlphaCurrency; #[test] fn test_register_leased_network_works() { diff --git a/pallets/subtensor/src/tests/recycle_alpha.rs b/pallets/subtensor/src/tests/recycle_alpha.rs index 5ceaf86d13..e2dd644fa7 100644 --- a/pallets/subtensor/src/tests/recycle_alpha.rs +++ b/pallets/subtensor/src/tests/recycle_alpha.rs @@ -1,7 +1,7 @@ use approx::assert_abs_diff_eq; use frame_support::{assert_noop, assert_ok, traits::Currency}; use sp_core::U256; -use subtensor_runtime_common::{Alpha as AlphaCurrency, Currency as CurrencyT}; +use subtensor_runtime_common::{AlphaCurrency, Currency as CurrencyT}; use super::mock; use super::mock::*; diff --git a/pallets/subtensor/src/tests/registration.rs b/pallets/subtensor/src/tests/registration.rs index 8a39306315..997a71268e 100644 --- a/pallets/subtensor/src/tests/registration.rs +++ b/pallets/subtensor/src/tests/registration.rs @@ -8,7 +8,7 @@ use frame_support::{assert_err, assert_noop, assert_ok}; use frame_system::{Config, RawOrigin}; use sp_core::U256; use sp_runtime::traits::{DispatchInfoOf, TransactionExtension, TxBaseImplication}; -use subtensor_runtime_common::{Alpha as AlphaCurrency, Currency as CurrencyT, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, Currency as CurrencyT, NetUid}; use super::mock; use super::mock::*; diff --git a/pallets/subtensor/src/tests/staking.rs b/pallets/subtensor/src/tests/staking.rs index a73761dab4..c71022d782 100644 --- a/pallets/subtensor/src/tests/staking.rs +++ b/pallets/subtensor/src/tests/staking.rs @@ -14,7 +14,7 @@ use safe_math::FixedExt; use sp_core::{Get, H256, U256}; use substrate_fixed::traits::FromFixed; use substrate_fixed::types::{I96F32, I110F18, U64F64, U96F32}; -use subtensor_runtime_common::{Alpha as AlphaCurrency, Currency as CurrencyT, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, Currency as CurrencyT, NetUid}; use subtensor_swap_interface::{OrderType, SwapHandler}; use super::mock; diff --git a/pallets/subtensor/src/tests/staking2.rs b/pallets/subtensor/src/tests/staking2.rs index b42b437ea2..9e374095de 100644 --- a/pallets/subtensor/src/tests/staking2.rs +++ b/pallets/subtensor/src/tests/staking2.rs @@ -6,7 +6,7 @@ use frame_support::{ weights::Weight, }; use sp_core::U256; -use subtensor_runtime_common::{Alpha as AlphaCurrency, Currency}; +use subtensor_runtime_common::{AlphaCurrency, Currency}; use subtensor_swap_interface::SwapHandler; use super::mock; diff --git a/pallets/subtensor/src/tests/subnet.rs b/pallets/subtensor/src/tests/subnet.rs index cde332321c..d2bab08d39 100644 --- a/pallets/subtensor/src/tests/subnet.rs +++ b/pallets/subtensor/src/tests/subnet.rs @@ -5,7 +5,7 @@ use crate::*; use frame_support::{assert_err, assert_noop, assert_ok}; use frame_system::Config; use sp_core::U256; -use subtensor_runtime_common::Alpha as AlphaCurrency; +use subtensor_runtime_common::AlphaCurrency; use super::mock; diff --git a/pallets/subtensor/src/tests/swap_coldkey.rs b/pallets/subtensor/src/tests/swap_coldkey.rs index a3ab024f31..bab264a3c6 100644 --- a/pallets/subtensor/src/tests/swap_coldkey.rs +++ b/pallets/subtensor/src/tests/swap_coldkey.rs @@ -12,7 +12,7 @@ use frame_system::{Config, RawOrigin}; use sp_core::{Get, H256, U256}; use sp_runtime::{DispatchError, traits::TxBaseImplication}; use substrate_fixed::types::U96F32; -use subtensor_runtime_common::{Alpha as AlphaCurrency, Currency, SubnetInfo}; +use subtensor_runtime_common::{AlphaCurrency, Currency, SubnetInfo}; use subtensor_swap_interface::{OrderType, SwapHandler}; use super::mock; diff --git a/pallets/subtensor/src/tests/swap_hotkey.rs b/pallets/subtensor/src/tests/swap_hotkey.rs index 7b4f713c77..506bd77a9d 100644 --- a/pallets/subtensor/src/tests/swap_hotkey.rs +++ b/pallets/subtensor/src/tests/swap_hotkey.rs @@ -8,7 +8,7 @@ use frame_system::{Config, RawOrigin}; use sp_core::{Get, H160, H256, U256}; use sp_runtime::SaturatedConversion; use substrate_fixed::types::U64F64; -use subtensor_runtime_common::Alpha as AlphaCurrency; +use subtensor_runtime_common::AlphaCurrency; use subtensor_swap_interface::SwapHandler; use super::mock; diff --git a/pallets/subtensor/src/tests/swap_hotkey_with_subnet.rs b/pallets/subtensor/src/tests/swap_hotkey_with_subnet.rs index bc52dad426..de012d4074 100644 --- a/pallets/subtensor/src/tests/swap_hotkey_with_subnet.rs +++ b/pallets/subtensor/src/tests/swap_hotkey_with_subnet.rs @@ -5,7 +5,7 @@ use codec::Encode; use frame_support::weights::Weight; use frame_support::{assert_err, assert_noop, assert_ok}; use frame_system::{Config, RawOrigin}; -use subtensor_runtime_common::{Alpha as AlphaCurrency, Currency}; +use subtensor_runtime_common::{AlphaCurrency, Currency}; use super::mock::*; use crate::*; diff --git a/pallets/subtensor/src/tests/uids.rs b/pallets/subtensor/src/tests/uids.rs index 2544c3061b..bca6945b44 100644 --- a/pallets/subtensor/src/tests/uids.rs +++ b/pallets/subtensor/src/tests/uids.rs @@ -5,7 +5,7 @@ use crate::*; use frame_support::{assert_err, assert_ok}; use frame_system::Config; use sp_core::{H160, U256}; -use subtensor_runtime_common::Alpha as AlphaCurrency; +use subtensor_runtime_common::AlphaCurrency; /******************************************** tests for uids.rs file diff --git a/pallets/subtensor/src/utils/misc.rs b/pallets/subtensor/src/utils/misc.rs index 926fb7a8a1..4367fc94ca 100644 --- a/pallets/subtensor/src/utils/misc.rs +++ b/pallets/subtensor/src/utils/misc.rs @@ -8,7 +8,7 @@ use sp_core::Get; use sp_core::U256; use sp_runtime::Saturating; use substrate_fixed::types::{I32F32, U96F32}; -use subtensor_runtime_common::{Alpha as AlphaCurrency, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, NetUid}; impl Pallet { pub fn ensure_subnet_owner_or_root( diff --git a/pallets/swap-interface/src/lib.rs b/pallets/swap-interface/src/lib.rs index 4939edaba6..fce3d53f18 100644 --- a/pallets/swap-interface/src/lib.rs +++ b/pallets/swap-interface/src/lib.rs @@ -2,7 +2,7 @@ use frame_support::pallet_prelude::*; use substrate_fixed::types::U96F32; -use subtensor_runtime_common::{Alpha, NetUid}; +use subtensor_runtime_common::{AlphaCurrency, NetUid}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum OrderType { @@ -28,7 +28,7 @@ pub trait SwapHandler { fn current_alpha_price(netuid: NetUid) -> U96F32; fn max_price() -> u64; fn min_price() -> u64; - fn adjust_protocol_liquidity(netuid: NetUid, tao_delta: u64, alpha_delta: Alpha); + fn adjust_protocol_liquidity(netuid: NetUid, tao_delta: u64, alpha_delta: AlphaCurrency); fn is_user_liquidity_enabled(netuid: NetUid) -> bool; } diff --git a/pallets/swap/src/mock.rs b/pallets/swap/src/mock.rs index 57fb79d121..014c6ce4fe 100644 --- a/pallets/swap/src/mock.rs +++ b/pallets/swap/src/mock.rs @@ -14,7 +14,7 @@ use sp_runtime::{ BuildStorage, traits::{BlakeTwo256, IdentityLookup}, }; -use subtensor_runtime_common::{Alpha, BalanceOps, NetUid, SubnetInfo}; +use subtensor_runtime_common::{AlphaCurrency, BalanceOps, NetUid, SubnetInfo}; use crate::pallet::EnabledUserLiquidity; @@ -95,7 +95,7 @@ impl SubnetInfo for MockLiquidityProvider { } } - fn alpha_reserve(netuid: NetUid) -> Alpha { + fn alpha_reserve(netuid: NetUid) -> AlphaCurrency { match netuid.into() { 123u16 => 10_000.into(), WRAPPING_FEES_NETUID => 400_000_000_000.into(), @@ -132,7 +132,7 @@ impl BalanceOps for MockBalanceOps { _: NetUid, coldkey_account_id: &AccountId, hotkey_account_id: &AccountId, - ) -> Alpha { + ) -> AlphaCurrency { match (coldkey_account_id, hotkey_account_id) { (&OK_COLDKEY_ACCOUNT_ID, &OK_HOTKEY_ACCOUNT_ID) => 100_000_000_000_000, (&OK_COLDKEY_ACCOUNT_ID_2, &OK_HOTKEY_ACCOUNT_ID_2) => 100_000_000_000_000, @@ -154,7 +154,7 @@ impl BalanceOps for MockBalanceOps { _coldkey: &AccountId, _hotkey: &AccountId, _netuid: NetUid, - _alpha: Alpha, + _alpha: AlphaCurrency, ) -> Result<(), DispatchError> { Ok(()) } @@ -163,15 +163,15 @@ impl BalanceOps for MockBalanceOps { _coldkey: &AccountId, _hotkey: &AccountId, _netuid: NetUid, - alpha: Alpha, - ) -> Result { + alpha: AlphaCurrency, + ) -> Result { Ok(alpha) } fn increase_provided_tao_reserve(_netuid: NetUid, _tao: u64) {} fn decrease_provided_tao_reserve(_netuid: NetUid, _tao: u64) {} - fn increase_provided_alpha_reserve(_netuid: NetUid, _alpha: Alpha) {} - fn decrease_provided_alpha_reserve(_netuid: NetUid, _alpha: Alpha) {} + fn increase_provided_alpha_reserve(_netuid: NetUid, _alpha: AlphaCurrency) {} + fn decrease_provided_alpha_reserve(_netuid: NetUid, _alpha: AlphaCurrency) {} } impl crate::pallet::Config for Test { diff --git a/pallets/swap/src/pallet/impls.rs b/pallets/swap/src/pallet/impls.rs index 97616d2ad5..2e0a28c978 100644 --- a/pallets/swap/src/pallet/impls.rs +++ b/pallets/swap/src/pallet/impls.rs @@ -7,7 +7,7 @@ use safe_math::*; use sp_arithmetic::helpers_128bit; use sp_runtime::traits::AccountIdConversion; use substrate_fixed::types::{I64F64, U64F64, U96F32}; -use subtensor_runtime_common::{Alpha, BalanceOps, Currency, NetUid, SubnetInfo}; +use subtensor_runtime_common::{AlphaCurrency, BalanceOps, Currency, NetUid, SubnetInfo}; use subtensor_swap_interface::{SwapHandler, SwapResult}; use super::pallet::*; @@ -22,9 +22,9 @@ const MAX_SWAP_ITERATIONS: u16 = 1000; #[derive(Debug, PartialEq)] pub struct UpdateLiquidityResult { pub tao: u64, - pub alpha: Alpha, + pub alpha: AlphaCurrency, pub fee_tao: u64, - pub fee_alpha: Alpha, + pub fee_alpha: AlphaCurrency, pub removed: bool, pub tick_low: TickIndex, pub tick_high: TickIndex, @@ -33,9 +33,9 @@ pub struct UpdateLiquidityResult { #[derive(Debug, PartialEq)] pub struct RemoveLiquidityResult { pub tao: u64, - pub alpha: Alpha, + pub alpha: AlphaCurrency, pub fee_tao: u64, - pub fee_alpha: Alpha, + pub fee_alpha: AlphaCurrency, pub tick_low: TickIndex, pub tick_high: TickIndex, pub liquidity: u64, @@ -354,7 +354,11 @@ impl Pallet { } /// Adjusts protocol liquidity with new values of TAO and Alpha reserve - pub(super) fn adjust_protocol_liquidity(netuid: NetUid, tao_delta: u64, alpha_delta: Alpha) { + pub(super) fn adjust_protocol_liquidity( + netuid: NetUid, + tao_delta: u64, + alpha_delta: AlphaCurrency, + ) { // Update protocol position with new liquidity let protocol_account_id = Self::protocol_account_id(); let mut positions = @@ -838,7 +842,7 @@ impl Pallet { netuid.into(), coldkey_account_id, hotkey_account_id - ) >= Alpha::from(alpha), + ) >= AlphaCurrency::from(alpha), Error::::InsufficientBalance ); @@ -1003,7 +1007,7 @@ impl Pallet { ensure!( T::BalanceOps::tao_balance(coldkey_account_id) >= tao && T::BalanceOps::alpha_balance(netuid, coldkey_account_id, hotkey_account_id) - >= Alpha::from(alpha.saturating_to_num::()), + >= AlphaCurrency::from(alpha.saturating_to_num::()), Error::::InsufficientBalance ); } else { @@ -1265,7 +1269,7 @@ impl SwapHandler for Pallet { .saturating_to_num() } - fn adjust_protocol_liquidity(netuid: NetUid, tao_delta: u64, alpha_delta: Alpha) { + fn adjust_protocol_liquidity(netuid: NetUid, tao_delta: u64, alpha_delta: AlphaCurrency) { Self::adjust_protocol_liquidity(netuid, tao_delta, alpha_delta); } diff --git a/pallets/swap/src/pallet/mod.rs b/pallets/swap/src/pallet/mod.rs index ebb71a1a36..e765ef0df4 100644 --- a/pallets/swap/src/pallet/mod.rs +++ b/pallets/swap/src/pallet/mod.rs @@ -4,7 +4,7 @@ use core::ops::Neg; use frame_support::{PalletId, pallet_prelude::*, traits::Get}; use frame_system::pallet_prelude::*; use substrate_fixed::types::U64F64; -use subtensor_runtime_common::{Alpha, BalanceOps, Currency, NetUid, SubnetInfo}; +use subtensor_runtime_common::{AlphaCurrency, BalanceOps, Currency, NetUid, SubnetInfo}; use crate::{ position::{Position, PositionId}, @@ -165,7 +165,7 @@ mod pallet { /// The amount of TAO tokens committed to the position tao: u64, /// The amount of Alpha tokens committed to the position - alpha: Alpha, + alpha: AlphaCurrency, /// the lower tick tick_low: TickIndex, /// the upper tick @@ -187,11 +187,11 @@ mod pallet { /// The amount of TAO tokens returned to the user tao: u64, /// The amount of Alpha tokens returned to the user - alpha: Alpha, + alpha: AlphaCurrency, /// The amount of TAO fees earned from the position fee_tao: u64, /// The amount of Alpha fees earned from the position - fee_alpha: Alpha, + fee_alpha: AlphaCurrency, /// the lower tick tick_low: TickIndex, /// the upper tick @@ -218,7 +218,7 @@ mod pallet { /// The amount of TAO fees earned from the position fee_tao: u64, /// The amount of Alpha fees earned from the position - fee_alpha: Alpha, + fee_alpha: AlphaCurrency, /// the lower tick tick_low: TickIndex, /// the upper tick @@ -372,7 +372,7 @@ mod pallet { tick_high, liquidity, )?; - let alpha = Alpha::from(alpha); + let alpha = AlphaCurrency::from(alpha); // Remove TAO and Alpha balances or fail transaction if they can't be removed exactly let tao_provided = T::BalanceOps::decrease_balance(&coldkey, tao)?; diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index 163f2147ef..513dc017c5 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -68,7 +68,7 @@ use sp_std::prelude::*; use sp_version::NativeVersion; use sp_version::RuntimeVersion; use subtensor_precompiles::Precompiles; -use subtensor_runtime_common::{Alpha as AlphaCurrency, time::*, *}; +use subtensor_runtime_common::{AlphaCurrency, time::*, *}; // A few exports that help ease life for downstream crates. pub use frame_support::{ From b383e182193b6c9717c54b2dcf5b89e484ad7372 Mon Sep 17 00:00:00 2001 From: Aliaksandr Tsurko Date: Wed, 16 Jul 2025 20:05:56 +0300 Subject: [PATCH 7/7] Fix compilation --- pallets/subtensor/src/tests/epoch.rs | 88 ++++++++++++++++++++-------- 1 file changed, 65 insertions(+), 23 deletions(-) diff --git a/pallets/subtensor/src/tests/epoch.rs b/pallets/subtensor/src/tests/epoch.rs index 2af47ff167..f6b5b16d08 100644 --- a/pallets/subtensor/src/tests/epoch.rs +++ b/pallets/subtensor/src/tests/epoch.rs @@ -3586,7 +3586,10 @@ fn test_epoch_masks_first_tempo() { let (hot0, cold0) = (U256::from(2), U256::from(22)); register_ok_neuron(netuid, hot0, cold0, 0); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &hot0, &cold0, netuid, 1_000, + &hot0, + &cold0, + netuid, + 1_000.into(), ); run_to_block(tempo as u64 + 1); @@ -3594,7 +3597,10 @@ fn test_epoch_masks_first_tempo() { let (hot1, cold1) = (U256::from(3), U256::from(23)); register_ok_neuron(netuid, hot1, cold1, 0); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &hot1, &cold1, netuid, 1_000, + &hot1, + &cold1, + netuid, + 1_000.into(), ); // WAIT one block so out‑dated rule will _not_ wipe the cell @@ -3613,7 +3619,7 @@ fn test_epoch_masks_first_tempo() { SubtensorModule::set_commit_reveal_weights_enabled(netuid, true); /* epoch inside first tempo: uid‑1 must get ZERO reward */ - SubtensorModule::epoch(netuid, 1_000); + SubtensorModule::epoch(netuid, 1_000.into()); assert_eq!(SubtensorModule::get_rank_for_uid(netuid, 1), 0); assert_eq!(SubtensorModule::get_incentive_for_uid(netuid, 1), 0); }); @@ -3634,14 +3640,20 @@ fn test_epoch_masks_full_reveal_window() { let (hot1, cold1) = (U256::from(401), U256::from(441)); register_ok_neuron(netuid, hot0, cold0, 0); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &hot0, &cold0, netuid, 1_000, + &hot0, + &cold0, + netuid, + 1_000.into(), ); SubtensorModule::set_validator_permit_for_uid(netuid, 0, true); run_to_block(tempo as u64 + 1); register_ok_neuron(netuid, hot1, cold1, 0); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &hot1, &cold1, netuid, 1_000, + &hot1, + &cold1, + netuid, + 1_000.into(), ); SubtensorModule::set_validator_permit_for_uid(netuid, 1, true); SubtensorModule::set_max_allowed_validators(netuid, 2); @@ -3662,7 +3674,7 @@ fn test_epoch_masks_full_reveal_window() { /* inside the 2×reveal window uid‑1 must have rank 0 */ for _ in 0..(reveal_period * 2) { - SubtensorModule::epoch(netuid, 1); + SubtensorModule::epoch(netuid, 1.into()); assert_eq!(Rank::::get(netuid)[1], 0); run_to_block(System::block_number() + tempo as u64 + 1); } @@ -3679,7 +3691,7 @@ fn test_epoch_masks_full_reveal_window() { )); SubtensorModule::set_commit_reveal_weights_enabled(netuid, true); - SubtensorModule::epoch(netuid, 1); + SubtensorModule::epoch(netuid, 1.into()); assert!(Rank::::get(netuid)[1] > 0); }); } @@ -3699,14 +3711,20 @@ fn test_epoch_mask_boundary() { let (hot1, cold1) = (U256::from(601), U256::from(651)); register_ok_neuron(netuid, hot0, cold0, 0); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &hot0, &cold0, netuid, 1_000, + &hot0, + &cold0, + netuid, + 1_000.into(), ); SubtensorModule::set_validator_permit_for_uid(netuid, 0, true); run_to_block(tempo as u64 + 1); register_ok_neuron(netuid, hot1, cold1, 0); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &hot1, &cold1, netuid, 1_000, + &hot1, + &cold1, + netuid, + 1_000.into(), ); SubtensorModule::set_validator_permit_for_uid(netuid, 1, true); SubtensorModule::set_max_allowed_validators(netuid, 2); @@ -3725,7 +3743,7 @@ fn test_epoch_mask_boundary() { SubtensorModule::set_commit_reveal_weights_enabled(netuid, true); /* epoch 0 – masked */ - SubtensorModule::epoch(netuid, 1); + SubtensorModule::epoch(netuid, 1.into()); assert_eq!(Rank::::get(netuid)[1], 0); /* advance beyond window */ @@ -3744,7 +3762,7 @@ fn test_epoch_mask_boundary() { )); SubtensorModule::set_commit_reveal_weights_enabled(netuid, true); - SubtensorModule::epoch(netuid, 1); + SubtensorModule::epoch(netuid, 1.into()); assert!(Rank::::get(netuid)[1] > 0); }); } @@ -3763,7 +3781,10 @@ fn test_epoch_masking_resumes_after_feature_toggle() { let (hot0, cold0) = (U256::from(1200), U256::from(1250)); register_ok_neuron(netuid, hot0, cold0, 0); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &hot0, &cold0, netuid, 1_000, + &hot0, + &cold0, + netuid, + 1_000.into(), ); SubtensorModule::set_validator_permit_for_uid(netuid, 0, true); @@ -3784,7 +3805,10 @@ fn test_epoch_masking_resumes_after_feature_toggle() { let (hot1, cold1) = (U256::from(1201), U256::from(1251)); register_ok_neuron(netuid, hot1, cold1, 0); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &hot1, &cold1, netuid, 1_000, + &hot1, + &cold1, + netuid, + 1_000.into(), ); run_to_block(System::block_number() + 1); // avoid out‑dated @@ -3801,7 +3825,7 @@ fn test_epoch_masking_resumes_after_feature_toggle() { /* uid‑1 must stay masked for two epochs */ for _ in 0..reveal { - SubtensorModule::epoch(netuid, 1); + SubtensorModule::epoch(netuid, 1.into()); assert_eq!(SubtensorModule::get_rank_for_uid(netuid, 1), 0); run_to_block(System::block_number() + tempo as u64 + 1); } @@ -3825,7 +3849,10 @@ fn test_epoch_masks_incoming_to_sniped_uid_prevents_inheritance() { let (val_hot, val_cold) = (U256::from(100), U256::from(200)); register_ok_neuron(netuid, val_hot, val_cold, 0); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &val_hot, &val_cold, netuid, 10_000, + &val_hot, + &val_cold, + netuid, + 10_000.into(), ); SubtensorModule::set_validator_permit_for_uid(netuid, 0, true); @@ -3833,14 +3860,20 @@ fn test_epoch_masks_incoming_to_sniped_uid_prevents_inheritance() { let (old_hot, old_cold) = (U256::from(101), U256::from(201)); register_ok_neuron(netuid, old_hot, old_cold, 0); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &old_hot, &old_cold, netuid, 100, + &old_hot, + &old_cold, + netuid, + 100.into(), ); /* filler uid‑2 */ let (fill_hot, fill_cold) = (U256::from(102), U256::from(202)); register_ok_neuron(netuid, fill_hot, fill_cold, 0); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &fill_hot, &fill_cold, netuid, 5_000, + &fill_hot, + &fill_cold, + netuid, + 5_000.into(), ); SubtensorModule::set_max_allowed_validators(netuid, 3); @@ -3857,13 +3890,16 @@ fn test_epoch_masks_incoming_to_sniped_uid_prevents_inheritance() { 0 )); SubtensorModule::set_commit_reveal_weights_enabled(netuid, true); - SubtensorModule::epoch(netuid, 1_000); + SubtensorModule::epoch(netuid, 1_000.into()); /* snipe uid‑1 */ let (new_hot, new_cold) = (U256::from(103), U256::from(203)); register_ok_neuron(netuid, new_hot, new_cold, 0); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &new_hot, &new_cold, netuid, 10_000, + &new_hot, + &new_cold, + netuid, + 10_000.into(), ); assert_eq!( SubtensorModule::get_uid_for_net_and_hotkey(netuid, &new_hot).unwrap(), @@ -3885,7 +3921,7 @@ fn test_epoch_masks_incoming_to_sniped_uid_prevents_inheritance() { SubtensorModule::set_commit_reveal_weights_enabled(netuid, true); /* epoch inside window – new uid‑1 must NOT inherit */ - SubtensorModule::epoch(netuid, 1_000); + SubtensorModule::epoch(netuid, 1_000.into()); assert_eq!(SubtensorModule::get_rank_for_uid(netuid, 1), 0); assert_eq!(SubtensorModule::get_incentive_for_uid(netuid, 1), 0); }); @@ -3903,14 +3939,20 @@ fn test_epoch_no_mask_when_commit_reveal_disabled() { let (hot, cold) = (U256::from(1000), U256::from(1100)); register_ok_neuron(netuid, hot, cold, 0); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &hot, &cold, netuid, 1_000, + &hot, + &cold, + netuid, + 1_000.into(), ); SubtensorModule::set_validator_permit_for_uid(netuid, 0, true); let (hot1, cold1) = (U256::from(1001), U256::from(1101)); register_ok_neuron(netuid, hot1, cold1, 0); SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet( - &hot1, &cold1, netuid, 1_000, + &hot1, + &cold1, + netuid, + 1_000.into(), ); SubtensorModule::set_weights_set_rate_limit(netuid, 0); @@ -3923,7 +3965,7 @@ fn test_epoch_no_mask_when_commit_reveal_disabled() { )); for _ in 0..3 { - SubtensorModule::epoch(netuid, 1); + SubtensorModule::epoch(netuid, 1.into()); let row = SubtensorModule::get_weights_sparse(netuid)[0].clone(); assert!(!row.is_empty(), "no mask when CR disabled"); run_to_block(System::block_number() + tempo as u64 + 1);