Skip to content

Commit 6d3ab3a

Browse files
authored
Merge pull request #2011 from opentensor/feat/type-safe-swap
Type safe swap interface
2 parents 47bd6e7 + 7639869 commit 6d3ab3a

File tree

43 files changed

+1897
-1589
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

43 files changed

+1897
-1589
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

common/src/currency.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,9 @@ macro_rules! impl_approx {
227227
};
228228
}
229229

230-
pub trait Currency: ToFixed + Into<u64> + From<u64> + Clone + Copy {
230+
pub trait Currency:
231+
ToFixed + Into<u64> + From<u64> + Clone + Copy + Eq + Ord + PartialEq + PartialOrd + Display
232+
{
231233
const MAX: Self;
232234
const ZERO: Self;
233235

common/src/lib.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -169,8 +169,6 @@ impl Default for ProxyType {
169169
}
170170

171171
pub trait SubnetInfo<AccountId> {
172-
fn tao_reserve(netuid: NetUid) -> TaoCurrency;
173-
fn alpha_reserve(netuid: NetUid) -> AlphaCurrency;
174172
fn exists(netuid: NetUid) -> bool;
175173
fn mechanism(netuid: NetUid) -> u16;
176174
fn is_owner(account_id: &AccountId, netuid: NetUid) -> bool;
@@ -180,6 +178,12 @@ pub trait SubnetInfo<AccountId> {
180178
fn hotkey_of_uid(netuid: NetUid, uid: u16) -> Option<AccountId>;
181179
}
182180

181+
pub trait CurrencyReserve<C: Currency> {
182+
fn reserve(netuid: NetUid) -> C;
183+
fn increase_provided(netuid: NetUid, amount: C);
184+
fn decrease_provided(netuid: NetUid, amount: C);
185+
}
186+
183187
pub trait BalanceOps<AccountId> {
184188
fn tao_balance(account_id: &AccountId) -> TaoCurrency;
185189
fn alpha_balance(netuid: NetUid, coldkey: &AccountId, hotkey: &AccountId) -> AlphaCurrency;
@@ -200,10 +204,6 @@ pub trait BalanceOps<AccountId> {
200204
netuid: NetUid,
201205
alpha: AlphaCurrency,
202206
) -> Result<AlphaCurrency, DispatchError>;
203-
fn increase_provided_tao_reserve(netuid: NetUid, tao: TaoCurrency);
204-
fn decrease_provided_tao_reserve(netuid: NetUid, tao: TaoCurrency);
205-
fn increase_provided_alpha_reserve(netuid: NetUid, alpha: AlphaCurrency);
206-
fn decrease_provided_alpha_reserve(netuid: NetUid, alpha: AlphaCurrency);
207207
}
208208

209209
pub mod time {

pallets/admin-utils/src/tests/mock.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -341,6 +341,8 @@ impl pallet_subtensor_swap::Config for Test {
341341
type SubnetInfo = SubtensorModule;
342342
type BalanceOps = SubtensorModule;
343343
type ProtocolId = SwapProtocolId;
344+
type TaoReserve = pallet_subtensor::TaoCurrencyReserve<Self>;
345+
type AlphaReserve = pallet_subtensor::AlphaCurrencyReserve<Self>;
344346
type MaxFeeRate = SwapMaxFeeRate;
345347
type MaxPositions = SwapMaxPositions;
346348
type MinimumLiquidity = SwapMinimumLiquidity;

pallets/subtensor/src/coinbase/run_coinbase.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ impl<T: Config> Pallet<T> {
9191
let buy_swap_result = Self::swap_tao_for_alpha(
9292
*netuid_i,
9393
tou64!(difference_tao).into(),
94-
T::SwapInterface::max_price().into(),
94+
T::SwapInterface::max_price(),
9595
true,
9696
);
9797
if let Ok(buy_swap_result_ok) = buy_swap_result {
@@ -220,14 +220,14 @@ impl<T: Config> Pallet<T> {
220220
let swap_result = Self::swap_alpha_for_tao(
221221
*netuid_i,
222222
tou64!(root_alpha).into(),
223-
T::SwapInterface::min_price().into(),
223+
T::SwapInterface::min_price(),
224224
true,
225225
);
226226
if let Ok(ok_result) = swap_result {
227-
let root_tao: u64 = ok_result.amount_paid_out;
227+
let root_tao = ok_result.amount_paid_out;
228228
// Accumulate root divs for subnet.
229229
PendingRootDivs::<T>::mutate(*netuid_i, |total| {
230-
*total = total.saturating_add(root_tao.into());
230+
*total = total.saturating_add(root_tao);
231231
});
232232
}
233233
}

pallets/subtensor/src/lib.rs

Lines changed: 37 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ use scale_info::TypeInfo;
2323
use sp_core::Get;
2424
use sp_runtime::{DispatchError, transaction_validity::TransactionValidityError};
2525
use sp_std::marker::PhantomData;
26-
use subtensor_runtime_common::{AlphaCurrency, Currency, NetUid, TaoCurrency};
26+
use subtensor_runtime_common::{AlphaCurrency, Currency, CurrencyReserve, NetUid, TaoCurrency};
2727

2828
// ============================
2929
// ==== Benchmark Imports =====
@@ -2141,17 +2141,48 @@ impl<T, H, P> CollectiveInterface<T, H, P> for () {
21412141
}
21422142
}
21432143

2144-
impl<T: Config + pallet_balances::Config<Balance = u64>>
2145-
subtensor_runtime_common::SubnetInfo<T::AccountId> for Pallet<T>
2146-
{
2147-
fn tao_reserve(netuid: NetUid) -> TaoCurrency {
2144+
#[derive(Clone)]
2145+
pub struct TaoCurrencyReserve<T: Config>(PhantomData<T>);
2146+
2147+
impl<T: Config> CurrencyReserve<TaoCurrency> for TaoCurrencyReserve<T> {
2148+
fn reserve(netuid: NetUid) -> TaoCurrency {
21482149
SubnetTAO::<T>::get(netuid).saturating_add(SubnetTaoProvided::<T>::get(netuid))
21492150
}
21502151

2151-
fn alpha_reserve(netuid: NetUid) -> AlphaCurrency {
2152+
fn increase_provided(netuid: NetUid, tao: TaoCurrency) {
2153+
Pallet::<T>::increase_provided_tao_reserve(netuid, tao);
2154+
}
2155+
2156+
fn decrease_provided(netuid: NetUid, tao: TaoCurrency) {
2157+
Pallet::<T>::decrease_provided_tao_reserve(netuid, tao);
2158+
}
2159+
}
2160+
2161+
#[derive(Clone)]
2162+
pub struct AlphaCurrencyReserve<T: Config>(PhantomData<T>);
2163+
2164+
impl<T: Config> CurrencyReserve<AlphaCurrency> for AlphaCurrencyReserve<T> {
2165+
fn reserve(netuid: NetUid) -> AlphaCurrency {
21522166
SubnetAlphaIn::<T>::get(netuid).saturating_add(SubnetAlphaInProvided::<T>::get(netuid))
21532167
}
21542168

2169+
fn increase_provided(netuid: NetUid, alpha: AlphaCurrency) {
2170+
Pallet::<T>::increase_provided_alpha_reserve(netuid, alpha);
2171+
}
2172+
2173+
fn decrease_provided(netuid: NetUid, alpha: AlphaCurrency) {
2174+
Pallet::<T>::decrease_provided_alpha_reserve(netuid, alpha);
2175+
}
2176+
}
2177+
2178+
pub type GetAlphaForTao<T> =
2179+
subtensor_swap_interface::GetAlphaForTao<TaoCurrencyReserve<T>, AlphaCurrencyReserve<T>>;
2180+
pub type GetTaoForAlpha<T> =
2181+
subtensor_swap_interface::GetTaoForAlpha<AlphaCurrencyReserve<T>, TaoCurrencyReserve<T>>;
2182+
2183+
impl<T: Config + pallet_balances::Config<Balance = u64>>
2184+
subtensor_runtime_common::SubnetInfo<T::AccountId> for Pallet<T>
2185+
{
21552186
fn exists(netuid: NetUid) -> bool {
21562187
Self::if_subnet_exist(netuid)
21572188
}
@@ -2248,22 +2279,6 @@ impl<T: Config + pallet_balances::Config<Balance = u64>>
22482279
hotkey, coldkey, netuid, alpha,
22492280
))
22502281
}
2251-
2252-
fn increase_provided_tao_reserve(netuid: NetUid, tao: TaoCurrency) {
2253-
Self::increase_provided_tao_reserve(netuid, tao);
2254-
}
2255-
2256-
fn decrease_provided_tao_reserve(netuid: NetUid, tao: TaoCurrency) {
2257-
Self::decrease_provided_tao_reserve(netuid, tao);
2258-
}
2259-
2260-
fn increase_provided_alpha_reserve(netuid: NetUid, alpha: AlphaCurrency) {
2261-
Self::increase_provided_alpha_reserve(netuid, alpha);
2262-
}
2263-
2264-
fn decrease_provided_alpha_reserve(netuid: NetUid, alpha: AlphaCurrency) {
2265-
Self::decrease_provided_alpha_reserve(netuid, alpha);
2266-
}
22672282
}
22682283

22692284
/// Enum that defines types of rate limited operations for

pallets/subtensor/src/macros/config.rs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@ use frame_support::pallet_macros::pallet_section;
66
#[pallet_section]
77
mod config {
88

9-
use crate::CommitmentsInterface;
9+
use crate::{CommitmentsInterface, GetAlphaForTao, GetTaoForAlpha};
1010
use pallet_commitments::GetCommitments;
11-
use subtensor_swap_interface::SwapHandler;
11+
use subtensor_swap_interface::{SwapEngine, SwapHandler};
1212

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

54-
/// Swap interface.
55-
type SwapInterface: SwapHandler<Self::AccountId>;
54+
/// Implementor of `SwapHandler` interface from `subtensor_swap_interface`
55+
type SwapInterface: SwapHandler
56+
+ SwapEngine<GetAlphaForTao<Self>>
57+
+ SwapEngine<GetTaoForAlpha<Self>>;
5658

5759
/// Interface to allow interacting with the proxy pallet.
5860
type ProxyInterface: crate::ProxyInterface<Self::AccountId>;

pallets/subtensor/src/macros/dispatches.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -706,7 +706,7 @@ mod dispatches {
706706
///
707707
#[pallet::call_index(2)]
708708
#[pallet::weight((Weight::from_parts(340_800_000, 0)
709-
.saturating_add(T::DbWeight::get().reads(26))
709+
.saturating_add(T::DbWeight::get().reads(24_u64))
710710
.saturating_add(T::DbWeight::get().writes(15)), DispatchClass::Normal, Pays::Yes))]
711711
pub fn add_stake(
712712
origin: OriginFor<T>,
@@ -1671,7 +1671,7 @@ mod dispatches {
16711671
/// - Thrown if key has hit transaction rate limit
16721672
#[pallet::call_index(84)]
16731673
#[pallet::weight((Weight::from_parts(358_500_000, 0)
1674-
.saturating_add(T::DbWeight::get().reads(38_u64))
1674+
.saturating_add(T::DbWeight::get().reads(36_u64))
16751675
.saturating_add(T::DbWeight::get().writes(21_u64)), DispatchClass::Operational, Pays::Yes))]
16761676
pub fn unstake_all_alpha(origin: OriginFor<T>, hotkey: T::AccountId) -> DispatchResult {
16771677
Self::do_unstake_all_alpha(origin, hotkey)
@@ -1785,7 +1785,7 @@ mod dispatches {
17851785
#[pallet::call_index(87)]
17861786
#[pallet::weight((
17871787
Weight::from_parts(351_300_000, 0)
1788-
.saturating_add(T::DbWeight::get().reads(37_u64))
1788+
.saturating_add(T::DbWeight::get().reads(35_u64))
17891789
.saturating_add(T::DbWeight::get().writes(22_u64)),
17901790
DispatchClass::Normal,
17911791
Pays::Yes
@@ -1850,7 +1850,7 @@ mod dispatches {
18501850
///
18511851
#[pallet::call_index(88)]
18521852
#[pallet::weight((Weight::from_parts(402_900_000, 0)
1853-
.saturating_add(T::DbWeight::get().reads(26))
1853+
.saturating_add(T::DbWeight::get().reads(24_u64))
18541854
.saturating_add(T::DbWeight::get().writes(15)), DispatchClass::Normal, Pays::Yes))]
18551855
pub fn add_stake_limit(
18561856
origin: OriginFor<T>,
@@ -1914,7 +1914,7 @@ mod dispatches {
19141914
///
19151915
#[pallet::call_index(89)]
19161916
#[pallet::weight((Weight::from_parts(377_400_000, 0)
1917-
.saturating_add(T::DbWeight::get().reads(30_u64))
1917+
.saturating_add(T::DbWeight::get().reads(28_u64))
19181918
.saturating_add(T::DbWeight::get().writes(14)), DispatchClass::Normal, Pays::Yes))]
19191919
pub fn remove_stake_limit(
19201920
origin: OriginFor<T>,
@@ -1958,7 +1958,7 @@ mod dispatches {
19581958
#[pallet::call_index(90)]
19591959
#[pallet::weight((
19601960
Weight::from_parts(411_500_000, 0)
1961-
.saturating_add(T::DbWeight::get().reads(37_u64))
1961+
.saturating_add(T::DbWeight::get().reads(35_u64))
19621962
.saturating_add(T::DbWeight::get().writes(22_u64)),
19631963
DispatchClass::Normal,
19641964
Pays::Yes
@@ -2136,7 +2136,7 @@ mod dispatches {
21362136
/// Without limit_price it remove all the stake similar to `remove_stake` extrinsic
21372137
#[pallet::call_index(103)]
21382138
#[pallet::weight((Weight::from_parts(395_300_000, 10142)
2139-
.saturating_add(T::DbWeight::get().reads(30_u64))
2139+
.saturating_add(T::DbWeight::get().reads(28_u64))
21402140
.saturating_add(T::DbWeight::get().writes(14_u64)), DispatchClass::Normal, Pays::Yes))]
21412141
pub fn remove_stake_full_limit(
21422142
origin: T::RuntimeOrigin,

pallets/subtensor/src/rpc_info/stake_info.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ impl<T: Config> Pallet<T> {
128128
0_u64
129129
} else {
130130
let netuid = destination.or(origin).map(|v| v.1).unwrap_or_default();
131-
T::SwapInterface::approx_fee_amount(netuid.into(), amount)
131+
T::SwapInterface::approx_fee_amount(netuid.into(), TaoCurrency::from(amount)).to_u64()
132132
}
133133
}
134134
}

pallets/subtensor/src/staking/add_stake.rs

Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use substrate_fixed::types::I96F32;
22
use subtensor_runtime_common::{NetUid, TaoCurrency};
3-
use subtensor_swap_interface::{OrderType, SwapHandler};
3+
use subtensor_swap_interface::{Order, SwapHandler};
44

55
use super::*;
66

@@ -74,7 +74,7 @@ impl<T: Config> Pallet<T> {
7474
&coldkey,
7575
netuid,
7676
tao_staked.saturating_to_num::<u64>().into(),
77-
T::SwapInterface::max_price().into(),
77+
T::SwapInterface::max_price(),
7878
true,
7979
false,
8080
)?;
@@ -180,34 +180,30 @@ impl<T: Config> Pallet<T> {
180180
}
181181

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

195198
// Use reverting swap to estimate max limit amount
196-
let result = T::SwapInterface::swap(
197-
netuid.into(),
198-
OrderType::Buy,
199-
u64::MAX,
200-
limit_price.into(),
201-
false,
202-
true,
203-
)
204-
.map(|r| r.amount_paid_in.saturating_add(r.fee_paid))
205-
.map_err(|_| Error::ZeroMaxStakeAmount)?;
199+
let order = GetAlphaForTao::<T>::with_amount(u64::MAX);
200+
let result = T::SwapInterface::swap(netuid.into(), order, limit_price, false, true)
201+
.map(|r| r.amount_paid_in.saturating_add(r.fee_paid))?;
206202

207-
if result != 0 {
208-
Ok(result)
203+
if !result.is_zero() {
204+
Ok(result.into())
209205
} else {
210-
Err(Error::ZeroMaxStakeAmount)
206+
Err(Error::<T>::ZeroMaxStakeAmount.into())
211207
}
212208
}
213209
}

0 commit comments

Comments
 (0)