Skip to content

Stake operation limits #1766

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 14 commits into
base: devnet-ready
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pallets/admin-utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -734,7 +734,7 @@ pub mod pallet {
/// It is only callable by the root account or subnet owner.
/// The extrinsic will call the Subtensor pallet to set the difficulty.
#[pallet::call_index(24)]
#[pallet::weight(Weight::from_parts(20_280_000, 0)
#[pallet::weight(Weight::from_parts(17_040_000, 0)
.saturating_add(<T as frame_system::Config>::DbWeight::get().reads(1_u64))
.saturating_add(<T as frame_system::Config>::DbWeight::get().writes(1_u64)))]
pub fn sudo_set_difficulty(
Expand Down
18 changes: 18 additions & 0 deletions pallets/subtensor/src/benchmarks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -769,6 +769,9 @@ mod pallet_benchmarks {

Subtensor::<T>::create_account_if_non_existent(&coldkey, &destination);

// Remove stake limit for benchmark
StakingOperationRateLimiter::<T>::remove((origin.clone(), coldkey.clone(), netuid));

#[extrinsic_call]
_(
RawOrigin::Signed(coldkey.clone()),
Expand Down Expand Up @@ -827,6 +830,9 @@ mod pallet_benchmarks {

let amount_unstaked: u64 = 30_000_000_000;

// Remove stake limit for benchmark
StakingOperationRateLimiter::<T>::remove((hotkey.clone(), coldkey.clone(), netuid));

#[extrinsic_call]
_(
RawOrigin::Signed(coldkey.clone()),
Expand Down Expand Up @@ -887,6 +893,9 @@ mod pallet_benchmarks {
allow
));

// Remove stake limit for benchmark
StakingOperationRateLimiter::<T>::remove((hot.clone(), coldkey.clone(), netuid1));

#[extrinsic_call]
_(
RawOrigin::Signed(coldkey.clone()),
Expand Down Expand Up @@ -938,6 +947,9 @@ mod pallet_benchmarks {

Subtensor::<T>::create_account_if_non_existent(&dest, &hot);

// Remove stake limit for benchmark
StakingOperationRateLimiter::<T>::remove((hot.clone(), coldkey.clone(), netuid));

#[extrinsic_call]
_(
RawOrigin::Signed(coldkey.clone()),
Expand Down Expand Up @@ -990,6 +1002,9 @@ mod pallet_benchmarks {
let alpha_to_swap: u64 =
Subtensor::<T>::get_stake_for_hotkey_and_coldkey_on_subnet(&hot, &coldkey, netuid1);

// Remove stake limit for benchmark
StakingOperationRateLimiter::<T>::remove((hot.clone(), coldkey.clone(), netuid1));

#[extrinsic_call]
_(
RawOrigin::Signed(coldkey.clone()),
Expand Down Expand Up @@ -1352,6 +1367,9 @@ mod pallet_benchmarks {
staked_amt
));

// Remove stake limit for benchmark
StakingOperationRateLimiter::<T>::remove((hotkey.clone(), coldkey.clone(), netuid));

#[extrinsic_call]
_(RawOrigin::Signed(coldkey), hotkey);
}
Expand Down
14 changes: 14 additions & 0 deletions pallets/subtensor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1670,6 +1670,20 @@ pub mod pallet {
OptionQuery,
>;

#[pallet::storage]
/// DMAP ( hot, cold, netuid ) --> rate limits for staking operations
/// Value contains just a marker: we use this map as a set.
pub type StakingOperationRateLimiter<T: Config> = StorageNMap<
_,
(
NMapKey<Blake2_128Concat, T::AccountId>, // hot
NMapKey<Blake2_128Concat, T::AccountId>, // cold
NMapKey<Identity, NetUid>, // subnet
),
bool,
ValueQuery,
>;

/// =============================
/// ==== EVM related storage ====
/// =============================
Expand Down
28 changes: 14 additions & 14 deletions pallets/subtensor/src/macros/dispatches.rs
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,7 @@ mod dispatches {
/// - Attempting to set weights with max value exceeding limit.
///
#[pallet::call_index(8)]
#[pallet::weight((Weight::from_parts(4_068_000, 0)
#[pallet::weight((Weight::from_parts(3_266_000, 0)
.saturating_add(T::DbWeight::get().reads(0))
.saturating_add(T::DbWeight::get().writes(0)), DispatchClass::Normal, Pays::No))]
pub fn set_tao_weights(
Expand Down Expand Up @@ -587,7 +587,7 @@ mod dispatches {
#[pallet::call_index(2)]
#[pallet::weight((Weight::from_parts(345_500_000, 0)
.saturating_add(T::DbWeight::get().reads(26))
.saturating_add(T::DbWeight::get().writes(14)), DispatchClass::Normal, Pays::No))]
.saturating_add(T::DbWeight::get().writes(15)), DispatchClass::Normal, Pays::No))]
pub fn add_stake(
origin: OriginFor<T>,
hotkey: T::AccountId,
Expand Down Expand Up @@ -1465,7 +1465,7 @@ mod dispatches {
/// - The ip type v4 or v6.
///
#[pallet::call_index(68)]
#[pallet::weight((Weight::from_parts(38_980_000, 0)
#[pallet::weight((Weight::from_parts(31_780_000, 0)
.saturating_add(T::DbWeight::get().reads(3))
.saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Normal, Pays::Yes))]
pub fn set_identity(
Expand Down Expand Up @@ -1575,7 +1575,7 @@ mod dispatches {
/// * `TxRateLimitExceeded`:
/// - Thrown if key has hit transaction rate limit
#[pallet::call_index(83)]
#[pallet::weight((Weight::from_parts(36_200_000, 0)
#[pallet::weight((Weight::from_parts(30_190_000, 0)
.saturating_add(T::DbWeight::get().reads(6))
.saturating_add(T::DbWeight::get().writes(0)), DispatchClass::Operational, Pays::No))]
pub fn unstake_all(origin: OriginFor<T>, hotkey: T::AccountId) -> DispatchResult {
Expand Down Expand Up @@ -1609,7 +1609,7 @@ mod dispatches {
/// - Thrown if key has hit transaction rate limit
#[pallet::call_index(84)]
#[pallet::weight((Weight::from_parts(369_500_000, 0)
.saturating_add(T::DbWeight::get().reads(32))
.saturating_add(T::DbWeight::get().reads(33))
.saturating_add(T::DbWeight::get().writes(16)), DispatchClass::Operational, Pays::No))]
pub fn unstake_all_alpha(origin: OriginFor<T>, hotkey: T::AccountId) -> DispatchResult {
Self::do_unstake_all_alpha(origin, hotkey)
Expand Down Expand Up @@ -1638,8 +1638,8 @@ mod dispatches {
///
#[pallet::call_index(85)]
#[pallet::weight((Weight::from_parts(419_500_000, 0)
.saturating_add(T::DbWeight::get().reads(31))
.saturating_add(T::DbWeight::get().writes(19)), DispatchClass::Operational, Pays::No))]
.saturating_add(T::DbWeight::get().reads(32))
.saturating_add(T::DbWeight::get().writes(20)), DispatchClass::Operational, Pays::No))]
pub fn move_stake(
origin: T::RuntimeOrigin,
origin_hotkey: T::AccountId,
Expand Down Expand Up @@ -1681,7 +1681,7 @@ mod dispatches {
/// May emit a `StakeTransferred` event on success.
#[pallet::call_index(86)]
#[pallet::weight((Weight::from_parts(432_600_000, 0)
.saturating_add(T::DbWeight::get().reads(30))
.saturating_add(T::DbWeight::get().reads(31))
.saturating_add(T::DbWeight::get().writes(19)), DispatchClass::Operational, Pays::No))]
pub fn transfer_stake(
origin: T::RuntimeOrigin,
Expand Down Expand Up @@ -1723,8 +1723,8 @@ mod dispatches {
#[pallet::call_index(87)]
#[pallet::weight((
Weight::from_parts(351_300_000, 0)
.saturating_add(T::DbWeight::get().reads(31))
.saturating_add(T::DbWeight::get().writes(16)),
.saturating_add(T::DbWeight::get().reads(32))
.saturating_add(T::DbWeight::get().writes(17)),
DispatchClass::Operational,
Pays::No
))]
Expand Down Expand Up @@ -1789,7 +1789,7 @@ mod dispatches {
#[pallet::call_index(88)]
#[pallet::weight((Weight::from_parts(402_800_000, 0)
.saturating_add(T::DbWeight::get().reads(26))
.saturating_add(T::DbWeight::get().writes(14)), DispatchClass::Normal, Pays::No))]
.saturating_add(T::DbWeight::get().writes(15)), DispatchClass::Normal, Pays::No))]
pub fn add_stake_limit(
origin: OriginFor<T>,
hotkey: T::AccountId,
Expand Down Expand Up @@ -1852,7 +1852,7 @@ mod dispatches {
///
#[pallet::call_index(89)]
#[pallet::weight((Weight::from_parts(403_800_000, 0)
.saturating_add(T::DbWeight::get().reads(29))
.saturating_add(T::DbWeight::get().reads(30))
.saturating_add(T::DbWeight::get().writes(14)), DispatchClass::Normal, Pays::No))]
pub fn remove_stake_limit(
origin: OriginFor<T>,
Expand Down Expand Up @@ -1896,8 +1896,8 @@ mod dispatches {
#[pallet::call_index(90)]
#[pallet::weight((
Weight::from_parts(426_500_000, 0)
.saturating_add(T::DbWeight::get().reads(31))
.saturating_add(T::DbWeight::get().writes(16)),
.saturating_add(T::DbWeight::get().reads(32))
.saturating_add(T::DbWeight::get().writes(17)),
DispatchClass::Operational,
Pays::No
))]
Expand Down
2 changes: 2 additions & 0 deletions pallets/subtensor/src/macros/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -218,5 +218,7 @@ mod errors {
SameNetuid,
/// The caller does not have enough balance for the operation.
InsufficientBalance,
/// Too frequent staking operations
StakingOperationRateLimitExceeded,
}
}
4 changes: 3 additions & 1 deletion pallets/subtensor/src/macros/hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,9 @@ mod hooks {
// * 'n': (BlockNumberFor<T>):
// - The number of the block we are finalizing.
fn on_finalize(_block_number: BlockNumberFor<T>) {
// Self::do_on_finalize(block_number);
for _ in StakingOperationRateLimiter::<T>::drain() {
// Clear all entries each block
}
}

fn on_runtime_upgrade() -> frame_support::weights::Weight {
Expand Down
3 changes: 2 additions & 1 deletion pallets/subtensor/src/staking/add_stake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ impl<T: Config> Pallet<T> {
netuid,
tao_staked.saturating_to_num::<u64>(),
T::SwapInterface::max_price(),
true,
)?;

// Ok and return.
Expand Down Expand Up @@ -168,7 +169,7 @@ impl<T: Config> Pallet<T> {

// 6. Swap the stake into alpha on the subnet and increase counters.
// Emit the staking event.
Self::stake_into_subnet(&hotkey, &coldkey, netuid, tao_staked, limit_price)?;
Self::stake_into_subnet(&hotkey, &coldkey, netuid, tao_staked, limit_price, true)?;

// Ok and return.
Ok(())
Expand Down
6 changes: 6 additions & 0 deletions pallets/subtensor/src/staking/move_stake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ impl<T: Config> Pallet<T> {
None,
None,
false,
true,
)?;

// Log the event.
Expand Down Expand Up @@ -144,6 +145,7 @@ impl<T: Config> Pallet<T> {
None,
None,
true,
false,
)?;

// 9. Emit an event for logging/monitoring.
Expand Down Expand Up @@ -214,6 +216,7 @@ impl<T: Config> Pallet<T> {
None,
None,
false,
true,
)?;

// Emit an event for logging.
Expand Down Expand Up @@ -286,6 +289,7 @@ impl<T: Config> Pallet<T> {
Some(limit_price),
Some(allow_partial),
false,
true,
)?;

// Emit an event for logging.
Expand Down Expand Up @@ -322,6 +326,7 @@ impl<T: Config> Pallet<T> {
maybe_limit_price: Option<u64>,
maybe_allow_partial: Option<bool>,
check_transfer_toggle: bool,
set_limit: bool,
) -> Result<u64, DispatchError> {
// Calculate the maximum amount that can be executed
let max_amount = if let Some(limit_price) = maybe_limit_price {
Expand Down Expand Up @@ -374,6 +379,7 @@ impl<T: Config> Pallet<T> {
destination_netuid,
tao_unstaked,
T::SwapInterface::max_price(),
set_limit,
)?;
}

Expand Down
1 change: 1 addition & 0 deletions pallets/subtensor/src/staking/remove_stake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,7 @@ impl<T: Config> Pallet<T> {
NetUid::ROOT,
total_tao_unstaked,
T::SwapInterface::max_price(),
false, // no limit for Root subnet
)?;

// 5. Done and ok.
Expand Down
34 changes: 34 additions & 0 deletions pallets/subtensor/src/staking/stake_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -793,6 +793,7 @@ impl<T: Config> Pallet<T> {
netuid: NetUid,
tao: u64,
price_limit: u64,
set_limit: bool,
) -> Result<u64, DispatchError> {
// Swap the tao to alpha.
let swap_result = Self::swap_tao_for_alpha(netuid, tao, price_limit)?;
Expand Down Expand Up @@ -829,6 +830,10 @@ impl<T: Config> Pallet<T> {

LastColdkeyHotkeyStakeBlock::<T>::insert(coldkey, hotkey, Self::get_current_block_as_u64());

if set_limit {
Self::set_stake_operation_limit(hotkey, coldkey, netuid.into());
}

// Deposit and log the staking event.
Self::deposit_event(Event::StakeAdded(
coldkey.clone(),
Expand Down Expand Up @@ -941,6 +946,8 @@ impl<T: Config> Pallet<T> {
// Ensure that the subnet exists.
ensure!(Self::if_subnet_exist(netuid), Error::<T>::SubnetNotExists);

Self::ensure_stake_operation_limit_not_exceeded(hotkey, coldkey, netuid.into())?;

// Ensure that the subnet is enabled.
// Self::ensure_subtoken_enabled(netuid)?;

Expand Down Expand Up @@ -1030,6 +1037,12 @@ impl<T: Config> Pallet<T> {
ensure!(origin_netuid != destination_netuid, Error::<T>::SameNetuid);
}

Self::ensure_stake_operation_limit_not_exceeded(
origin_hotkey,
origin_coldkey,
origin_netuid.into(),
)?;

// Ensure that both subnets exist.
ensure!(
Self::if_subnet_exist(origin_netuid),
Expand Down Expand Up @@ -1147,6 +1160,27 @@ impl<T: Config> Pallet<T> {
SubnetAlphaIn::<T>::set(netuid, subnet_alpha.saturating_sub(carry_over));
}
}

pub fn set_stake_operation_limit(
hotkey: &T::AccountId,
coldkey: &T::AccountId,
netuid: NetUid,
) {
StakingOperationRateLimiter::<T>::insert((hotkey, coldkey, netuid), true);
}

pub fn ensure_stake_operation_limit_not_exceeded(
hotkey: &T::AccountId,
coldkey: &T::AccountId,
netuid: NetUid,
) -> Result<(), Error<T>> {
ensure!(
!StakingOperationRateLimiter::<T>::contains_key((hotkey, coldkey, netuid)),
Error::<T>::StakingOperationRateLimitExceeded
);

Ok(())
}
}

///////////////////////////////////////////
Expand Down
1 change: 1 addition & 0 deletions pallets/subtensor/src/tests/children.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2251,6 +2251,7 @@ fn test_do_remove_stake_clears_pending_childkeys() {
assert!(pending_before.1 > 0);

// Remove stake
remove_stake_rate_limit_for_tests(&hotkey, &coldkey, netuid);
assert_ok!(SubtensorModule::do_remove_stake(
RuntimeOrigin::signed(coldkey),
hotkey,
Expand Down
5 changes: 5 additions & 0 deletions pallets/subtensor/src/tests/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -900,6 +900,7 @@ pub fn increase_stake_on_coldkey_hotkey_account(
netuid,
tao_staked,
<Test as Config>::SwapInterface::max_price(),
false,
)
.unwrap();
}
Expand All @@ -919,6 +920,10 @@ pub fn increase_stake_on_hotkey_account(hotkey: &U256, increment: u64, netuid: N
);
}

pub(crate) fn remove_stake_rate_limit_for_tests(hotkey: &U256, coldkey: &U256, netuid: NetUid) {
StakingOperationRateLimiter::<Test>::remove((hotkey, coldkey, netuid));
}

pub(crate) fn setup_reserves(netuid: NetUid, tao: u64, alpha: u64) {
SubnetTAO::<Test>::set(netuid, tao);
SubnetAlphaIn::<Test>::set(netuid, alpha);
Expand Down
Loading
Loading