Skip to content
Merged
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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion common/src/currency.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,9 @@ macro_rules! impl_approx {
};
}

pub trait Currency: ToFixed + Into<u64> + From<u64> + Clone + Copy {
pub trait Currency:
ToFixed + Into<u64> + From<u64> + Clone + Copy + Eq + Ord + PartialEq + PartialOrd + Display
{
const MAX: Self;
const ZERO: Self;

Expand Down
12 changes: 6 additions & 6 deletions common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,8 +169,6 @@ impl Default for ProxyType {
}

pub trait SubnetInfo<AccountId> {
fn tao_reserve(netuid: NetUid) -> TaoCurrency;
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;
Expand All @@ -180,6 +178,12 @@ pub trait SubnetInfo<AccountId> {
fn hotkey_of_uid(netuid: NetUid, uid: u16) -> Option<AccountId>;
}

pub trait CurrencyReserve<C: Currency> {
fn reserve(netuid: NetUid) -> C;
fn increase_provided(netuid: NetUid, amount: C);
fn decrease_provided(netuid: NetUid, amount: C);
}

pub trait BalanceOps<AccountId> {
fn tao_balance(account_id: &AccountId) -> TaoCurrency;
fn alpha_balance(netuid: NetUid, coldkey: &AccountId, hotkey: &AccountId) -> AlphaCurrency;
Expand All @@ -200,10 +204,6 @@ pub trait BalanceOps<AccountId> {
netuid: NetUid,
alpha: AlphaCurrency,
) -> Result<AlphaCurrency, DispatchError>;
fn increase_provided_tao_reserve(netuid: NetUid, tao: TaoCurrency);
fn decrease_provided_tao_reserve(netuid: NetUid, tao: TaoCurrency);
fn increase_provided_alpha_reserve(netuid: NetUid, alpha: AlphaCurrency);
fn decrease_provided_alpha_reserve(netuid: NetUid, alpha: AlphaCurrency);
}

pub mod time {
Expand Down
2 changes: 2 additions & 0 deletions pallets/admin-utils/src/tests/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,8 @@ impl pallet_subtensor_swap::Config for Test {
type SubnetInfo = SubtensorModule;
type BalanceOps = SubtensorModule;
type ProtocolId = SwapProtocolId;
type TaoReserve = pallet_subtensor::TaoCurrencyReserve<Self>;
type AlphaReserve = pallet_subtensor::AlphaCurrencyReserve<Self>;
type MaxFeeRate = SwapMaxFeeRate;
type MaxPositions = SwapMaxPositions;
type MinimumLiquidity = SwapMinimumLiquidity;
Expand Down
8 changes: 4 additions & 4 deletions pallets/subtensor/src/coinbase/run_coinbase.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ impl<T: Config> Pallet<T> {
let buy_swap_result = Self::swap_tao_for_alpha(
*netuid_i,
tou64!(difference_tao).into(),
T::SwapInterface::max_price().into(),
T::SwapInterface::max_price(),
true,
);
if let Ok(buy_swap_result_ok) = buy_swap_result {
Expand Down Expand Up @@ -220,14 +220,14 @@ impl<T: Config> Pallet<T> {
let swap_result = Self::swap_alpha_for_tao(
*netuid_i,
tou64!(root_alpha).into(),
T::SwapInterface::min_price().into(),
T::SwapInterface::min_price(),
true,
);
if let Ok(ok_result) = swap_result {
let root_tao: u64 = ok_result.amount_paid_out;
let root_tao = ok_result.amount_paid_out;
// Accumulate root divs for subnet.
PendingRootDivs::<T>::mutate(*netuid_i, |total| {
*total = total.saturating_add(root_tao.into());
*total = total.saturating_add(root_tao);
});
}
}
Expand Down
59 changes: 37 additions & 22 deletions pallets/subtensor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use scale_info::TypeInfo;
use sp_core::Get;
use sp_runtime::{DispatchError, transaction_validity::TransactionValidityError};
use sp_std::marker::PhantomData;
use subtensor_runtime_common::{AlphaCurrency, Currency, NetUid, TaoCurrency};
use subtensor_runtime_common::{AlphaCurrency, Currency, CurrencyReserve, NetUid, TaoCurrency};

// ============================
// ==== Benchmark Imports =====
Expand Down Expand Up @@ -2131,17 +2131,48 @@ impl<T, H, P> CollectiveInterface<T, H, P> for () {
}
}

impl<T: Config + pallet_balances::Config<Balance = u64>>
subtensor_runtime_common::SubnetInfo<T::AccountId> for Pallet<T>
{
fn tao_reserve(netuid: NetUid) -> TaoCurrency {
#[derive(Clone)]
pub struct TaoCurrencyReserve<T: Config>(PhantomData<T>);

impl<T: Config> CurrencyReserve<TaoCurrency> for TaoCurrencyReserve<T> {
fn reserve(netuid: NetUid) -> TaoCurrency {
SubnetTAO::<T>::get(netuid).saturating_add(SubnetTaoProvided::<T>::get(netuid))
}

fn alpha_reserve(netuid: NetUid) -> AlphaCurrency {
fn increase_provided(netuid: NetUid, tao: TaoCurrency) {
Pallet::<T>::increase_provided_tao_reserve(netuid, tao);
}

fn decrease_provided(netuid: NetUid, tao: TaoCurrency) {
Pallet::<T>::decrease_provided_tao_reserve(netuid, tao);
}
}

#[derive(Clone)]
pub struct AlphaCurrencyReserve<T: Config>(PhantomData<T>);

impl<T: Config> CurrencyReserve<AlphaCurrency> for AlphaCurrencyReserve<T> {
fn reserve(netuid: NetUid) -> AlphaCurrency {
SubnetAlphaIn::<T>::get(netuid).saturating_add(SubnetAlphaInProvided::<T>::get(netuid))
}

fn increase_provided(netuid: NetUid, alpha: AlphaCurrency) {
Pallet::<T>::increase_provided_alpha_reserve(netuid, alpha);
}

fn decrease_provided(netuid: NetUid, alpha: AlphaCurrency) {
Pallet::<T>::decrease_provided_alpha_reserve(netuid, alpha);
}
}

pub type GetAlphaForTao<T> =
subtensor_swap_interface::GetAlphaForTao<TaoCurrencyReserve<T>, AlphaCurrencyReserve<T>>;
pub type GetTaoForAlpha<T> =
subtensor_swap_interface::GetTaoForAlpha<AlphaCurrencyReserve<T>, TaoCurrencyReserve<T>>;

impl<T: Config + pallet_balances::Config<Balance = u64>>
subtensor_runtime_common::SubnetInfo<T::AccountId> for Pallet<T>
{
fn exists(netuid: NetUid) -> bool {
Self::if_subnet_exist(netuid)
}
Expand Down Expand Up @@ -2238,22 +2269,6 @@ impl<T: Config + pallet_balances::Config<Balance = u64>>
hotkey, coldkey, netuid, alpha,
))
}

fn increase_provided_tao_reserve(netuid: NetUid, tao: TaoCurrency) {
Self::increase_provided_tao_reserve(netuid, tao);
}

fn decrease_provided_tao_reserve(netuid: NetUid, tao: TaoCurrency) {
Self::decrease_provided_tao_reserve(netuid, tao);
}

fn increase_provided_alpha_reserve(netuid: NetUid, alpha: AlphaCurrency) {
Self::increase_provided_alpha_reserve(netuid, alpha);
}

fn decrease_provided_alpha_reserve(netuid: NetUid, alpha: AlphaCurrency) {
Self::decrease_provided_alpha_reserve(netuid, alpha);
}
}

/// Enum that defines types of rate limited operations for
Expand Down
10 changes: 6 additions & 4 deletions pallets/subtensor/src/macros/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ use frame_support::pallet_macros::pallet_section;
#[pallet_section]
mod config {

use crate::CommitmentsInterface;
use crate::{CommitmentsInterface, GetAlphaForTao, GetTaoForAlpha};
use pallet_commitments::GetCommitments;
use subtensor_swap_interface::SwapHandler;
use subtensor_swap_interface::{SwapEngine, SwapHandler};

/// Configure the pallet by specifying the parameters and types on which it depends.
#[pallet::config]
Expand Down Expand Up @@ -51,8 +51,10 @@ mod config {
/// the preimage to store the call data.
type Preimages: QueryPreimage<H = Self::Hashing> + StorePreimage;

/// Swap interface.
type SwapInterface: SwapHandler<Self::AccountId>;
/// Implementor of `SwapHandler` interface from `subtensor_swap_interface`
type SwapInterface: SwapHandler
+ SwapEngine<GetAlphaForTao<Self>>
+ SwapEngine<GetTaoForAlpha<Self>>;

/// Interface to allow interacting with the proxy pallet.
type ProxyInterface: crate::ProxyInterface<Self::AccountId>;
Expand Down
14 changes: 7 additions & 7 deletions pallets/subtensor/src/macros/dispatches.rs
Original file line number Diff line number Diff line change
Expand Up @@ -706,7 +706,7 @@ mod dispatches {
///
#[pallet::call_index(2)]
#[pallet::weight((Weight::from_parts(340_800_000, 0)
.saturating_add(T::DbWeight::get().reads(26))
.saturating_add(T::DbWeight::get().reads(24_u64))
.saturating_add(T::DbWeight::get().writes(15)), DispatchClass::Normal, Pays::Yes))]
pub fn add_stake(
origin: OriginFor<T>,
Expand Down Expand Up @@ -1671,7 +1671,7 @@ mod dispatches {
/// - Thrown if key has hit transaction rate limit
#[pallet::call_index(84)]
#[pallet::weight((Weight::from_parts(358_500_000, 0)
.saturating_add(T::DbWeight::get().reads(38_u64))
.saturating_add(T::DbWeight::get().reads(36_u64))
.saturating_add(T::DbWeight::get().writes(21_u64)), DispatchClass::Operational, Pays::Yes))]
pub fn unstake_all_alpha(origin: OriginFor<T>, hotkey: T::AccountId) -> DispatchResult {
Self::do_unstake_all_alpha(origin, hotkey)
Expand Down Expand Up @@ -1785,7 +1785,7 @@ mod dispatches {
#[pallet::call_index(87)]
#[pallet::weight((
Weight::from_parts(351_300_000, 0)
.saturating_add(T::DbWeight::get().reads(37_u64))
.saturating_add(T::DbWeight::get().reads(35_u64))
.saturating_add(T::DbWeight::get().writes(22_u64)),
DispatchClass::Normal,
Pays::Yes
Expand Down Expand Up @@ -1850,7 +1850,7 @@ mod dispatches {
///
#[pallet::call_index(88)]
#[pallet::weight((Weight::from_parts(402_900_000, 0)
.saturating_add(T::DbWeight::get().reads(26))
.saturating_add(T::DbWeight::get().reads(24_u64))
.saturating_add(T::DbWeight::get().writes(15)), DispatchClass::Normal, Pays::Yes))]
pub fn add_stake_limit(
origin: OriginFor<T>,
Expand Down Expand Up @@ -1914,7 +1914,7 @@ mod dispatches {
///
#[pallet::call_index(89)]
#[pallet::weight((Weight::from_parts(377_400_000, 0)
.saturating_add(T::DbWeight::get().reads(30_u64))
.saturating_add(T::DbWeight::get().reads(28_u64))
.saturating_add(T::DbWeight::get().writes(14)), DispatchClass::Normal, Pays::Yes))]
pub fn remove_stake_limit(
origin: OriginFor<T>,
Expand Down Expand Up @@ -1958,7 +1958,7 @@ mod dispatches {
#[pallet::call_index(90)]
#[pallet::weight((
Weight::from_parts(411_500_000, 0)
.saturating_add(T::DbWeight::get().reads(37_u64))
.saturating_add(T::DbWeight::get().reads(35_u64))
.saturating_add(T::DbWeight::get().writes(22_u64)),
DispatchClass::Normal,
Pays::Yes
Expand Down Expand Up @@ -2136,7 +2136,7 @@ mod dispatches {
/// Without limit_price it remove all the stake similar to `remove_stake` extrinsic
#[pallet::call_index(103)]
#[pallet::weight((Weight::from_parts(395_300_000, 10142)
.saturating_add(T::DbWeight::get().reads(30_u64))
.saturating_add(T::DbWeight::get().reads(28_u64))
.saturating_add(T::DbWeight::get().writes(14_u64)), DispatchClass::Normal, Pays::Yes))]
pub fn remove_stake_full_limit(
origin: T::RuntimeOrigin,
Expand Down
2 changes: 1 addition & 1 deletion pallets/subtensor/src/rpc_info/stake_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ impl<T: Config> Pallet<T> {
0_u64
} else {
let netuid = destination.or(origin).map(|v| v.1).unwrap_or_default();
T::SwapInterface::approx_fee_amount(netuid.into(), amount)
T::SwapInterface::approx_fee_amount(netuid.into(), TaoCurrency::from(amount)).to_u64()
}
}
}
30 changes: 13 additions & 17 deletions pallets/subtensor/src/staking/add_stake.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use substrate_fixed::types::I96F32;
use subtensor_runtime_common::{NetUid, TaoCurrency};
use subtensor_swap_interface::{OrderType, SwapHandler};
use subtensor_swap_interface::{Order, SwapHandler};

use super::*;

Expand Down Expand Up @@ -74,7 +74,7 @@ impl<T: Config> Pallet<T> {
&coldkey,
netuid,
tao_staked.saturating_to_num::<u64>().into(),
T::SwapInterface::max_price().into(),
T::SwapInterface::max_price(),
true,
false,
)?;
Expand Down Expand Up @@ -180,34 +180,30 @@ impl<T: Config> Pallet<T> {
}

// Returns the maximum amount of RAO that can be executed with price limit
pub fn get_max_amount_add(netuid: NetUid, limit_price: TaoCurrency) -> Result<u64, Error<T>> {
pub fn get_max_amount_add(
netuid: NetUid,
limit_price: TaoCurrency,
) -> Result<u64, DispatchError> {
// Corner case: root and stao
// There's no slippage for root or stable subnets, so if limit price is 1e9 rao or
// higher, then max_amount equals u64::MAX, otherwise it is 0.
if netuid.is_root() || SubnetMechanism::<T>::get(netuid) == 0 {
if limit_price >= 1_000_000_000.into() {
return Ok(u64::MAX);
} else {
return Err(Error::ZeroMaxStakeAmount);
return Err(Error::<T>::ZeroMaxStakeAmount.into());
}
}

// Use reverting swap to estimate max limit amount
let result = T::SwapInterface::swap(
netuid.into(),
OrderType::Buy,
u64::MAX,
limit_price.into(),
false,
true,
)
.map(|r| r.amount_paid_in.saturating_add(r.fee_paid))
.map_err(|_| Error::ZeroMaxStakeAmount)?;
let order = GetAlphaForTao::<T>::with_amount(u64::MAX);
let result = T::SwapInterface::swap(netuid.into(), order, limit_price, false, true)
.map(|r| r.amount_paid_in.saturating_add(r.fee_paid))?;

if result != 0 {
Ok(result)
if !result.is_zero() {
Ok(result.into())
} else {
Err(Error::ZeroMaxStakeAmount)
Err(Error::<T>::ZeroMaxStakeAmount.into())
}
}
}
29 changes: 13 additions & 16 deletions pallets/subtensor/src/staking/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use frame_support::traits::{
use safe_math::*;
use substrate_fixed::types::U96F32;
use subtensor_runtime_common::{NetUid, TaoCurrency};
use subtensor_swap_interface::{OrderType, SwapHandler};
use subtensor_swap_interface::{Order, SwapHandler};

use super::*;

Expand Down Expand Up @@ -73,20 +73,17 @@ impl<T: Config> Pallet<T> {
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.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()
let order = GetTaoForAlpha::<T>::with_amount(alpha_stake);
T::SwapInterface::sim_swap(netuid.into(), order)
.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.to_u64().saturating_add(fee)
})
.unwrap_or_default()
})
.sum::<u64>()
})
Expand Down Expand Up @@ -202,7 +199,7 @@ impl<T: Config> Pallet<T> {
coldkey,
netuid,
alpha_stake,
T::SwapInterface::min_price().into(),
T::SwapInterface::min_price(),
false,
);

Expand Down
Loading
Loading