### Asynchronous Subnet Setup Test Source: https://github.com/latent-to/bittensor/blob/master/bittensor/extras/dev_framework/README.md Illustrates subnet setup and activation using asynchronous execution. This example requires pytest and an async subtensor instance. ```python import pytest @pytest.mark.asyncio async def test_subnet_async(async_subtensor, alice_wallet): from tests.e2e_tests.utils import ( TestSubnet, NETUID, REGISTER_SUBNET, ACTIVATE_SUBNET, SUDO_SET_TEMPO, AdminUtils ) sn = TestSubnet(async_subtensor) steps = [ REGISTER_SUBNET(alice_wallet), ACTIVATE_SUBNET(alice_wallet), SUDO_SET_TEMPO(alice_wallet, AdminUtils, True, NETUID, 100), ] await sn.async_execute_steps(steps) assert await async_subtensor.subnets.is_subnet_active(sn.netuid) ``` -------------------------------- ### Install Bittensor with Pip Source: https://github.com/latent-to/bittensor/blob/master/contrib/DEBUGGING.md Install the Bittensor package using pip for a quick setup. ```bash pip install bittensor ``` -------------------------------- ### Install Bittensor from Source Source: https://github.com/latent-to/bittensor/blob/master/contrib/DEBUGGING.md Clone the Bittensor repository and install it locally from source. This is useful for development or contributing. ```bash git clone https://github.com/opentensor/bittensor.git python3 -m pip install -e bittensor/ ``` -------------------------------- ### Install Bittensor via Installer Script Source: https://github.com/latent-to/bittensor/blob/master/contrib/DEBUGGING.md Use this script to install Bittensor. Ensure you have curl and bash installed. ```bash /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/opentensor/bittensor/master/scripts/install.sh)" ``` -------------------------------- ### Install Silver Searcher (ag) Source: https://github.com/latent-to/bittensor/blob/master/contrib/DEBUGGING.md Install the 'ag' command-line tool, a fast and convenient tool for searching text patterns in files. ```bash apt-get install silversearcher-ag ``` -------------------------------- ### Install Bittensor SDK with Torch Source: https://github.com/latent-to/bittensor/blob/master/README.md Install the Bittensor SDK along with PyTorch support. Use the quoted version if the standard command fails. ```python pip install bittensor[torch] ``` ```python pip install "bittensor[torch]" ``` -------------------------------- ### Verify Bittensor SDK Installation Source: https://github.com/latent-to/bittensor/blob/master/README.md Check the installed version of the Bittensor SDK using this command. This confirms that the SDK has been successfully installed. ```bash python3 -m bittensor ``` -------------------------------- ### AsyncSubtensor Initialization and Usage Source: https://github.com/latent-to/bittensor/wiki/Concurrency-in-Bittensor Shows the recommended way to initialize and use AsyncSubtensor with 'async with' for proper setup and cleanup. ```python async with AsyncSubtensor() as subtensor: # `initialize()` setup occurs in here await subtensor.call... ``` -------------------------------- ### Full Git Log Entry Example Source: https://github.com/latent-to/bittensor/blob/master/contrib/STYLE.md This example shows a complete Git log entry, including commit hash, author, date, subject, and body, demonstrating the structure of detailed commit history. ```git commit 42e769bdf4894310333942ffc5a15151222a87be Author: Kevin Flynn Date: Fri Jan 01 00:00:00 1982 -0200 Derezz the master control program MCP turned out to be evil and had become intent on world domination. This commit throws Tron's disc into MCP (causing its deresolution) and turns it back into a chess game. ``` -------------------------------- ### Verify Bittensor Installation Source: https://github.com/latent-to/bittensor/blob/master/contrib/DEBUGGING.md Run this command to check your installed Bittensor version and confirm the installation was successful. ```python python3 -c "import bittensor; print(bittensor.__version__)" ``` -------------------------------- ### Install Bittensor SDK using pip Source: https://github.com/latent-to/bittensor/blob/master/README.md Create and activate a Python virtual environment before installing the Bittensor SDK using pip. This method is suitable for macOS and Linux. ```bash python3 -m venv bt_venv source bt_venv/bin/activate pip install bittensor ``` -------------------------------- ### Run E2E Tests with Legacy Runner (Docker Installed) Source: https://github.com/latent-to/bittensor/blob/master/README.md Force the use of the legacy runner for end-to-end tests, even if Docker is installed. Requires setting LOCALNET_SH_PATH, BUILD_BINARY=0, and USE_DOCKER=0. ```bash USE_DOCKER=0 BUILD_BINARY=0 LOCALNET_SH_PATH=/path/to/your/localnet.sh pytest tests/e2e_tests ``` -------------------------------- ### Install Bittensor Development Dependencies Source: https://github.com/latent-to/bittensor/blob/master/contrib/TESTING.md Install all necessary testing and development dependencies for Bittensor, ensuring compatible versions are used. ```bash python -m pip install bittensor[dev] ``` -------------------------------- ### Synchronous Subnet Setup Test Source: https://github.com/latent-to/bittensor/blob/master/bittensor/extras/dev_framework/README.md Demonstrates setting up and activating a subnet using synchronous execution of predefined steps. Requires a subtensor instance and an alice wallet. ```python def test_subnet_setup(subtensor, alice_wallet): from tests.e2e_tests.utils import ( TestSubnet, NETUID, REGISTER_SUBNET, ACTIVATE_SUBNET, SUDO_SET_TEMPO, AdminUtils ) sn = TestSubnet(subtensor) steps = [ REGISTER_SUBNET(alice_wallet), ACTIVATE_SUBNET(alice_wallet), SUDO_SET_TEMPO(alice_wallet, AdminUtils, True, NETUID, 100), ] sn.execute_steps(steps) assert subtensor.subnets.is_subnet_active(sn.netuid) ``` -------------------------------- ### Get Stake Info For Coldkey (Renamed) Source: https://github.com/latent-to/bittensor/blob/master/MIGRATION-GUIDE.md The method to get stake information for a coldkey has been renamed from `get_stake_for_coldkey` to `get_stake_info_for_coldkey`. ```APIDOC ## Get Stake Info For Coldkey ### Description Retrieves detailed stake information associated with a given coldkey. ### Method `subtensor.get_stake_info_for_coldkey(coldkey_ss58)` ### Parameters - **coldkey_ss58**: The SS58 address of the coldkey. ### Example ```python # New method stake_info = subtensor.get_stake_info_for_coldkey(coldkey_ss58) ``` ``` -------------------------------- ### Install pytest-cov for Test Coverage Source: https://github.com/latent-to/bittensor/blob/master/contrib/TESTING.md Install the pytest-cov plugin to measure test coverage. This is a prerequisite for running coverage reports. ```bash pip install pytest-cov ``` -------------------------------- ### Basic Bittensor Unit Test Structure Source: https://github.com/latent-to/bittensor/blob/master/contrib/TESTING.md A fundamental example of a Python unit test for a Bittensor function. It demonstrates setup, function calls, and assertions. ```python import pytest import bittensor def test_some_functionality(): # Setup any necessary objects or state. wallet = bittensor.Wallet() # Call the function you're testing. result = wallet.create_new_coldkey() # Assert that the function behaved as expected. assert result is not None ``` -------------------------------- ### Synchronous Subtensor New Instance Example Source: https://github.com/latent-to/bittensor/wiki/Concurrency-in-Bittensor Shows creating a new Subtensor instance within each thread for concurrent tempo calls. ```python def new(): def new_(netuid: int): subtensor = Subtensor() return subtensor.tempo(netuid) with ThreadPoolExecutor() as executor: for tempo in executor.map(new_, [1,2,3]): print(tempo) ``` -------------------------------- ### Example Console Output Source: https://github.com/latent-to/bittensor/blob/master/bittensor/extras/dev_framework/README.md Illustrates the colorized logging output for various operations within the `TestSubnet` framework, such as subnet registration, activation, and hyperparameter updates. ```text Subnet [blue]1[/blue] was registered. Subnet [blue]1[/blue] was activated. Hyperparameter [blue]sudo_set_tempo[/blue] was set successfully with params [blue]{'netuid': 1, 'tempo': 20}[/blue]. ``` -------------------------------- ### Run Integration and Unit Tests Source: https://github.com/latent-to/bittensor/blob/master/README.md Execute integration and unit tests from your terminal. Ensure you have pytest installed. ```bash pytest tests/integration_tests ``` ```bash pytest tests/unit_tests ``` -------------------------------- ### Clone Bittensor SDK Repository Source: https://github.com/latent-to/bittensor/blob/master/README.md Clone the Bittensor SDK repository from GitHub to install from source. Ensure you have Git installed. ```bash git clone https://github.com/opentensor/bittensor.git ``` -------------------------------- ### Bitcoin Core Commit Example Source: https://github.com/latent-to/bittensor/blob/master/contrib/STYLE.md This commit message from Bitcoin Core demonstrates explaining what changed and why, focusing on the 'what' and 'why' rather than the 'how'. ```git commit eb0b56b19017ab5c16c745e6da39c53126924ed6 Author: Pieter Wuille Date: Fri Aug 1 22:57:55 2014 +0200 Simplify serialize.h's exception handling Remove the 'state' and 'exceptmask' from serialize.h's stream implementations, as well as related methods. As exceptmask always included 'failbit', and setstate was always called with bits = failbit, all it did was immediately raise an exception. Get rid of those variables, and replace the setstate with direct exception throwing (which also removes some dead code). As a result, good() is never reached after a failure (there are only 2 calls, one of which is in tests), and can just be replaced by !eof(). fail(), clear(n) and exceptions() are just never called. Delete them. ``` -------------------------------- ### Synchronous Subtensor Reuse Example Source: https://github.com/latent-to/bittensor/wiki/Concurrency-in-Bittensor Demonstrates using ThreadPoolExecutor to concurrently call the tempo function on a single Subtensor instance. ```python import asyncio from bittensor.core.subtensor import Subtensor from bittensor.core.async_subtensor import AsyncSubtensor from concurrent.futures import ThreadPoolExecutor def reuse(): def reuse_(netuid: int): return subtensor.tempo(netuid) subtensor = Subtensor() with ThreadPoolExecutor() as executor: for tempo in executor.map(reuse_, [1,2,3]): print(tempo) ``` -------------------------------- ### Verify Bittensor Version Source: https://github.com/latent-to/bittensor/blob/master/README.md Run this in the Python interpreter to check your installed Bittensor version. Ensure bittensor is installed correctly. ```bash python3 ``` ```python import bittensor as bt print( bt.__version__ ) ``` -------------------------------- ### Bittensor Package - Full Miner/Validator Interaction Source: https://github.com/latent-to/bittensor/blob/master/contrib/DEBUGGING.md This comprehensive example demonstrates creating a wallet, connecting to an axon, serving messages, and sending prompts using the Bittensor package. It covers typical codepaths for miners and validators. ```python import bittensor # Bittensor's wallet maintenance class. wallet = bittensor.Wallet() # Bittensor's chain interface. subtensor = bittensor.Subtensor() # Bittensor's chain state object. metagraph = bittensor.Metagraph(netuid=1) # Instantiate a Bittensor endpoint. axon = bittensor.Axon(wallet=wallet) # Start servicing messages on the wire. axon.start() # Register this axon on a subnetwork subtensor.serve_axon(netuid=1, axon=axon) # Connect to the axon running on slot 10, use the wallet to sign messages. dendrite = bittensor.Dendrite(wallet=wallet) # Send a prompt to this endpoint dendrite.forward(axon=metagraph.axons[10], roles=['user'], messages=['Who is Rick James?']) ``` -------------------------------- ### Get Stake Info for Coldkey (New) Source: https://github.com/latent-to/bittensor/blob/master/MIGRATION-GUIDE.md Retrieve stake information for a given coldkey address. This replaces the removed `get_stake_for_coldkey` method. ```python # ✅ Use instead: stake_info = subtensor.get_stake_info_for_coldkey(coldkey_ss58) ``` -------------------------------- ### Asynchronous Subtensor Usage Example Source: https://github.com/latent-to/bittensor/wiki/Concurrency-in-Bittensor Illustrates concurrent calls using AsyncSubtensor and asyncio.gather, managed within an async context. ```python def async_use(): async def async_use_(): async def async_reuse(netuid: int): return await async_subtensor.tempo(netuid) async with AsyncSubtensor() as async_subtensor: for tempo in await asyncio.gather(async_reuse(1), async_reuse(2), async_subtensor.tempo(3)): print(tempo) asyncio.run(async_use_()) ``` -------------------------------- ### Run E2E Tests with Docker Runner Source: https://github.com/latent-to/bittensor/blob/master/README.md Execute end-to-end tests using the Docker runner. This is the default and requires Docker to be installed. ```bash pytest tests/e2e_tests ``` -------------------------------- ### Bad vs. Good Commit Message Example Source: https://github.com/latent-to/bittensor/blob/master/contrib/STYLE.md Avoid trivial commit messages. Use descriptive messages that clearly indicate the changes made, as shown in the 'Good Commit Message' example. ```git $ git commit -m "fix" ``` ```git $ git commit -m "Fix typo in README file" ``` -------------------------------- ### Upgrade Bittensor SDK Source: https://github.com/latent-to/bittensor/blob/master/README.md Use this command to upgrade to the latest version of the Bittensor SDK. Ensure you have Python 3 installed. ```bash python3 -m pip install --upgrade bittensor ``` -------------------------------- ### Mocking Bittensor Components for Testing Source: https://github.com/latent-to/bittensor/blob/master/contrib/TESTING.md Example of using unittest.mock (via pytest's mocker fixture) to mock Bittensor Wallet components for isolated testing of the Axon server. ```python import bittensor import pytest def test_axon_start(mocker): mock_wallet = mocker.Mock( spec=bittensor.Wallet, coldkey=mocker.Mock(spec=str), coldkeypub=mocker.Mock( # mock ss58 address ss58_address="5DD26kC2kxajmwfbbZmVmxhrY9VeeyR1Gpzy9i8wxLUg6zxm" ), hotkey=mocker.Mock( ss58_address="5CtstubuSoVLJGCXkiWRNKrrGg2DVBZ9qMs2qYTLsZR4q1Wg" ), ) axon = bittensor.Axon(wallet=mock_wallet, config=bittensor.Config()) axon.start() assert axon.server._state.stage == grpc._server._ServerStage.STARTED ``` -------------------------------- ### Commit Message with Body Example Source: https://github.com/latent-to/bittensor/blob/master/contrib/STYLE.md When a commit requires more explanation, use a blank line to separate the subject from the body. This format is best written in a text editor rather than using the `-m` option. ```git Derezz the master control program MCP turned out to be evil and had become intent on world domination. This commit throws Tron's disc into MCP (causing its deresolution) and turns it back into a chess game. ``` -------------------------------- ### Enable Verbose Logging for Subtensor Source: https://github.com/latent-to/bittensor/blob/master/MIGRATION-GUIDE.md Enable trace-level logging for the Subtensor class to get detailed logs of interactions with the Subtensor blockchain. ```python # Set verbose mode for trace-level logging subtensor = Subtensor(network="test", log_verbose=True) # Automatically sets btlogging to TRACE level for detailed blockchain interaction logs ``` -------------------------------- ### Get Fee for Moving Stake Between Subnets Source: https://github.com/latent-to/bittensor/blob/master/MIGRATION-GUIDE.md Calculate the application-level swap fee for moving stake between two subnets. This method returns a Balance object. ```python # Get fee for moving stake between subnets fee = subtensor.get_stake_movement_fee(origin_netuid, destination_netuid, amount) ``` -------------------------------- ### Simple Commit Message Example Source: https://github.com/latent-to/bittensor/blob/master/contrib/STYLE.md For very simple changes, a single-line commit message is sufficient. This is easily achieved using the `git commit -m` option. ```git Fix typo in introduction to user guide ``` ```git $ git commit -m "Fix typo in introduction to user guide" ``` -------------------------------- ### Query Bittensor Network Block Height Source: https://github.com/latent-to/bittensor/blob/master/contrib/DEBUGGING.md Example of querying the Bittensor network's current block height using the Subtensor object. Ensure trace logging is enabled for detailed output. ```python import bittensor bittensor.trace() # Attempt to query through the foundation endpoint. print(bittensor.Subtensor().block) ``` -------------------------------- ### Initializing MetagraphInfo with MechID Source: https://github.com/latent-to/bittensor/blob/master/MIGRATION-GUIDE.md The MetagraphInfo class now requires the 'mechid' parameter to support multiple incentive mechanisms per subnet. Ensure you provide the correct mechanism ID when instantiating MetagraphInfo. ```python # mechid is now required in MetagraphInfo from bittensor.core.chain_data.metagraph_info import MetagraphInfo info = MetagraphInfo( netuid=1, mechid=0, # Now required (mechanism ID) # ... other fields ) ``` -------------------------------- ### Install Bittensor Package Source: https://github.com/latent-to/bittensor/blob/master/MIGRATION-GUIDE.md Update the bittensor package to version 10.0.0 or higher. Until the public release, install the latest available release candidate. ```bash pip install bittensor>=10.0.0 ``` -------------------------------- ### Balance Arithmetic Source: https://context7.com/latent-to/bittensor/llms.txt Demonstrates the usage of the `Balance` class for handling TAO and Rao amounts, including construction, arithmetic operations, and comparisons. ```APIDOC ## Balance — TAO/Rao Arithmetic `Balance` is the SDK's unit-aware currency type. All staking, transfer, and fee amounts are expressed as `Balance` objects (stored internally in Rao, the smallest indivisible unit; 1 TAO = 10⁹ Rao). ```python # Construction b1 = Balance.from_tao(10.5) b2 = Balance.from_rao(500_000_000) # 0.5 TAO print(f"b1: {b1.tao} TAO ({b1.rao} Rao)") print(f"b2: {b2.tao} TAO") # Arithmetic (balances must share the same netuid for subnets) total = b1 + b2 print(f"Sum: {total.tao} TAO") diff = b1 - b2 print(f"Diff: {diff.tao} TAO") # Subnet Alpha balance (netuid=14) alpha = Balance.from_tao(5.0, netuid=14) print(f"Alpha unit: {alpha.unit}") # α14 # Comparisons print(b1 > b2) # True print(b1 == Balance.from_rao(10_500_000_000)) # True ``` ``` -------------------------------- ### Example Atomic Commit Message for PR Source: https://github.com/latent-to/bittensor/blob/master/contrib/STYLE.md An example of a well-structured commit message for a pull request that provides a comprehensive overview of changes, including a summary, detailed breakdown, and resolution of issues. ```gitcommit Add feature X This commit introduces feature X which does A, B, and C. It adds new files for layout, updates the code behind the file, and introduces new resources. This change is important because it allows users to perform task Y more efficiently. It includes: - Creation of new layout file - Updates in the code-behind file - Addition of new resources Resolves: #123 ``` -------------------------------- ### Run Pre-configured Miner Source: https://github.com/latent-to/bittensor/blob/master/contrib/DEBUGGING.md Execute a pre-configured miner, such as the text prompting miner. Replace `` with the appropriate UID. ```bash python3 bittensor/neurons/text_prompting/miners/GPT4ALL/neuron.py --netuid ``` -------------------------------- ### Removed Duplicate Stake Info Method Source: https://github.com/latent-to/bittensor/blob/master/MIGRATION-GUIDE.md The `subtensor.get_stake_info_for_coldkey` method was a duplicate reference and has been removed. Use the canonical name `subtensor.get_stake_for_coldkey` instead. ```python # ❌ Removed (was just a reference): subtensor.get_stake_info_for_coldkey = subtensor.get_stake_for_coldkey # ✅ Use the canonical name: subtensor.get_stake_info_for_coldkey(coldkey_ss58) ``` -------------------------------- ### Get All Subnets Netuid (Renamed) Source: https://github.com/latent-to/bittensor/blob/master/MIGRATION-GUIDE.md The method to retrieve subnet UIDs has been renamed from `get_subnets` to `get_all_subnets_netuid`. ```APIDOC ## Get All Subnets Netuid ### Description Retrieves a list of all subnet netuids. ### Method `subtensor.get_all_subnets_netuid()` ### Example ```python # New method netuids = subtensor.get_all_subnets_netuid() ``` ``` -------------------------------- ### Simulate Adding Stake (TAO to Alpha) Source: https://github.com/latent-to/bittensor/blob/master/MIGRATION-GUIDE.md Simulate adding stake from TAO to a target subnet to see the exact amount of Alpha received and associated fees, without executing the transaction. ```python # Simulate adding stake (TAO → Alpha) to see exact Alpha received result = subtensor.sim_swap( origin_netuid=0, # 0 = TAO (root) destination_netuid=1, # Target subnet amount=tao(100.0), ) print(f"TAO amount: {result.tao_amount}") print(f"Alpha received: {result.alpha_amount}") print(f"TAO fee: {result.tao_fee}") print(f"Alpha fee: {result.alpha_fee}") ``` -------------------------------- ### Check Miner Slot Overview Source: https://github.com/latent-to/bittensor/blob/master/contrib/DEBUGGING.md View the overview of your miner's slot on the network. Replace `` with the appropriate UID. ```bash btcli wallet overview --netuid ``` -------------------------------- ### Get All Subnets NetUID (New) Source: https://github.com/latent-to/bittensor/blob/master/MIGRATION-GUIDE.md Retrieve a list of all subnet netuids. This replaces the deprecated `get_subnets` method. ```python # ✅ New: netuids = subtensor.get_all_subnets_netuid() ``` -------------------------------- ### Get Timelocked Weight Commits (Renamed) Source: https://github.com/latent-to/bittensor/blob/master/MIGRATION-GUIDE.md The method for retrieving weight commit information has been renamed and updated to `get_timelocked_weight_commits`. ```APIDOC ## Get Timelocked Weight Commits ### Description Retrieves information about timelocked weight commits for a given subnet and mechanism. ### Method `subtensor.get_timelocked_weight_commits(netuid, mechid)` ### Parameters - **netuid**: The unique identifier of the subnet. - **mechid**: The identifier for the mechanism. ### Example ```python # New method commits = subtensor.get_timelocked_weight_commits(netuid, mechid) ``` ``` -------------------------------- ### Get Fee for Unstaking Source: https://github.com/latent-to/bittensor/blob/master/MIGRATION-GUIDE.md Calculate the application-level swap fee for unstaking from a subnet. This method returns a Balance object. ```python # Get fee for removing stake (unstaking operation) fee = subtensor.get_unstake_fee(netuid, amount) ``` -------------------------------- ### Run E2E Tests with Legacy Runner Source: https://github.com/latent-to/bittensor/blob/master/README.md Execute end-to-end tests using the legacy runner. Requires setting LOCALNET_SH_PATH and optionally BUILD_BINARY. ```bash LOCALNET_SH_PATH=/path/to/your/localnet.sh pytest tests/e2e_tests ``` -------------------------------- ### Configure Git to Sign All Commits Source: https://github.com/latent-to/bittensor/blob/master/contrib/CONTRIBUTING.md Set Git to automatically sign all commits. This is a global configuration. ```bash git config --global commit.gpgsign true ``` -------------------------------- ### Examples of Imperative Git Commit Subjects Source: https://github.com/latent-to/bittensor/blob/master/contrib/STYLE.md Commit subject lines should be written in the imperative mood, as if giving a command. ```git Refactor subsystem X for readability ``` ```git Update getting started documentation ``` ```git Remove deprecated methods ``` ```git Release version 1.0.0 ``` -------------------------------- ### Simulate Unstaking (Alpha to TAO) Source: https://github.com/latent-to/bittensor/blob/master/MIGRATION-GUIDE.md Simulate unstaking from a source subnet back to TAO to determine the exact TAO received and associated fees, without executing the transaction. ```python # Simulate unstaking (Alpha → TAO) result = subtensor.sim_swap( origin_netuid=1, # Source subnet destination_netuid=0, # 0 = TAO (root) amount=tao(100.0), ) ``` -------------------------------- ### Query Last Bonds Reset Block Source: https://github.com/latent-to/bittensor/blob/master/MIGRATION-GUIDE.md Get the block number of the last bonds reset for a subnet using `get_last_bonds_reset`. ```APIDOC ## Query Bonds Reset ### Description Retrieves the block number when the bonds for a specific subnet were last reset. ### Method `subtensor.get_last_bonds_reset(netuid, hotkey_ss58)` ### Parameters - **netuid**: The unique identifier of the subnet. - **hotkey_ss58**: The SS58 address of the hotkey. ### Example ```python last_reset_block = subtensor.get_last_bonds_reset(netuid=1, hotkey_ss58="5D...") ``` ``` -------------------------------- ### Get Commitment Metadata (New) Source: https://github.com/latent-to/bittensor/blob/master/MIGRATION-GUIDE.md Retrieve commitment metadata using the Subtensor object. This replaces the standalone `get_metadata` function. ```python # ✅ New: metadata = subtensor.get_commitment_metadata(netuid, hotkey_ss58) ``` -------------------------------- ### Get Weights for Specific Mechanism Source: https://github.com/latent-to/bittensor/blob/master/MIGRATION-GUIDE.md Retrieve the weights for a given network and mechanism. This allows inspection of how subnet validators are weighted. ```python weights = subtensor.weights(netuid=1, mechid=0) ``` -------------------------------- ### Run E2E Tests Skipping Re-build (Legacy Runner) Source: https://github.com/latent-to/bittensor/blob/master/README.md Execute end-to-end tests with the legacy runner, skipping the re-build process. Requires setting LOCALNET_SH_PATH and BUILD_BINARY=0. ```bash BUILD_BINARY=0 LOCALNET_SH_PATH=/path/to/your/localnet.sh pytest tests/e2e_tests ``` -------------------------------- ### Example of Indicative Git Commit Subject Source: https://github.com/latent-to/bittensor/blob/master/contrib/STYLE.md Commit messages written in the indicative mood, stating facts, are less effective. ```git Fixed bug with Y ``` ```git Changing behavior of X ``` ```git More fixes for broken stuff ``` ```git Sweet new API methods ``` -------------------------------- ### Run Specific Test File Source: https://github.com/latent-to/bittensor/blob/master/contrib/TESTING.md Execute tests within a particular file, such as 'test_wallet.py'. ```bash pytest tests/test_wallet.py ``` -------------------------------- ### Register Neuron to Subnet Using Burned Registration Source: https://context7.com/latent-to/bittensor/llms.txt Register a wallet's hotkey to a subnet by burning TAO using burned_register_extrinsic. This is the standard registration method. Ensure you check the registration cost before proceeding. ```python import bittensor as bt from bittensor.core.extrinsics.registration import burned_register_extrinsic wallet = bt.wallet(name="miner", hotkey="default") sub = bt.Subtensor(network="finney") # Check registration cost recycle = sub.recycle(netuid=1) print(f"Registration cost: {recycle.tao} TAO") result = burned_register_extrinsic( subtensor=sub, wallet=wallet, netuid=1, wait_for_inclusion=True, wait_for_finalization=True, ) if result.success: print(f"Registered! UID: {result.data.get('neuron', {}).uid}") else: print(f"Failed: {result.message}") ``` -------------------------------- ### Get Timelocked Weight Commits (New) Source: https://github.com/latent-to/bittensor/blob/master/MIGRATION-GUIDE.md Retrieve timelocked weight commit information. This replaces the deprecated `get_current_weight_commit_info` and `get_current_weight_commit_info_v2` methods. ```python # ✅ Use: commits = subtensor.get_timelocked_weight_commits(netuid, mechid) ``` -------------------------------- ### Run All Bittensor Tests Source: https://github.com/latent-to/bittensor/blob/master/contrib/TESTING.md Execute all tests in the Bittensor repository. Ensure you are in the root directory. ```bash pytest ``` -------------------------------- ### Sign Commits with GPG Source: https://github.com/latent-to/bittensor/blob/master/contrib/CONTRIBUTING.md Use this command to sign individual commits. Ensure GPG signing is configured in Git. ```bash git commit -S -m "your commit message" ``` -------------------------------- ### Get Fee for Adding Stake Source: https://github.com/latent-to/bittensor/blob/master/MIGRATION-GUIDE.md Calculate the application-level swap fee for adding stake to a subnet. This method returns a Balance object. ```python # Get fee for adding stake (staking operation) fee = subtensor.get_stake_add_fee(amount, netuid) ``` -------------------------------- ### Balance Arithmetic - Balance Class Source: https://context7.com/latent-to/bittensor/llms.txt The `Balance` class handles TAO and Rao arithmetic, ensuring unit consistency. Use `from_tao` or `from_rao` for construction and standard operators for calculations. Balances for subnets require a `netuid`. ```python from bittensor.utils.balance import Balance # Construction b1 = Balance.from_tao(10.5) b2 = Balance.from_rao(500_000_000) # 0.5 TAO print(f"b1: {b1.tao} TAO ({b1.rao} Rao)") print(f"b2: {b2.tao} TAO") # Arithmetic (balances must share the same netuid for subnets) total = b1 + b2 print(f"Sum: {total.tao} TAO") diff = b1 - b2 print(f"Diff: {diff.tao} TAO") # Subnet Alpha balance (netuid=14) alpha = Balance.from_tao(5.0, netuid=14) print(f"Alpha unit: {alpha.unit}") # α14 # Comparisons print(b1 > b2) # True print(b1 == Balance.from_rao(10_500_000_000)) # True ``` -------------------------------- ### Get Bonds for Specific Mechanism Source: https://github.com/latent-to/bittensor/blob/master/MIGRATION-GUIDE.md Retrieve the bonds for a given network and mechanism. This provides information on stake amounts associated with validators. ```python bonds = subtensor.bonds(netuid=1, mechid=0) ``` -------------------------------- ### Query Neuron Info - get_neuron_for_pubkey_and_subnet / neurons_lite Source: https://context7.com/latent-to/bittensor/llms.txt Fetch individual neuron details using `get_neuron_for_pubkey_and_subnet` or retrieve a list of all neurons for a subnet with `neurons_lite`. This is useful for checking registration status and stake without loading the full metagraph. ```python import bittensor as bt sub = bt.Subtensor(network="finney") hotkey = "5FFApaS75bv5pJHfAp2FVLBj9ZaXuFDjEypsaBNc1wCfe52v" netuid = 1 # Fetch a single neuron neuron = sub.get_neuron_for_pubkey_and_subnet(hotkey_ss58=hotkey, netuid=netuid) if neuron.is_null: print("Not registered on subnet 1") else: print(f"UID: {neuron.uid}, stake: {neuron.stake}") print(f"Axon: {neuron.axon_info.ip}:{neuron.axon_info.port}") print(f"Validator permit: {neuron.validator_permit}") # Get all neurons (lite) for a subnet neurons_lite = sub.neurons_lite(netuid=1) print(f"Total neurons on subnet 1: {len(neurons_lite)}") ``` -------------------------------- ### Get Metagraph for Specific Mechanism Source: https://github.com/latent-to/bittensor/blob/master/MIGRATION-GUIDE.md Retrieve the metagraph for a given network and mechanism. This is useful for understanding network topology and validator information. ```python metagraph = subtensor.metagraph(netuid=1, mechid=0) ``` -------------------------------- ### Create a Release Branch Source: https://github.com/latent-to/bittensor/blob/master/contrib/DEVELOPMENT_WORKFLOW.md Steps to create a release branch from 'staging', update the version using a script, and commit the changes. The version can be updated to 'major' or 'minor'. ```bash git checkout -b release/3.4.0/descriptive-message/creators_name staging ./scripts/update_version.sh major|minor git commit -a -m "Updated version to 3.4.0" ``` -------------------------------- ### Get Timelocked Weight Commits for a Mechanism Source: https://github.com/latent-to/bittensor/blob/master/MIGRATION-GUIDE.md Retrieve timelocked weight commits for a specific mechanism. This is useful for tracking historical weight updates. ```python commits = subtensor.get_timelocked_weight_commits(netuid=1, mechid=0) ``` -------------------------------- ### Create Pure Proxy Account Source: https://github.com/latent-to/bittensor/wiki/Proxy-System-Overview Spawner creates a pure proxy account, which is a new account without a private key. The spawner becomes its proxy. A deposit is reserved from the spawner. ```mermaid sequenceDiagram participant S as Spawner participant Chain as On-chain participant Pure as Pure Account (no private key) S->>Chain: create_pure(proxy_type, delay, index) Note over Chain: Derive pure address deterministically
from (spawner, block_height, ext_index, proxy_type, index).
Store Proxies[pure] = [{delegate: spawner}]
Reserve deposit from spawner. Note over S: Control pure via proxy call: S->>Chain: proxy(real=pure, call=...) Chain->>Chain: Execute call as if pure account signed it Note over S: To destroy the pure account: S->>Chain: proxy(real=pure, call=kill_pure(spawner, ...)) Note over Chain: Remove Proxies[pure], return deposit to spawner Note over Pure: Permanently inaccessible.
Any funds remaining on this account are lost forever. ``` -------------------------------- ### Get Last Bonds Reset (New) Source: https://github.com/latent-to/bittensor/blob/master/MIGRATION-GUIDE.md Retrieve the last bonds reset block using the Subtensor object. This replaces the standalone `get_last_bonds_reset` function. ```python # ✅ New: last_reset = subtensor.get_last_bonds_reset(netuid, hotkey_ss58) ``` -------------------------------- ### Mechanism Weight Functions Import Paths Source: https://github.com/latent-to/bittensor/blob/master/MIGRATION-GUIDE.md Mechanism-specific weight functions have been renamed and moved. Use the new paths under `bittensor.core.extrinsics.weights`. ```python # Old paths (removed): from bittensor.core.extrinsics.mechanism import ( commit_timelocked_mechanism_weights_extrinsic, commit_mechanism_weights_extrinsic, reveal_mechanism_weights_extrinsic, ) # ✅ New paths: from bittensor.core.extrinsics.weights import ( commit_timelocked_weights_extrinsic, commit_weights_extrinsic, reveal_weights_extrinsic, set_weights_extrinsic, ) ``` -------------------------------- ### Push Master and Tags Source: https://github.com/latent-to/bittensor/blob/master/contrib/DEVELOPMENT_WORKFLOW.md Push the updated master branch and all tags to the remote origin. This makes the release available. ```bash git push origin master git push origin --tags ``` -------------------------------- ### Create a Feature Branch Source: https://github.com/latent-to/bittensor/blob/master/contrib/DEVELOPMENT_WORKFLOW.md Use this command to create a new feature branch from the 'staging' branch. Follow the naming convention 'feat//'. ```bash git checkout -b feat/mygithubname/my-feature staging ``` -------------------------------- ### Query Last Bonds Reset Block Source: https://github.com/latent-to/bittensor/blob/master/MIGRATION-GUIDE.md Get the block number when bonds were last reset for a given subnet and hotkey. This method is now part of the Subtensor class. ```python # Query when bonds were last reset (requires both netuid and hotkey_ss58) last_reset_block = subtensor.get_last_bonds_reset(netuid=1, hotkey_ss58="5D...") ``` -------------------------------- ### Search for Strings with ag Source: https://github.com/latent-to/bittensor/blob/master/contrib/DEBUGGING.md Use the 'ag' command to search for a specific string (e.g., 'query_subtensor') across your project files. The output shows file paths and line numbers where the string is found. ```bash $ ag "query_subtensor" ``` -------------------------------- ### Get Block Information by Block Hash Source: https://github.com/latent-to/bittensor/blob/master/MIGRATION-GUIDE.md Retrieve detailed information about a specific blockchain block using its hash. Includes metadata and links to block explorers. ```python # Or get block information by block hash block = subtensor.get_block_info(block_hash="0x1234...") ``` -------------------------------- ### Removal of Deprecated `set_root_weights_extrinsic` Source: https://github.com/latent-to/bittensor/blob/master/MIGRATION-GUIDE.md The `set_root_weights_extrinsic` method has been removed as it was obsolete. ```python # ❌ Removed: subtensor.set_root_weights_extrinsic(...) ``` -------------------------------- ### Async Methods Parity Source: https://github.com/latent-to/bittensor/blob/master/MIGRATION-GUIDE.md Async methods now accept the same parameters as their synchronous counterparts, including `block_hash` and `reuse_block`. ```python # New parameters added to async versions: async_subtensor.get_subnet_validator_permits(netuid, block_hash=None, reuse_block=None) async_subtensor.get_subnet_owner_hotkey(netuid, block_hash=None, reuse_block=None) ``` -------------------------------- ### Stake and Unstake TAO - add_stake_extrinsic / unstake_extrinsic Source: https://context7.com/latent-to/bittensor/llms.txt Use `add_stake_extrinsic` to stake TAO onto a subnet and `unstake_extrinsic` to remove it. Ensure `wait_for_inclusion` and `wait_for_finalization` are set for reliable transaction confirmation. ```python result = add_stake_extrinsic( subtensor=sub, wallet=wallet, hotkey_ss58=hotkey, netuid=1, amount=Balance.from_tao(10), wait_for_inclusion=True, wait_for_finalization=True, ) print(f"Stake added: {result.success}") # Check new stake stake = sub.get_stake( hotkey_ss58=hotkey, coldkey_ss58=wallet.coldkeypub.ss58_address, netuid=1, ) print(f"Current stake: {stake.tao} Alpha") # Unstake 5 TAO worth of Alpha result = unstake_extrinsic( subtensor=sub, wallet=wallet, hotkey_ss58=hotkey, netuid=1, amount=Balance.from_tao(5), allow_partial_stake=True, ) print(f"Unstake result: {result.success}, message: {result.message}") ``` -------------------------------- ### Get Block Information by Block Number Source: https://github.com/latent-to/bittensor/blob/master/MIGRATION-GUIDE.md Retrieve detailed information about a specific blockchain block using its block number. Includes metadata and links to block explorers. ```python from bittensor.core.types import BlockInfo # Get block information by block number block = subtensor.get_block_info(block=12345) ```