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
27 changes: 27 additions & 0 deletions Cargo.lock

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

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ pallet-commitments = { default-features = false, path = "pallets/commitments" }
pallet-registry = { default-features = false, path = "pallets/registry" }
pallet-subtensor = { default-features = false, path = "pallets/subtensor" }
pallet-subtensor-swap = { default-features = false, path = "pallets/swap" }
pallet-subtensor-swap-runtime-api = { default-features = false, path = "pallets/swap/runtime-api" }
pallet-subtensor-swap-rpc = { default-features = false, path = "pallets/swap/rpc" }
safe-math = { default-features = false, path = "primitives/safe-math" }
subtensor-custom-rpc = { default-features = false, path = "pallets/subtensor/rpc" }
subtensor-custom-rpc-runtime-api = { default-features = false, path = "pallets/subtensor/runtime-api" }
Expand Down
2 changes: 2 additions & 0 deletions node/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,8 @@ node-subtensor-runtime = { workspace = true, features = ["std"] }
subtensor-runtime-common = { workspace = true, features = ["std"] }
subtensor-custom-rpc = { workspace = true, features = ["std"] }
subtensor-custom-rpc-runtime-api = { workspace = true, features = ["std"] }
pallet-subtensor-swap-rpc = { workspace = true, features = ["std"] }
pallet-subtensor-swap-runtime-api = { workspace = true, features = ["std"] }

[build-dependencies]
substrate-build-script-utils = { workspace = true }
Expand Down
4 changes: 4 additions & 0 deletions node/src/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ where
CIDP: CreateInherentDataProviders<Block, ()> + Send + Clone + 'static,
CT: fp_rpc::ConvertTransaction<<Block as BlockT>::Extrinsic> + Send + Sync + Clone + 'static,
{
use pallet_subtensor_swap_rpc::{Swap, SwapRpcApiServer};
use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer};
use sc_consensus_manual_seal::rpc::{ManualSeal, ManualSealApiServer};
use substrate_frame_rpc_system::{System, SystemApiServer};
Expand All @@ -127,6 +128,9 @@ where
// Custom RPC methods for Paratensor
module.merge(SubtensorCustom::new(client.clone()).into_rpc())?;

// Swap RPC
module.merge(Swap::new(client.clone()).into_rpc())?;

module.merge(System::new(client.clone(), pool.clone()).into_rpc())?;
module.merge(TransactionPayment::new(client).into_rpc())?;

Expand Down
4 changes: 3 additions & 1 deletion pallets/admin-utils/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ std = [
"pallet-evm-chain-id/std",
"pallet-grandpa/std",
"pallet-scheduler/std",
"pallet-subtensor-swap/std",
"pallet-subtensor/std",
"scale-info/std",
"sp-consensus-aura/std",
Expand All @@ -69,7 +70,7 @@ std = [
"sp-tracing/std",
"sp-weights/std",
"substrate-fixed/std",
"pallet-subtensor-swap/std",
"subtensor-swap-interface/std",
]
runtime-benchmarks = [
"frame-benchmarking/runtime-benchmarks",
Expand All @@ -80,6 +81,7 @@ runtime-benchmarks = [
"pallet-grandpa/runtime-benchmarks",
"pallet-scheduler/runtime-benchmarks",
"pallet-subtensor/runtime-benchmarks",
"pallet-subtensor-swap/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
]
try-runtime = [
Expand Down
2 changes: 1 addition & 1 deletion pallets/admin-utils/src/tests/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ parameter_types! {
impl pallet_subtensor_swap::Config for Test {
type RuntimeEvent = RuntimeEvent;
type AdminOrigin = EnsureRoot<AccountId>;
type LiquidityDataProvider = SubtensorModule;
type SubnetInfo = SubtensorModule;
type BalanceOps = SubtensorModule;
type ProtocolId = SwapProtocolId;
type MaxFeeRate = SwapMaxFeeRate;
Expand Down
18 changes: 9 additions & 9 deletions pallets/subtensor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2422,7 +2422,7 @@ impl<T, H, P> CollectiveInterface<T, H, P> for () {
}

impl<T: Config + pallet_balances::Config<Balance = u64>>
subtensor_swap_interface::LiquidityDataProvider<T::AccountId> for Pallet<T>
subtensor_swap_interface::SubnetInfo<T::AccountId> for Pallet<T>
{
fn tao_reserve(netuid: u16) -> u64 {
SubnetTAO::<T>::get(netuid)
Expand All @@ -2432,11 +2432,11 @@ impl<T: Config + pallet_balances::Config<Balance = u64>>
SubnetAlphaIn::<T>::get(netuid)
}

fn subnet_exist(netuid: u16) -> bool {
fn exists(netuid: u16) -> bool {
Self::if_subnet_exist(netuid)
}

fn subnet_mechanism(netuid: u16) -> u16 {
fn mechanism(netuid: u16) -> u16 {
SubnetMechanism::<T>::get(netuid)
}
}
Expand All @@ -2453,11 +2453,11 @@ impl<T: Config + pallet_balances::Config<Balance = u64>>
}

fn increase_balance(coldkey: &T::AccountId, tao: u64) {
Self::add_balance_to_coldkey_account(&coldkey, tao)
Self::add_balance_to_coldkey_account(coldkey, tao)
}

fn decrease_balance(coldkey: &T::AccountId, tao: u64) -> Result<u64, DispatchError> {
Self::remove_balance_from_coldkey_account(&coldkey, tao)
Self::remove_balance_from_coldkey_account(coldkey, tao)
}

fn increase_stake(
Expand All @@ -2467,11 +2467,11 @@ impl<T: Config + pallet_balances::Config<Balance = u64>>
alpha: u64,
) -> Result<(), DispatchError> {
ensure!(
Self::hotkey_account_exists(&hotkey),
Self::hotkey_account_exists(hotkey),
Error::<T>::HotKeyAccountNotExists
);

Self::increase_stake_for_hotkey_and_coldkey_on_subnet(&hotkey, &coldkey, netuid, alpha);
Self::increase_stake_for_hotkey_and_coldkey_on_subnet(hotkey, coldkey, netuid, alpha);

Ok(())
}
Expand All @@ -2483,12 +2483,12 @@ impl<T: Config + pallet_balances::Config<Balance = u64>>
alpha: u64,
) -> Result<u64, DispatchError> {
ensure!(
Self::hotkey_account_exists(&hotkey),
Self::hotkey_account_exists(hotkey),
Error::<T>::HotKeyAccountNotExists
);

Ok(Self::decrease_stake_for_hotkey_and_coldkey_on_subnet(
&hotkey, &coldkey, netuid, alpha,
hotkey, coldkey, netuid, alpha,
))
}
}
12 changes: 6 additions & 6 deletions pallets/subtensor/src/staking/helpers.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
use super::*;
use safe_math::*;
use substrate_fixed::types::U96F32;
use subtensor_swap_interface::SwapHandler;

use frame_support::traits::{
Imbalance,
tokens::{
Fortitude, Precision, Preservation,
fungible::{Balanced as _, Inspect as _},
},
};
use safe_math::*;
use substrate_fixed::types::U96F32;
use subtensor_swap_interface::{OrderType, SwapHandler};

use super::*;

impl<T: Config> Pallet<T> {
// Returns true if the passed hotkey allow delegative staking.
Expand Down Expand Up @@ -70,7 +70,7 @@ impl<T: Config> Pallet<T> {
let alpha_stake = Self::get_stake_for_hotkey_and_coldkey_on_subnet(
hotkey, coldkey, netuid,
);
Self::sim_swap_alpha_for_tao(netuid, alpha_stake)
T::SwapInterface::sim_swap(netuid, OrderType::Sell, alpha_stake)
.map(|r| {
let fee: u64 = U96F32::saturating_from_num(r.fee_paid)
.saturating_mul(T::SwapInterface::current_alpha_price(netuid))
Expand Down
73 changes: 7 additions & 66 deletions pallets/subtensor/src/staking/stake_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -596,66 +596,6 @@ impl<T: Config> Pallet<T> {
actual_alpha.neg().max(0).unsigned_abs()
}

/// Calculates Some(Alpha) returned from pool by staking operation
/// if liquidity allows that. If not, returns None.
///
/// If new alpha_reserve is about to drop below DefaultMinimumPoolLiquidity,
/// then don't do it.
///
pub fn sim_swap_tao_for_alpha(netuid: u16, tao: u64) -> Result<SwapResult, DispatchError> {
// Step 1: Get the mechanism type for the subnet (0 for Stable, 1 for Dynamic)
let mechanism_id: u16 = SubnetMechanism::<T>::get(netuid);
// Step 2: Simulate swapping tao and attain alpha
if mechanism_id == 1 {
T::SwapInterface::swap(
netuid,
OrderType::Buy,
tao,
T::SwapInterface::max_price(),
true,
)
} else {
// Step 3.b.1: Stable mechanism, just return the value 1:1
Ok(SwapResult {
amount_paid_in: tao,
amount_paid_out: tao,
fee_paid: 0,
new_tao_reserve: 0,
new_alpha_reserve: 0,
})
}
}

/// Calculates Some(Tao) returned from pool by unstaking operation
/// if liquidity allows that. If not, returns None.
///
/// If new tao_reserve is about to drop below DefaultMinimumPoolLiquidity,
/// then don't do it.
///
pub fn sim_swap_alpha_for_tao(netuid: u16, alpha: u64) -> Result<SwapResult, DispatchError> {
// Step 1: Get the mechanism type for the subnet (0 for Stable, 1 for Dynamic)
let mechanism_id: u16 = SubnetMechanism::<T>::get(netuid);
// Step 2: Simulate swapping alpha and attain tao
if mechanism_id == 1 {
T::SwapInterface::swap(
netuid,
OrderType::Sell,
alpha,
T::SwapInterface::min_price(),
true,
)
} else {
// Step 3.b.1: Stable mechanism, just return the value 1:1
Ok(SwapResult {
amount_paid_in: alpha,
amount_paid_out: alpha,
fee_paid: 0,
new_tao_reserve: 0,
new_alpha_reserve: 0,
})
}
}

/// Swaps TAO for the alpha token on the subnet.
///
/// Updates TaoIn, AlphaIn, and AlphaOut
Expand Down Expand Up @@ -900,7 +840,7 @@ impl<T: Config> Pallet<T> {
// Get the minimum balance (and amount) that satisfies the transaction
let min_amount = {
let min_stake = DefaultMinStake::<T>::get();
let fee = Self::sim_swap_tao_for_alpha(netuid, min_stake)
let fee = T::SwapInterface::sim_swap(netuid, OrderType::Buy, min_stake)
.map(|res| res.fee_paid)
.unwrap_or(T::SwapInterface::approx_fee_amount(netuid, min_stake));
min_stake.saturating_add(fee)
Expand All @@ -927,7 +867,7 @@ impl<T: Config> Pallet<T> {
Error::<T>::HotKeyAccountNotExists
);

let expected_alpha = Self::sim_swap_tao_for_alpha(netuid, stake_to_be_added)
let expected_alpha = T::SwapInterface::sim_swap(netuid, OrderType::Buy, stake_to_be_added)
.map_err(|_| Error::<T>::InsufficientLiquidity)?;

ensure!(
Expand Down Expand Up @@ -960,7 +900,7 @@ impl<T: Config> Pallet<T> {
ensure!(Self::if_subnet_exist(netuid), Error::<T>::SubnetNotExists);

// Ensure that the stake amount to be removed is above the minimum in tao equivalent.
match Self::sim_swap_alpha_for_tao(netuid, alpha_unstaked) {
match T::SwapInterface::sim_swap(netuid, OrderType::Sell, alpha_unstaked) {
Ok(res) => ensure!(
res.amount_paid_out > DefaultMinStake::<T>::get(),
Error::<T>::AmountTooLow
Expand Down Expand Up @@ -1040,9 +980,10 @@ impl<T: Config> Pallet<T> {
);

// Ensure that the stake amount to be removed is above the minimum in tao equivalent.
let tao_equivalent = Self::sim_swap_alpha_for_tao(origin_netuid, alpha_amount)
.map(|res| res.amount_paid_out)
.map_err(|_| Error::<T>::InsufficientLiquidity)?;
let tao_equivalent =
T::SwapInterface::sim_swap(origin_netuid, OrderType::Sell, alpha_amount)
.map(|res| res.amount_paid_out)
.map_err(|_| Error::<T>::InsufficientLiquidity)?;
ensure!(
tao_equivalent > DefaultMinStake::<T>::get(),
Error::<T>::AmountTooLow
Expand Down
2 changes: 1 addition & 1 deletion pallets/subtensor/src/tests/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -431,7 +431,7 @@ parameter_types! {
impl pallet_subtensor_swap::Config for Test {
type RuntimeEvent = RuntimeEvent;
type AdminOrigin = EnsureRoot<AccountId>;
type LiquidityDataProvider = SubtensorModule;
type SubnetInfo = SubtensorModule;
type BalanceOps = SubtensorModule;
type ProtocolId = SwapProtocolId;
type MaxFeeRate = SwapMaxFeeRate;
Expand Down
2 changes: 2 additions & 0 deletions pallets/subtensor/src/tests/move_stake.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![allow(clippy::unwrap_used)]

use approx::assert_abs_diff_eq;
use frame_support::{assert_err, assert_noop, assert_ok};
use sp_core::{Get, U256};
Expand Down
2 changes: 1 addition & 1 deletion pallets/subtensor/src/tests/staking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2762,7 +2762,7 @@ fn test_unstake_low_liquidity_validate() {
let subnet_owner_hotkey = U256::from(1002);
let hotkey = U256::from(2);
let coldkey = U256::from(3);
let amount_staked = DefaultMinStake::<Test>::get() * 10 + 0; // FIXME: DefaultStakingFee is deprecated
let amount_staked = DefaultMinStake::<Test>::get() * 10; // FIXME: DefaultStakingFee is deprecated

let netuid = add_dynamic_network(&subnet_owner_hotkey, &subnet_owner_coldkey);
SubtensorModule::create_account_if_non_existent(&coldkey, &hotkey);
Expand Down
2 changes: 2 additions & 0 deletions pallets/subtensor/src/tests/staking2.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![allow(clippy::unwrap_used)]

use frame_support::{
assert_ok,
dispatch::{GetDispatchInfo, Pays},
Expand Down
2 changes: 1 addition & 1 deletion pallets/subtensor/src/tests/swap_coldkey.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use frame_system::{Config, RawOrigin};
use sp_core::{Get, H256, U256};
use sp_runtime::DispatchError;
use substrate_fixed::types::U96F32;
use subtensor_swap_interface::{LiquidityDataProvider, OrderType, SwapHandler};
use subtensor_swap_interface::{OrderType, SubnetInfo, SwapHandler};

use super::mock;
use super::mock::*;
Expand Down
7 changes: 4 additions & 3 deletions pallets/swap-interface/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ pub trait SwapHandler<AccountId> {
price_limit: u64,
should_rollback: bool,
) -> Result<SwapResult, DispatchError>;
fn sim_swap(netuid: u16, order_t: OrderType, amount: u64) -> Result<SwapResult, DispatchError>;
fn approx_fee_amount(netuid: u16, amount: u64) -> u64;
fn current_alpha_price(netuid: u16) -> U96F32;
fn max_price() -> u64;
Expand All @@ -41,11 +42,11 @@ pub struct UpdateLiquidityResult {
pub fee_alpha: u64,
}

pub trait LiquidityDataProvider<AccountId> {
pub trait SubnetInfo<AccountId> {
fn tao_reserve(netuid: u16) -> u64;
fn alpha_reserve(netuid: u16) -> u64;
fn subnet_exist(netuid: u16) -> bool;
fn subnet_mechanism(netuid: u16) -> u16;
fn exists(netuid: u16) -> bool;
fn mechanism(netuid: u16) -> u16;
}

pub trait BalanceOps<AccountId> {
Expand Down
Loading
Loading