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.

2 changes: 2 additions & 0 deletions chain-extensions/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ pallet-subtensor-proxy.workspace = true
pallet-drand.workspace = true
subtensor-swap-interface.workspace = true
num_enum.workspace = true
substrate-fixed.workspace = true

[lints]
workspace = true
Expand Down Expand Up @@ -64,4 +65,5 @@ std = [
"pallet-drand/std",
"subtensor-swap-interface/std",
"num_enum/std",
"substrate-fixed/std",
]
28 changes: 26 additions & 2 deletions chain-extensions/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ use pallet_subtensor_proxy as pallet_proxy;
use pallet_subtensor_proxy::WeightInfo;
use sp_runtime::{DispatchError, Weight, traits::StaticLookup};
use sp_std::marker::PhantomData;
use substrate_fixed::types::U96F32;
use subtensor_runtime_common::{AlphaCurrency, NetUid, ProxyType, TaoCurrency};
use subtensor_swap_interface::SwapHandler;

#[derive(DebugNoBound)]
pub struct SubtensorChainExtension<T>(PhantomData<T>);
Expand All @@ -33,7 +35,8 @@ impl<T> ChainExtension<T> for SubtensorChainExtension<T>
where
T: pallet_subtensor::Config
+ pallet_contracts::Config
+ pallet_proxy::Config<ProxyType = ProxyType>,
+ pallet_proxy::Config<ProxyType = ProxyType>
+ pallet_subtensor_swap::Config,
T::AccountId: Clone,
<<T as SysConfig>::Lookup as StaticLookup>::Source: From<<T as SysConfig>::AccountId>,
{
Expand All @@ -54,7 +57,8 @@ impl<T> SubtensorChainExtension<T>
where
T: pallet_subtensor::Config
+ pallet_contracts::Config
+ pallet_proxy::Config<ProxyType = ProxyType>,
+ pallet_proxy::Config<ProxyType = ProxyType>
+ pallet_subtensor_swap::Config,
T::AccountId: Clone,
{
fn dispatch<Env>(env: &mut Env) -> Result<RetVal, DispatchError>
Expand Down Expand Up @@ -506,6 +510,26 @@ where
}
}
}
FunctionId::GetAlphaPriceV1 => {
let netuid: NetUid = env
.read_as()
.map_err(|_| DispatchError::Other("Failed to decode input parameters"))?;

let current_alpha_price =
<pallet_subtensor_swap::Pallet<T> as SwapHandler>::current_alpha_price(
netuid.into(),
);

let price = current_alpha_price.saturating_mul(U96F32::from_num(1_000_000_000));
let price: u64 = price.saturating_to_num();

let encoded_result = price.encode();

env.write_output(&encoded_result)
.map_err(|_| DispatchError::Other("Failed to write output"))?;

Ok(RetVal::Converging(Output::Success as u32))
}
}
}
}
Expand Down
41 changes: 40 additions & 1 deletion chain-extensions/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@

use super::{SubtensorChainExtension, SubtensorExtensionEnv, mock};
use crate::types::{FunctionId, Output};
use codec::Encode;
use codec::{Decode, Encode};
use frame_support::{assert_ok, weights::Weight};
use frame_system::RawOrigin;
use pallet_contracts::chain_extension::RetVal;
use pallet_subtensor::DefaultMinStake;
use sp_core::Get;
use sp_core::U256;
use sp_runtime::DispatchError;
use substrate_fixed::types::U96F32;
use subtensor_runtime_common::{AlphaCurrency, Currency as CurrencyTrait, NetUid, TaoCurrency};
use subtensor_swap_interface::SwapHandler;

Expand Down Expand Up @@ -964,3 +965,41 @@ fn unstake_all_success_unstakes_balance() {
assert!(post_balance > pre_balance);
});
}

#[test]
fn get_alpha_price_returns_encoded_price() {
mock::new_test_ext(1).execute_with(|| {
let owner_hotkey = U256::from(8001);
let owner_coldkey = U256::from(8002);
let caller = U256::from(8003);

let netuid = mock::add_dynamic_network(&owner_hotkey, &owner_coldkey);

// Set up reserves to establish a price
let tao_reserve = TaoCurrency::from(150_000_000_000u64);
let alpha_reserve = AlphaCurrency::from(100_000_000_000u64);
mock::setup_reserves(netuid, tao_reserve, alpha_reserve);

// Get expected price from swap handler
let expected_price =
<pallet_subtensor_swap::Pallet<mock::Test> as SwapHandler>::current_alpha_price(
netuid.into(),
);
let expected_price_scaled = expected_price.saturating_mul(U96F32::from_num(1_000_000_000));
let expected_price_u64: u64 = expected_price_scaled.saturating_to_num();

let mut env = MockEnv::new(FunctionId::GetAlphaPriceV1, caller, netuid.encode());

let ret = SubtensorChainExtension::<mock::Test>::dispatch(&mut env).unwrap();
assert_success(ret);
assert!(env.charged_weight().is_none());

// Decode the output
let output_price: u64 = Decode::decode(&mut &env.output()[..]).unwrap();

assert_eq!(
output_price, expected_price_u64,
"Price should match expected value"
);
});
}
1 change: 1 addition & 0 deletions chain-extensions/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ pub enum FunctionId {
SetColdkeyAutoStakeHotkeyV1 = 12,
AddProxyV1 = 13,
RemoveProxyV1 = 14,
GetAlphaPriceV1 = 15,
}

#[derive(PartialEq, Eq, Copy, Clone, Encode, Decode, Debug)]
Expand Down
12 changes: 12 additions & 0 deletions contract-tests/bittensor/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ pub enum FunctionId {
SetColdkeyAutoStakeHotkeyV1 = 12,
AddProxyV1 = 13,
RemoveProxyV1 = 14,
GetAlphaPriceV1 = 15,
}

#[ink::chain_extension(extension = 0x1000)]
Expand Down Expand Up @@ -127,6 +128,9 @@ pub trait RuntimeReadWrite {

#[ink(function = 14)]
fn remove_proxy(delegate: <CustomEnvironment as ink::env::Environment>::AccountId);

#[ink(function = 15)]
fn get_alpha_price(netuid: NetUid) -> u64;
}

#[ink::scale_derive(Encode, Decode, TypeInfo)]
Expand Down Expand Up @@ -412,5 +416,13 @@ mod bittensor {
.remove_proxy(delegate.into())
.map_err(|_e| ReadWriteErrorCode::WriteFailed)
}

#[ink(message)]
pub fn get_alpha_price(&self, netuid: u16) -> Result<u64, ReadWriteErrorCode> {
self.env()
.extension()
.get_alpha_price(netuid.into())
.map_err(|_e| ReadWriteErrorCode::ReadFailed)
}
}
}
20 changes: 11 additions & 9 deletions contract-tests/run-ci.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,16 @@

echo "start run-ci.sh"

cd contract-tests

cd bittensor

rustup component add rust-src
cargo install cargo-contract
cargo contract build --release

cd ../..

scripts/localnet.sh &>/dev/null &

i=1
Expand All @@ -15,7 +25,7 @@ while [ $i -le 2000 ]; do
done

# port not available exit with error
if [ "$i" -eq 1000 ]; then
if [ "$i" -eq 2000 ]; then
exit 1
fi

Expand All @@ -28,14 +38,6 @@ fi

cd contract-tests

cd bittensor

rustup component add rust-src
cargo install cargo-contract
cargo contract build --release

cd ..

# required for papi in get-metadata.sh, but we cannot run yarn before papi as it adds the descriptors to the package.json which won't resolve
npm i -g polkadot-api

Expand Down
21 changes: 21 additions & 0 deletions contract-tests/test/wasm.contract.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -563,4 +563,25 @@ describe("Test wasm contract", () => {
assert.ok(proxiesAfterRemove !== undefined)
assert.ok(proxiesAfterRemove[0].length === 0)
})

it("Can get alpha price", async () => {
const message = inkClient.message("get_alpha_price")
const data = message.encode({
netuid: netuid,
})

const response = await api.apis.ContractsApi.call(
convertPublicKeyToSs58(hotkey.publicKey),
contractAddress,
BigInt(0),
undefined,
undefined,
Binary.fromBytes(data.asBytes()),
)

assert.ok(response.result.success)
const result = message.decode(response.result.value).value.value

assert.ok(result !== undefined)
})
});
2 changes: 1 addition & 1 deletion runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion {
// `spec_version`, and `authoring_version` are the same between Wasm and native.
// This value is set to 100 to notify Polkadot-JS App (https://polkadot.js.org/apps) to use
// the compatible custom types.
spec_version: 362,
spec_version: 363,
impl_version: 1,
apis: RUNTIME_API_VERSIONS,
transaction_version: 1,
Expand Down
Loading