### Example Rust Toolchain Output Source: https://github.com/opentensor/subtensor/blob/main/docs/rust-setup.md An example output from the `rustup show` command, illustrating the default stable toolchain and installed targets, including wasm32v1-none. ```text Default host: x86_64-unknown-linux-gnu rustup home: /home/user/.rustup installed toolchains -------------------- stable-x86_64-unknown-linux-gnu (default) nightly-x86_64-unknown-linux-gnu active toolchain ---------------- name: stable-x86_64-unknown-linux-gnu active because: it's the default toolchain installed targets: x86_64-unknown-linux-gnu wasm32v1-none ``` -------------------------------- ### Install Build Dependencies on OpenSUSE Source: https://github.com/opentensor/subtensor/blob/main/docs/rust-setup.md Run these commands in a terminal to install the required development tools and libraries on OpenSUSE. ```bash sudo zypper install clang curl git openssl-devel llvm-devel libudev-devel ``` -------------------------------- ### Setup and Run Local Subtensor Node with Docker Compose Source: https://context7.com/opentensor/subtensor/llms.txt Clones the Subtensor repository, builds the Docker images, and starts the local network in detached mode. This setup is for local development and testing purposes. ```bash # Clone the repository git clone https://github.com/opentensor/subtensor.git cd subtensor # Build and run localnet docker compose -f docker-compose.localnet.yml build docker compose -f docker-compose.localnet.yml up -d ``` -------------------------------- ### Install Homebrew and Dependencies on macOS Source: https://github.com/opentensor/subtensor/blob/main/docs/rust-setup.md Installs Homebrew if not present, then updates it and installs protobuf, openssl, and a specific LLVM version. Ensure Rosetta 2 is installed for Apple M1 systems. ```bash # Install Homebrew if necessary https://brew.sh/ /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" # Make sure Homebrew is up-to-date, install protobuf and openssl brew update brew install protobuf openssl llvm@16 ``` -------------------------------- ### Install and Configure Rust Toolchain Source: https://github.com/opentensor/subtensor/blob/main/docs/rust-setup.md Installs Rust using rustup and configures the default toolchain to the latest stable version, also adding the WebAssembly target. ```bash # Install curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh # Configure source ~/.cargo/env ``` ```bash rustup default stable rustup update rustup target add wasm32v1-none ``` -------------------------------- ### Check Rust Toolchain Configuration Source: https://github.com/opentensor/subtensor/blob/main/docs/rust-setup.md Displays the currently active Rust toolchain, installed toolchains, and targets. Useful for verifying the setup after installation. ```bash rustup show ``` -------------------------------- ### Staking Example Contract Source: https://context7.com/opentensor/subtensor/llms.txt Demonstrates how to use the IStaking interface to stake TAO to a hotkey and check stake amounts. ```solidity // Usage example contract StakingExample { IStaking constant STAKING = IStaking(0x0000000000000000000000000000000000000805); function stakeToHotkey(bytes32 hotkey, uint256 netuid) external payable { // Stake the sent TAO to the hotkey STAKING.addStake{value: 0}(hotkey, msg.value / 1e9, netuid); // Convert to RAO } function checkMyStake(bytes32 hotkey, bytes32 myColdkey, uint256 netuid) external view returns (uint256) { return STAKING.getStake(hotkey, myColdkey, netuid); } } ``` -------------------------------- ### Set up Python Virtual Environment Source: https://github.com/opentensor/subtensor/blob/main/docs/consensus.md Creates and activates a Python virtual environment for managing project dependencies. Installs NumPy, Matplotlib, and JupyterLab. ```bash python3 -m venv .venv source .venv/bin/activate pip install numpy matplotlib jupyterlab ``` -------------------------------- ### Start Single Node Development Chain Source: https://github.com/opentensor/subtensor/blob/main/README.md Run this command to compile your code and start a local development network. You can append custom commands to this script. ```bash ./scripts/docker_run.sh ``` -------------------------------- ### Install Build Dependencies on Fedora Source: https://github.com/opentensor/subtensor/blob/main/docs/rust-setup.md Execute these commands in a terminal to update the system and install necessary development packages on Fedora. ```bash sudo dnf update sudo dnf install clang curl git openssl-devel ``` -------------------------------- ### Announce and Execute Coldkey Swap (Rust) Source: https://context7.com/opentensor/subtensor/llms.txt Rust examples for the coldkey swap process. Step 1 announces the swap by committing a hash of the new coldkey. Step 2 executes the swap after the delay period, requiring the new coldkey account. ```rust // Step 1: Announce coldkey swap (commits hash of new coldkey) use sp_runtime::traits::Hash; let new_coldkey_hash = T::Hashing::hash_of(&new_coldkey_account); let call = pallet_subtensor::Call::::announce_coldkey_swap { new_coldkey_hash: new_coldkey_hash, }; // Step 2: After delay period, execute the swap let call = pallet_subtensor::Call::::swap_coldkey_announced { new_coldkey: new_coldkey_account, }; ``` -------------------------------- ### Start Development Chain with Debug Logging Source: https://github.com/opentensor/subtensor/blob/main/README.md Starts the Subtensor development chain with detailed logging enabled by setting RUST_BACKTRACE and RUST_LOG environment variables. ```bash RUST_BACKTRACE=1 ./target/release/subtensor-ldebug --dev ``` -------------------------------- ### Install Build Dependencies on Arch Linux Source: https://github.com/opentensor/subtensor/blob/main/docs/rust-setup.md Run these commands in a terminal to install required packages for Substrate development on Arch Linux. ```bash pacman -Syu --needed --noconfirm curl git clang ``` -------------------------------- ### Install Build Dependencies on Ubuntu/Debian Source: https://github.com/opentensor/subtensor/blob/main/docs/rust-setup.md Execute these commands in a terminal to install necessary build tools and libraries for Substrate development on Ubuntu or Debian-based systems. ```bash sudo apt update # May prompt for location information sudo apt install -y git clang curl libssl-dev llvm libudev-dev make pkg-config protobuf-compiler ``` -------------------------------- ### Install polkadot-api Globally Source: https://github.com/opentensor/subtensor/blob/main/contract-tests/README.md Install the polkadot-api tool globally using npm. This is a prerequisite for interacting with Subtensor's local network. ```bash npm i -g polkadot-api ``` -------------------------------- ### Install Subtensor Prerequisites Source: https://github.com/opentensor/subtensor/blob/main/docs/consensus.md Updates system packages and installs essential tools like Python, Rust, and build dependencies required for compiling Subtensor. This command also sets up the Rust environment and targets. ```bash sudo apt-get update && sudo apt install -y build-essential clang curl git make libssl-dev llvm libudev-dev protobuf-compiler python3 python3-pip \ && curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y \ && source ~/.cargo/env \ && rustup default stable \ && rustup update \ && rustup target add wasm32v1-none ``` -------------------------------- ### Set Children for Delegation (Python) Source: https://context7.com/opentensor/subtensor/llms.txt This Python example shows how to compose a `set_children` call using the `substrate` library. It specifies the parent hotkey, network UID, and a list of child hotkeys with their respective stake proportions. ```python call = substrate.compose_call( call_module='SubtensorModule', call_function='set_children', call_params={ 'hotkey': parent_hotkey_ss58, 'netuid': 1, 'children': [ (9223372036854775807, child1_ss58), # u64::MAX / 2 (4611686018427387903, child2_ss58), # u64::MAX / 4 ] } ) ``` -------------------------------- ### Start Jupyter-lab Source: https://github.com/opentensor/subtensor/blob/main/docs/consensus.md Launches Jupyter-lab on the VPS, allowing interactive exploration of generated plots and modification of plotting scripts. Access it via the provided URL in your local browser. ```bash jupyter-lab --allow-root --port=8888 ``` -------------------------------- ### Set Subnet Hyperparameters with Admin Utils (Python) Source: https://context7.com/opentensor/subtensor/llms.txt Python example demonstrating how to compose a call to the `sudo_set_immunity_period` extrinsic using the `substrate-interface` library. ```python # Python example call = substrate.compose_call( call_module='AdminUtils', call_function='sudo_set_immunity_period', call_params={ 'netuid': 1, 'immunity_period': 7200 } ) ``` -------------------------------- ### Start Single-Node Development Chain Source: https://github.com/opentensor/subtensor/blob/main/README.md Launches a local Subtensor node for development. The chain state is not persistent and will be lost when the node stops. ```bash ./target/release/subtensor --dev ``` -------------------------------- ### Serve Axon Endpoint (Python) Source: https://context7.com/opentensor/subtensor/llms.txt This Python example demonstrates how to compose a `serve_axon` call using the `substrate` library. It includes a helper function to convert IP addresses to the required integer format. ```python import socket import struct def ip_to_int(ip_str): return struct.unpack("!I", socket.inet_aton(ip_str))[0] call = substrate.compose_call( call_module='SubtensorModule', call_function='serve_axon', call_params={ 'netuid': 1, 'version': 1, 'ip': ip_to_int('192.168.1.100'), 'port': 8091, 'ip_type': 4, # IPv4 'protocol': 0, # TCP 'placeholder1': 0, 'placeholder2': 0 } ) ``` -------------------------------- ### Announce Coldkey Swap (Python) Source: https://context7.com/opentensor/subtensor/llms.txt Python example for announcing a coldkey swap. It involves hashing the new coldkey's public key and composing the `announce_coldkey_swap` extrinsic call. ```python # Python example from substrateinterface import SubstrateInterface, Keypair import hashlib substrate = SubstrateInterface(url="ws://127.0.0.1:9945") old_coldkey = Keypair.create_from_mnemonic("old coldkey mnemonic") new_coldkey = Keypair.create_from_mnemonic("new coldkey mnemonic") # Hash the new coldkey new_coldkey_hash = hashlib.blake2b(bytes.fromhex(new_coldkey.public_key.hex()), digest_size=32).digest() # Announce the swap call = substrate.compose_call( call_module='SubtensorModule', call_function='announce_coldkey_swap', call_params={'new_coldkey_hash': '0x' + new_coldkey_hash.hex()} ) ``` -------------------------------- ### Validator Example Contract Source: https://context7.com/opentensor/subtensor/llms.txt Provides an example contract for validators to submit weights to neurons using the INeuron interface. ```solidity // Usage example contract ValidatorExample { INeuron constant NEURON = INeuron(0x0000000000000000000000000000000000000804); function submitWeights(uint16 netuid, uint16[] calldata uids, uint16[] calldata weights) external { NEURON.setWeights(netuid, uids, weights, 1000); } } ``` -------------------------------- ### Install and Run Moonwall Tests Source: https://github.com/opentensor/subtensor/blob/main/docs/testing.md Commands to install Moonwall, set up dependencies, and run different types of tests (dev, zombienet, smoke_mainnet). Ensure the correct Node version is used and consider using sudo for zombienet on MacOS. ```bash # Use the correct Node version nvm use # Install moonwall sudo npm i -g pnpm # Change directory to test cd ts-tests # Install dependencies pnpm i # Run manual seal dev tests pnpm moonwall test dev # Run zombienet tests pnpm moonwall test zombienet # If you have MacOS, you might need to run zombinet test with sudo, because tmp folder sudo pnpm moonwall test zombienet # Run smoke tests pnpm moonwall test smoke_mainnet ``` -------------------------------- ### Query Stake Information (Python) Source: https://context7.com/opentensor/subtensor/llms.txt Python examples for querying various stake-related information from the Subtensor chain using `substrate-interface`. This includes total hotkey stake, specific coldkey stake on a subnet, subnet existence, neuron count, and weights. ```python from substrateinterface import SubstrateInterface substrate = SubstrateInterface(url="ws://127.0.0.1:9945") # Get total stake for a hotkey result = substrate.query('SubtensorModule', 'TotalHotkeyStake', [hotkey_ss58]) print(f"Total hotkey stake: {result.value}") # Get stake for coldkey on specific subnet result = substrate.query('SubtensorModule', 'Alpha', [hotkey_ss58, coldkey_ss58, netuid]) print(f"Alpha stake: {result.value}") # Get subnet info result = substrate.query('SubtensorModule', 'NetworksAdded', [netuid]) print(f"Subnet exists: {result.value}") # Get neuron count in subnet result = substrate.query('SubtensorModule', 'SubnetworkN', [netuid]) print(f"Neurons in subnet: {result.value}") # Get current block weights result = substrate.query('SubtensorModule', 'Weights', [netuid, uid]) print(f"Weights set by UID {uid}: {result.value}") ``` -------------------------------- ### Start Development Chain with Persistent State Source: https://github.com/opentensor/subtensor/blob/main/README.md Launches a Subtensor development chain using a specified directory for persistent storage of the chain's database and keystore. ```bash ./target/release/node-template --dev --base-path ./my-chain-state/ ``` -------------------------------- ### Check \"//Alice\" Account Balance Source: https://github.com/opentensor/subtensor/blob/main/docs/running-subtensor-locally.md Use this Python script to verify your connection to the local Subtensor node by querying the balance of the \"//Alice\" account. Ensure you have the substrate-interface library installed. ```python # pip install substrate-interface from substrateinterface import Keypair, SubstrateInterface substrate = SubstrateInterface(url="ws://127.0.0.1:9945") hotkey = Keypair.create_from_uri('//Alice') result = substrate.query("System", "Account", [hotkey.ss58_address]) print(result.value) ``` -------------------------------- ### Start tmux Session Source: https://github.com/opentensor/subtensor/blob/main/docs/consensus.md Initiates a tmux session to maintain your terminal environment persistently, even if your SSH connection drops. ```bash tmux ``` -------------------------------- ### Query Metagraph Data (Python) Source: https://context7.com/opentensor/subtensor/llms.txt Python example to retrieve the total number of neurons (UIDs) in a given subnet, which can be used to iterate through all UIDs. ```python # Get all UIDs in a subnet result = substrate.query('SubtensorModule', 'SubnetworkN', [netuid]) neuron_count = result.value ``` -------------------------------- ### Add Development Network Metadata Source: https://github.com/opentensor/subtensor/blob/main/contract-tests/README.md Add metadata for the development network by running this command after starting the localnet. It creates a .papi folder with type definitions. ```bash npx papi add devnet -w ws://localhost:9944 ``` -------------------------------- ### Run Benchmark Unit Tests Source: https://github.com/opentensor/subtensor/blob/main/docs/benchmarks-and-weights.md This command runs fast unit tests for benchmarks, primarily checking the setup rather than performing real measurements. Ensure the `runtime-benchmarks` feature is enabled for the `pallet-subtensor` crate. ```rust cargo test -p pallet-subtensor --features runtime-benchmarks benchmarks ``` -------------------------------- ### Run Subtensor Node Without Recompiling Source: https://github.com/opentensor/subtensor/blob/main/README.md Execute this command to start the Subtensor node using Docker without recompiling the code. Useful for quick restarts or testing changes. ```bash ./scripts/docker_run.sh ./target/release/node-template --dev --ws-external ``` -------------------------------- ### Set Subnet Hyperparameters with Admin Utils (Rust) Source: https://context7.com/opentensor/subtensor/llms.txt Rust examples for using the admin-utils pallet to set subnet hyperparameters like immunity period, minimum allowed weights, weights version key, and max difficulty. These functions are typically restricted to sudo or owner roles. ```rust // Set immunity period (subnet owner or root) let call = pallet_admin_utils::Call::::sudo_set_immunity_period { netuid: NetUid::from(1u16), immunity_period: 7200u16, // ~1 day at 12s blocks }; // Set minimum allowed weights let call = pallet_admin_utils::Call::::sudo_set_min_allowed_weights { netuid: NetUid::from(1u16), min_allowed_weights: 10u16, }; // Set weights version key (forces validators to update) let call = pallet_admin_utils::Call::::sudo_set_weights_version_key { netuid: NetUid::from(1u16), weights_version_key: 2000u64, }; // Set max difficulty for registration let call = pallet_admin_utils::Call::::sudo_set_max_difficulty { netuid: NetUid::from(1u16), max_difficulty: 1_000_000_000u64, }; ``` -------------------------------- ### Display Node Help Information Source: https://github.com/opentensor/subtensor/blob/main/README.md Execute this command after building the node to view its capabilities and configuration parameters. ```shell ./target/release/node-subtensor --help ``` -------------------------------- ### Build and Generate Weights for All Pallets Source: https://github.com/opentensor/subtensor/blob/main/docs/benchmarks-and-weights.md Execute this script to build the node and generate benchmark weights for all pallets. This is the most comprehensive benchmarking command. ```sh ./scripts/benchmark_all.sh ``` -------------------------------- ### Install Specific Rust Nightly Version Source: https://github.com/opentensor/subtensor/blob/main/docs/rust-setup.md Install a specific Rust nightly toolchain by replacing `` with the desired date. This is useful for ensuring build consistency across different development environments. ```bash rustup install nightly- ``` -------------------------------- ### Run Code Coverage Source: https://github.com/opentensor/subtensor/blob/main/README.md Generates a code coverage report for the project using cargo-tarpaulin. Ensure cargo-tarpaulin is installed. ```bash bash scripts/code-coverage.sh ``` -------------------------------- ### Explore Subtensor Parameters Source: https://github.com/opentensor/subtensor/blob/main/README.md After building the project, use this command to view all available parameters and subcommands for the Subtensor executable. ```sh ./target/release/subtensor -h ``` -------------------------------- ### Configure Wasm Toolchain Source: https://github.com/opentensor/subtensor/blob/main/docs/rust-setup.md Add the Wasm compilation target to a specific Rust nightly toolchain. Replace `` with the date of the nightly version you installed. ```bash rustup target add wasm32v1-none --toolchain nightly- ``` -------------------------------- ### Coldkey Swap - Announce and Execute Source: https://context7.com/opentensor/subtensor/llms.txt Securely migrate your coldkey using a two-step process involving announcement and final execution after a delay. ```APIDOC ## Coldkey Swap - Announce and Execute ### Description Enables secure coldkey migration with a delay period using `announce_coldkey_swap` and `swap_coldkey_announced` extrinsics. ### Step 1: Announce Coldkey Swap Commits the hash of the new coldkey. ```rust // Announce coldkey swap (commits hash of new coldkey) use sp_runtime::traits::Hash; let new_coldkey_hash = T::Hashing::hash_of(&new_coldkey_account); let call = pallet_subtensor::Call::::announce_coldkey_swap { new_coldkey_hash: new_coldkey_hash, }; ``` ### Step 2: Execute Coldkey Swap After the delay period, execute the swap with the new coldkey. ```rust // Execute the swap let call = pallet_subtensor::Call::::swap_coldkey_announced { new_coldkey: new_coldkey_account, }; ``` ### Python Example (Announce Coldkey Swap) ```python from substrateinterface import SubstrateInterface, Keypair import hashlib substrate = SubstrateInterface(url="ws://127.0.0.1:9945") old_coldkey = Keypair.create_from_mnemonic("old coldkey mnemonic") new_coldkey = Keypair.create_from_mnemonic("new coldkey mnemonic") # Hash the new coldkey new_coldkey_hash = hashlib.blake2b(bytes.fromhex(new_coldkey.public_key.hex()), digest_size=32).digest() # Announce the swap call = substrate.compose_call( call_module='SubtensorModule', call_function='announce_coldkey_swap', call_params={'new_coldkey_hash': '0x' + new_coldkey_hash.hex()} ) ``` ``` -------------------------------- ### Run Specific Test Case Source: https://github.com/opentensor/subtensor/blob/main/contract-tests/README.md Run a particular test case by providing a filter argument. This example filters for tests containing 'Can set subnet parameter'. ```bash yarn run test -- -g "Can set subnet parameter" ``` -------------------------------- ### Downgrade Rust Nightly Source: https://github.com/opentensor/subtensor/blob/main/docs/rust-setup.md Uninstall the current nightly toolchain, install a specific version, and add the Wasm target for that version. This is helpful if the latest nightly causes build errors. ```bash rustup uninstall nightly ustup install nightly- ustup target add wasm32v1-none --toolchain nightly- ``` -------------------------------- ### Configure macOS Environment Variables for LLVM 16 Source: https://github.com/opentensor/subtensor/blob/main/docs/rust-setup.md Appends environment variable configurations to ~/.zshrc to direct the build process to use LLVM 16 installed via Homebrew. ```bash # LLVM 16 from Homebrew export PATH="/opt/homebrew/opt/llvm@16/bin:$PATH" export CC="/opt/homebrew/opt/llvm@16/bin/clang" export CXX="/opt/homebrew/opt/llvm@16/bin/clang++" export LIBCLANG_PATH="/opt/homebrew/opt/llvm@16/lib/libclang.dylib" export LDFLAGS="-L/opt/homebrew/opt/llvm@16/lib" export CPPFLAGS="-I/opt/homebrew/opt/llvm@16/include" ``` -------------------------------- ### Connect to Runpod Instance via SSH Source: https://github.com/opentensor/subtensor/blob/main/docs/consensus.md Use this command to establish an SSH connection to your deployed Runpod instance. Ensure you replace placeholders with your actual IP address and port. The `-i` flag specifies your private key. ```bash ssh -L 8888:localhost:8888 root@ -p -i ~/.ssh/id_ed25519 # Replace placeholders ``` -------------------------------- ### Compare Two Weight Files Source: https://github.com/opentensor/subtensor/blob/main/docs/benchmarks-and-weights.md This command-line tool compares two weight files (`--old` and `--new`) and reports differences based on a specified threshold. It's useful for identifying significant changes in benchmark results. ```rust cargo run -p subtensor-weight-tools --bin weight-compare -- \ --old pallets/foo/src/weights.rs \ --new /tmp/new_weights.rs \ --threshold 40 ``` -------------------------------- ### Subtensor Chain Extension for ink! Contracts Source: https://github.com/opentensor/subtensor/blob/main/docs/wasm-contracts.md Example of how to define and use the Subtensor chain extension within an ink! smart contract to interact with Subtensor's staking functionalities. ```rust #[ink::chain_extension(extension = 0)] pub trait SubtensorExtension { type ErrorCode = SubtensorError; #[ink(function = 0)] fn get_stake_info( hotkey: AccountId, coldkey: AccountId, netuid: u16, ) -> Result, SubtensorError>; } ``` -------------------------------- ### Wire Up WeightInfo in Runtime Source: https://github.com/opentensor/subtensor/blob/main/docs/benchmarks-and-weights.md This Rust snippet shows how to wire up the pallet's `WeightInfo` implementation within the runtime configuration. This ensures that the runtime uses the correct weight information for extrinsics. ```rust type WeightInfo = pallet_::weights::SubstrateWeight; ``` -------------------------------- ### Build Project Source: https://github.com/opentensor/subtensor/blob/main/pallets/drand/README.md Compile the project using Cargo. This command builds the project in debug mode. ```shell cargo build ``` -------------------------------- ### Run Moonwall in Manual Test Mode Source: https://github.com/opentensor/subtensor/blob/main/docs/testing.md Commands to run the Moonwall testing environment in 'run' mode for manual testing. This allows you to interact with the testing setup without executing predefined tests. ```bash # Dev tests in run mode pnpm moonwall run dev # Zombinet test with run mode pnpm moonwall run zombienet ``` -------------------------------- ### Run All Tests Source: https://github.com/opentensor/subtensor/blob/main/contract-tests/README.md Execute the entire test suite using the yarn test command. ```bash yarn run test ``` -------------------------------- ### Build and Run Subtensor Node Source: https://github.com/opentensor/subtensor/blob/main/README.md Use this command to build the Subtensor node in release mode and launch it for development. The state will be discarded after termination. ```sh cargo run --release -- --dev ```