bittensor.core.async_subtensor#
Classes#
Asynchronous interface for interacting with the Bittensor blockchain. |
Functions#
|
Factory method to create an initialized AsyncSubtensor instance. |
Module Contents#
- class bittensor.core.async_subtensor.AsyncSubtensor(network=None, config=None, log_verbose=False, fallback_endpoints=None, retry_forever=False, archive_endpoints=None, websocket_shutdown_timer=5.0, mock=False)[source]#
Bases:
bittensor.core.types.SubtensorMixinAsynchronous interface for interacting with the Bittensor blockchain.
This class provides a thin layer over the Substrate Interface offering async functionality for Bittensor. This includes frequently-used calls for querying blockchain data, managing stakes and liquidity positions, registering neurons, submitting weights, and many other functions for participating in Bittensor.
Notes
Key Bittensor concepts used throughout this class:
Coldkey: The key pair corresponding to a user’s overall wallet. Used to transfer, stake, manage subnets.
Hotkey: A key pair (each wallet may have zero, one, or more) used for neuron operations (mining and validation).
Netuid: Unique identifier for a subnet (0 is the Root Subnet)
UID: Unique identifier for a neuron registered to a hotkey on a specific subnet.
Metagraph: Data structure containing the complete state of a subnet at a block.
TAO: The base network token; subnet 0 stake is in TAO
Alpha: Subnet-specific token representing some quantity of TAO staked into a subnet.
Rao: Smallest unit of TAO (1 TAO = 1e9 Rao)
Bittensor Glossary <https://docs.learnbittensor.org/glossary>
Wallets, Coldkeys and Hotkeys in Bittensor <https://docs.learnbittensor.org/keys/wallets>
Initializes an AsyncSubtensor instance for blockchain interaction.
- Parameters:
network (Optional[str]) – The network name to connect to (e.g.,
"finney"for Bittensor mainnet,"test", for Bittensor test network,"local"for a locally deployed blockchain). IfNone, uses the default network from config.config (Optional[bittensor.core.config.Config]) – Configuration object for the AsyncSubtensor instance. If
None, uses the default configuration.log_verbose (bool) – Enables or disables verbose logging.
fallback_endpoints (Optional[list[str]]) – List of fallback WebSocket endpoints to use if the primary network endpoint is unavailable. These are tried in order when the default endpoint fails.
retry_forever (bool) – Whether to retry connection attempts indefinitely on connection errors.
mock (bool) – Whether this is a mock instance. FOR TESTING ONLY.
archive_endpoints (Optional[list[str]]) – List of archive node endpoints for queries requiring historical block data beyond the retention period of lite nodes. These are only used when requesting blocks that the current node is unable to serve.
websocket_shutdown_timer (Optional[float]) – Amount of time (in seconds) to wait after the last response from the chain before automatically closing the WebSocket connection. Pass
Noneto disable automatic shutdown entirely.
- Returns:
None
- async add_liquidity(wallet, netuid, liquidity, price_low, price_high, hotkey_ss58=None, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)[source]#
Adds liquidity to the specified price range.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet used to sign the extrinsic (must be unlocked).
netuid (int) – The UID of the target subnet for which the call is being initiated.
liquidity (bittensor.utils.balance.Balance) – The amount of liquidity to be added.
price_low (bittensor.utils.balance.Balance) – The lower bound of the price tick range. In TAO.
price_high (bittensor.utils.balance.Balance) – The upper bound of the price tick range. In TAO.
hotkey_ss58 (Optional[str]) – The hotkey with staked TAO in Alpha. If not passed then the wallet hotkey is used.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Whether to wait for the extrinsic to be included in a block.
wait_for_finalization (bool) – Whether to wait for finalization of the extrinsic.
- Returns:
The result object of the extrinsic execution.
- Return type:
Note
Adding is allowed even when user liquidity is enabled in specified subnet. Call
toggle_user_liquiditymethod to enable/disable user liquidity.
- async add_proxy(wallet, delegate_ss58, proxy_type, delay, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)#
Adds a proxy relationship.
This method creates a proxy relationship where the delegate can execute calls on behalf of the real account (the wallet owner) with restrictions defined by the proxy type and a delay period. A deposit is required and held as long as the proxy relationship exists.
- Parameters:
wallet (bittensor_wallet.Wallet) – Bittensor wallet object.
delegate_ss58 (str) – The SS58 address of the delegate proxy account.
proxy_type (Union[str, bittensor.core.chain_data.ProxyType]) – The type of proxy permissions (e.g., “Any”, “NonTransfer”, “Governance”, “Staking”). Can be a string or ProxyType enum value. For available proxy types and their permissions, see the documentation link in the Notes section below.
delay (int) – Optionally, include a delay in blocks. The number of blocks that must elapse between announcing and executing a proxied transaction. A delay of
0means the proxy can be used immediately without announcements. A non-zero delay creates a time-lock, requiring the proxy to announce calls viaannounce_proxy()before execution, giving the real account time to review and reject unwanted operations viareject_proxy_announcement().period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Whether to wait for the inclusion of the transaction.
wait_for_finalization (bool) – Whether to wait for the finalization of the transaction.
- Returns:
The result object of the extrinsic execution.
- Return type:
Notes
A deposit is required when adding a proxy. The deposit amount is determined by runtime constants and is returned when the proxy is removed. Use
get_proxy_constants()to check current deposit requirements.For available proxy types and their specific permissions, see: <https://docs.learnbittensor.org/keys/proxies#types-of-proxies>
Bittensor proxies: <https://docs.learnbittensor.org/keys/proxies/create-proxy>
Warning
The
"Any"proxy type is dangerous as it grants full permissions to the proxy, including the ability to make transfers and manage the account completely. Use with extreme caution.
- async add_stake(wallet, netuid, hotkey_ss58, amount, safe_staking=False, allow_partial_stake=False, rate_tolerance=0.005, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)[source]#
Adds a stake from the specified wallet to the neuron identified by the SS58 address of its hotkey in specified subnet. Staking is a fundamental process in the Bittensor network that enables neurons to participate actively and earn incentives.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet to be used for staking.
netuid (int) – The unique identifier of the subnet to which the neuron belongs.
hotkey_ss58 (str) – The ss58 address of the hotkey account to stake to default to the wallet’s hotkey.
amount (bittensor.utils.balance.Balance) – The amount of TAO to stake.
safe_staking (bool) – If true, enables price safety checks to protect against fluctuating prices. The stake will only execute if the price change doesn’t exceed the rate tolerance.
allow_partial_stake (bool) – If true and safe_staking is enabled, allows partial staking when the full amount would exceed the price tolerance. If false, the entire stake fails if it would exceed the tolerance.
rate_tolerance (float) – The maximum allowed price change ratio when staking. For example, 0.005 = 0.5% maximum price increase. Only used when safe_staking is True.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Whether to wait for the extrinsic to be included in a block.
wait_for_finalization (bool) – Whether to wait for finalization of the extrinsic.
- Returns:
The result object of the extrinsic execution.
- Return type:
This function enables neurons to increase their stake in the network, enhancing their influence and potential. When safe_staking is enabled, it provides protection against price fluctuations during the time stake is executed and the time it is actually processed by the chain.
Notes
Price Protection: <https://docs.learnbittensor.org/learn/price-protection>
Rate Limits: <https://docs.learnbittensor.org/learn/chain-rate-limits#staking-operations-rate-limits>
- async add_stake_multiple(wallet, netuids, hotkey_ss58s, amounts, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)[source]#
Adds stakes to multiple neurons identified by their hotkey SS58 addresses. This bulk operation allows for efficient staking across different neurons from a single wallet.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet used for staking.
netuids (bittensor.core.types.UIDs) – List of subnet UIDs.
hotkey_ss58s (list[str]) – List of
SS58addresses of hotkeys to stake to.amounts (list[bittensor.utils.balance.Balance]) – List of corresponding TAO amounts to bet for each netuid and hotkey.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Waits for the transaction to be included in a block.
wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain.
- Returns:
The result object of the extrinsic execution.
- Return type:
Notes
Price Protection: <https://docs.learnbittensor.org/learn/price-protection>
Rate Limits: <https://docs.learnbittensor.org/learn/chain-rate-limits#staking-operations-rate-limits>
- async all_subnets(block=None, block_hash=None, reuse_block=False)[source]#
Queries the blockchain for comprehensive information about all subnets, including their dynamic parameters and operational status.
- Parameters:
block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
A list of
DynamicInfoobjects, each containing detailed information about a subnet, or None if the query fails.- Return type:
Optional[list[DynamicInfo]]
- async announce_proxy(wallet, real_account_ss58, call_hash, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)#
Announces a future call that will be executed through a proxy.
This method allows a proxy account to declare its intention to execute a specific call on behalf of a real account after a delay period. The real account can review and either approve (via
proxy_announced()) or reject (viareject_proxy_announcement()) the announcement.- Parameters:
wallet (bittensor_wallet.Wallet) – Bittensor wallet object (should be the proxy account wallet).
real_account_ss58 (str) – The SS58 address of the real account on whose behalf the call will be made.
call_hash (str) – The hash of the call that will be executed in the future.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Whether to wait for the inclusion of the transaction.
wait_for_finalization (bool) – Whether to wait for the finalization of the transaction.
- Returns:
The result object of the extrinsic execution.
- Return type:
Notes
A deposit is required when making an announcement. The deposit is returned when the announcement is executed, rejected, or removed. The announcement can be executed after the delay period has passed.
Bittensor proxies: <https://docs.learnbittensor.org/keys/proxies>
- property block#
Provides an asynchronous getter to retrieve the current block number.
- Returns:
The current blockchain block number.
- async blocks_since_last_step(netuid, block=None, block_hash=None, reuse_block=False)[source]#
Queries the blockchain to determine how many blocks have passed since the last epoch step for a specific subnet.
- Parameters:
netuid (int) – The unique identifier of the subnetwork.
block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
The number of blocks since the last step in the subnet, or None if the query fails.
- Return type:
Optional[int]
- async blocks_since_last_update(netuid, uid, block=None, block_hash=None, reuse_block=False)[source]#
Returns the number of blocks since the last update, or
Noneif the subnetwork or UID does not exist.- Parameters:
netuid (int) – The unique identifier of the subnetwork.
uid (int) – The unique identifier of the neuron.
block (Optional[int]) – The block number for this query. Do not specify if using block_hash or reuse_block.
block_hash (Optional[str]) – The hash of the block for the query. Do not specify if using reuse_block or block.
reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
The number of blocks since the last update, or None if the subnetwork or UID does not exist.
- Return type:
Optional[int]
- async blocks_until_next_epoch(netuid, tempo=None, block=None, block_hash=None, reuse_block=False)#
Returns the number of blocks until the next epoch of subnet with provided netuid.
- Parameters:
netuid (int) – The unique identifier of the subnetwork.
tempo (Optional[int]) – The tempo of the subnet.
block (Optional[int]) – The block number to query. Do not specify if using block_hash or reuse_block.
block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using block or reuse_block.
reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using block_hash or block.
- Returns:
The number of blocks until the next epoch of the subnet with provided netuid.
- Return type:
Optional[int]
- async bonds(netuid, mechid=0, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves the bond distribution set by subnet validators within a specific subnet.
Bonds represent a validator’s accumulated assessment of each miner’s performance over time, which serves as the starting point of Yuma Consensus.
- Parameters:
netuid (int) – Subnet identifier.
mechid (int) – Subnet mechanism identifier (default 0 for primary mechanism).
block (Optional[int]) – The block number for this query. Do not specify if using block_hash or reuse_block.
block_hash (Optional[str]) – The hash of the block for the query. Do not specify if using reuse_block or block.
reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
- validator_uid: The UID of the validator
bonds: List of (miner_uid, bond_value) pairs
Bond values are u16-normalized (0-65535, where 65535 = 1.0 or 100%).
- Return type:
List of tuples, where each tuple contains
Example:
# Get bonds for subnet 1 bonds = await subtensor.bonds(netuid=1) print(bonds[0]) # example output: (5, [(0, 32767), (1, 16383), (3, 8191)]) # This means validator UID 5 has bonds: 50% to miner 0, 25% to miner 1, 12.5% to miner 3
- async burned_register(wallet, netuid, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)[source]#
Registers a neuron on the Bittensor network by recycling TAO. This method of registration involves recycling TAO tokens, allowing them to be re-mined by performing work on the network.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet associated with the neuron to be registered.
netuid (int) – The unique identifier of the subnet.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Waits for the transaction to be included in a block.
wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain.
- Returns:
The result object of the extrinsic execution.
- Return type:
Notes
- async claim_root(wallet, netuids, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)#
Submit an extrinsic to manually claim accumulated root dividends from one or more subnets.
- Parameters:
wallet (bittensor_wallet.Wallet) – Bittensor
Walletinstance.netuids (bittensor.core.types.UIDs) – Iterable of subnet IDs to claim from in this call (the chain enforces a maximum number per transaction).
period (Optional[int]) – Number of blocks during which the transaction remains valid after submission. If the extrinsic is not included in a block within this window, it will expire and be rejected.
raise_error (bool) – Whether to raise a Python exception instead of returning a failed
ExtrinsicResponse.wait_for_inclusion (bool) – Whether to wait until the extrinsic is included in a block before returning.
wait_for_finalization (bool) – Whether to wait for finalization of the extrinsic in a block before returning.
- Returns:
ExtrinsicResponsedescribing the result of the extrinsic execution.
Notes
Only Alpha dividends are claimed; the underlying TAO stake on the Root Subnet remains unchanged.
The current root claim type (
"Swap"or"Keep") determines whether claimed Alpha is converted to TAO and restaked on root or left as Alpha on the originating subnets.See: <https://docs.learnbittensor.org/staking-and-delegation/root-claims>
See also: <https://docs.learnbittensor.org/staking-and-delegation/root-claims/managing-root-claims>
Transaction fees: <https://docs.learnbittensor.org/learn/fees>
- async close()[source]#
Closes the connection to the blockchain.
Use this to explicitly clean up resources and close the network connection instead of waiting for garbage collection.
- Returns:
None
Example:
sub = bt.AsyncSubtensor(network="finney") # Initialize the connection await subtensor.initialize() # calls to subtensor await subtensor.close()
- async commit_reveal_enabled(netuid, block=None, block_hash=None, reuse_block=False)[source]#
Check if commit-reveal mechanism is enabled for a given subnet at a specific block.
- Parameters:
netuid (int) – The unique identifier of the subnet for which to check the commit-reveal mechanism.
block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
True if commit-reveal mechanism is enabled, False otherwise.
- Return type:
- async commit_weights(wallet, netuid, salt, uids, weights, mechid=0, version_key=version_as_int, max_attempts=5, period=16, raise_error=True, wait_for_inclusion=False, wait_for_finalization=False)[source]#
Commits a hash of the subnet validator’s weight vector to the Bittensor blockchain using the provided wallet. This action serves as a commitment or snapshot of the validator’s current weight distribution.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet associated with the neuron committing the weights.
netuid (int) – The unique identifier of the subnet.
salt (bittensor.core.types.Salt) – list of randomly generated integers as salt to generated weighted hash.
uids (bittensor.core.types.UIDs) – NumPy array of neuron UIDs for which weights are being committed.
weights (bittensor.core.types.Weights) – NumPy array of weight values corresponding to each UID.
mechid (int) – The subnet mechanism unique identifier.
version_key (int) – Version key for compatibility with the network.
max_attempts (int) – The number of maximum attempts to commit weights.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Whether to wait for the extrinsic to be included in a block.
wait_for_finalization (bool) – Whether to wait for finalization of the extrinsic.
- Returns:
The result object of the extrinsic execution.
- Return type:
This function allows subnet validators to create a tamper-proof record of their weight vector at a specific point in time, creating a foundation of transparency and accountability for the Bittensor network.
- async compose_call(call_module, call_function, call_params, block=None, block_hash=None, reuse_block=False)#
Dynamically compose a GenericCall using on-chain Substrate metadata after validating the provided parameters.
- Parameters:
call_module (str) – Pallet name (e.g. “SubtensorModule”, “AdminUtils”).
call_function (str) – Function name (e.g. “set_weights”, “sudo_set_tempo”).
call_params (dict[str, Any]) – Dictionary of parameters for the call.
block (Optional[int]) – The blockchain block number for the query.
block_hash (Optional[str]) – The blockchain block_hash representation of the block id.
reuse_block (bool) – Whether to reuse the last-used blockchain block hash.
- Returns:
Composed call object ready for extrinsic submission.
- Return type:
GenericCall
# TODO: document whole extrinsic flow
- async contribute_crowdloan(wallet, crowdloan_id, amount, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)#
Contributes TAO to an active crowdloan campaign.
Contributions must occur before the crowdloan’s end block and are subject to minimum contribution requirements. If a contribution would push the total raised above the cap, it is automatically clipped to fit the remaining amount. Once the cap is reached, further contributions are rejected.
- Parameters:
wallet (bittensor_wallet.Wallet) – Bittensor wallet instance used to sign the transaction (coldkey pays, coldkey receives emissions).
crowdloan_id (int) – The unique identifier of the crowdloan to contribute to.
amount (bittensor.utils.balance.Balance) – Amount to contribute (TAO). Must meet or exceed the campaign’s
min_contribution.period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted.
raise_error (bool) – If
True, raises an exception rather than returning failure in the response.wait_for_inclusion (bool) – Whether to wait for the extrinsic to be included in a block.
wait_for_finalization (bool) – Whether to wait for finalization of the extrinsic.
- Returns:
ExtrinsicResponseindicating success or failure, with error details if applicable.- Return type:
Notes
Contributions can be withdrawn before finalization via
withdraw_crowdloan.If the campaign does not reach its cap by the end block, contributors can be refunded via
refund_crowdloan.Contributions are counted toward
MaxContributorslimit per crowdloan.Crowdloans Overview: <https://docs.learnbittensor.org/subnets/crowdloans>
Crowdloan Tutorial: <https://docs.learnbittensor.org/subnets/crowdloans/crowdloans-tutorial#step-4-contribute-to-the-crowdloan>
- async create_crowdloan(wallet, deposit, min_contribution, cap, end, call=None, target_address=None, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)#
Creates a new crowdloan campaign on-chain.
- Parameters:
wallet (bittensor_wallet.Wallet) – Bittensor Wallet instance used to sign the transaction.
deposit (bittensor.utils.balance.Balance) – Initial deposit in RAO from the creator.
min_contribution (bittensor.utils.balance.Balance) – Minimum contribution amount.
cap (bittensor.utils.balance.Balance) – Maximum cap to be raised.
end (int) – Block number when the campaign ends.
call (Optional[scalecodec.GenericCall]) – Runtime call data (e.g., subtensor::register_leased_network).
target_address (Optional[str]) – SS58 address to transfer funds to on success.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Whether to wait for the extrinsic to be included in a block.
wait_for_finalization (bool) – Whether to wait for finalization of the extrinsic.
- Returns:
ExtrinsicResponseindicating success or failure. On success, the crowdloan ID can be extracted from theCrowdloan.Createdevent in the response.- Return type:
Notes
Creator cannot update
callortarget_addressafter creation.Creator can update
cap,end, andmin_contributionbefore finalization viaupdate_*methods.Use
get_crowdloan_next_idto determine the ID that will be assigned to the new crowdloan.Crowdloans Overview: <https://docs.learnbittensor.org/subnets/crowdloans>
Crowdloan Tutorial: <https://docs.learnbittensor.org/subnets/crowdloans/crowdloans-tutorial#step-3-create-a-crowdloan>
- async create_pure_proxy(wallet, proxy_type, delay, index, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)#
Creates a pure proxy account.
A pure proxy is a keyless account that can only be controlled through proxy relationships. Unlike regular proxies, pure proxies do not have their own private keys, making them more secure for certain use cases. The pure proxy address is deterministically generated based on the spawner account, proxy type, delay, and index.
- Parameters:
wallet (bittensor_wallet.Wallet) – Bittensor wallet object.
proxy_type (Union[str, bittensor.core.chain_data.ProxyType]) – The type of proxy permissions for the pure proxy. Can be a string or ProxyType enum value. For available proxy types and their permissions, see the documentation link in the Notes section below.
delay (int) – Optionally, include a delay in blocks. The number of blocks that must elapse between announcing and executing a proxied transaction. A delay of
0means the pure proxy can be used immediately without any announcement period. A non-zero delay creates a time-lock, requiring announcements before execution to give the spawner time to review/reject.index (int) – A salt value (u16, range
0-65535) used to generate unique pure proxy addresses. This should generally be left as0unless you are creating batches of proxies. When creating multiple pure proxies with identical parameters (sameproxy_typeanddelay), different index values will produce different SS58 addresses. This is not a sequential counter—you can use any unique values (e.g., 0, 100, 7, 42) in any order. The index must be preserved as it’s required forkill_pure_proxy(). If creating multiple pure proxies in a single batch transaction, each must have a unique index value.period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Whether to wait for the inclusion of the transaction.
wait_for_finalization (bool) – Whether to wait for the finalization of the transaction.
- Returns:
The result object of the extrinsic execution.
- Return type:
Notes
The pure proxy account address can be extracted from the “PureCreated” event in the response. Store the spawner address, proxy_type, index, height, and ext_index as they are required to kill the pure proxy later via
kill_pure_proxy().For available proxy types and their specific permissions, see: <https://docs.learnbittensor.org/keys/proxies#types-of-proxies>
Bittensor proxies: <https://docs.learnbittensor.org/keys/proxies/pure-proxies>
Warning
The
"Any"proxy type is dangerous as it grants full permissions to the proxy, including the ability to make transfers and kill the proxy. Use with extreme caution.
- async determine_block_hash(block=None, block_hash=None, reuse_block=False)[source]#
Determine the block hash for the block specified with the provided parameters.
Ensures that only one of the block specification parameters is used and returns the appropriate block hash for blockchain queries.
- Parameter precedence (in order):
If
reuse_block=Trueandblockorblock_hashis set → raises ValueErrorIf both
blockandblock_hashare set → validates they match, raises ValueError if notIf only
block_hashis set → returns it directlyIf only
blockis set → fetches and returns its hashIf none are set → returns
None
- Parameters:
block (Optional[int]) – The block number to get the hash for. If specifying along with
block_hash, the hash ofblockwill be checked and compared with the supplied block hash, raising a ValueError if the two do not match.block_hash (Optional[str]) – The hash of the blockchain block (hex string prefixed with
0x). If specifying along withblock, the hash ofblockwill be checked and compared with the supplied block hash, raising a ValueError if the two do not match.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
blockorblock_hash.
- Returns:
The block hash (hex string with
0xprefix) if one can be determined,Noneotherwise.- Return type:
Optional[str]
- async difficulty(netuid, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves the ‘Difficulty’ hyperparameter for a specified subnet in the Bittensor network.
- This parameter determines the computational challenge required for neurons to participate in consensus and
validation processes, using proof of work (POW) registration.
- Parameters:
netuid (int) – The unique identifier of the subnet.
block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
The value of the ‘Difficulty’ hyperparameter if the subnet exists,
Noneotherwise.- Return type:
Optional[int]
Notes
Burn registration is much more common on Bittensor subnets currently, compared to POW registration.
- async dissolve_crowdloan(wallet, crowdloan_id, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)#
Dissolves a failed or refunded crowdloan, cleaning up storage and returning the creator’s deposit.
This permanently removes the crowdloan from on-chain storage and returns the creator’s deposit. Can only be called by the creator after all non-creator contributors have been refunded via
refund_crowdloan. This is the final step in the lifecycle of a failed crowdloan (one that did not reach its cap by the end block).- Parameters:
wallet (bittensor_wallet.Wallet) – Bittensor wallet instance used to sign the transaction (must be the creator’s coldkey).
crowdloan_id (int) – The unique identifier of the crowdloan to dissolve.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after submission.
raise_error (bool) – If
True, raises an exception rather than returning failure in the response.wait_for_inclusion (bool) – Whether to wait for the extrinsic to be included in a block.
wait_for_finalization (bool) – Whether to wait for finalization of the extrinsic.
- Returns:
ExtrinsicResponseindicating success or failure, with error details if applicable.- Return type:
Notes
Only the creator can dissolve their own crowdloan.
All non-creator contributors must be refunded first via
refund_crowdloan.The creator’s deposit (and any remaining contribution above deposit) is returned.
After dissolution, the crowdloan is permanently removed from chain storage.
Crowdloans Overview: <https://docs.learnbittensor.org/subnets/crowdloans>
Refund and Dissolve: <https://docs.learnbittensor.org/subnets/crowdloans/crowdloans-tutorial#alternative-path-refund-and-dissolve>
- async does_hotkey_exist(hotkey_ss58, block=None, block_hash=None, reuse_block=False)[source]#
Returns true if the hotkey has been associated with a coldkey through account creation.
This method queries the Subtensor’s Owner storage map to check if the hotkey has been paired with a coldkey, as it must be before it (the hotkey) can be used for neuron registration.
The Owner storage map defaults to the zero address (
5C4hrfjw9DjXZTzV3MwzrrAr9P1MJhSrvWGWqi1eSuyUpnhM) for unused hotkeys. This method returnsTrueif the Owner value is anything other than this default.- Parameters:
hotkey_ss58 (str) – The SS58 address of the hotkey.
block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
True if the hotkey has been associated with a coldkey, False otherwise.
- Return type:
- async filter_netuids_by_registered_hotkeys(all_netuids, filter_for_netuids, all_hotkeys, block=None, block_hash=None, reuse_block=False)[source]#
Filters a given list of all netuids for certain specified netuids and hotkeys
- # TODO @roman I find this confusing, what is the difference between all_netuids and filter_for_netuids? what is the intent for this method’s
- Parameters:
all_netuids: A list of netuids to filter. filter_for_netuids: A subset of all_netuids to filter from the main list. all_hotkeys: Hotkeys to filter from the main list. block: The blockchain block number for the query. block_hash: hash of the blockchain block number at which to perform the query. reuse_block: whether to reuse the last-used blockchain hash when retrieving info.
- Returns:
The filtered list of netuids.
- async finalize_crowdloan(wallet, crowdloan_id, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)#
Finalizes a successful crowdloan after the cap is fully raised and the end block has passed.
Finalization executes the stored call (e.g.,
register_leased_network) or transfers raised funds to the target address. For subnet lease crowdloans, this registers the subnet, creates aSubnetLeaseBeneficiaryproxy for the creator, and records contributor shares for pro-rata emissions distribution. Leftover funds (after registration and proxy costs) are refunded to contributors.Only the creator can finalize, and finalization can only occur after both the end block is reached and the total raised equals the cap.
- Parameters:
wallet (bittensor_wallet.Wallet) – Bittensor wallet instance used to sign the transaction (must be the creator’s coldkey).
crowdloan_id (int) – The unique identifier of the crowdloan to finalize.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after submission.
raise_error (bool) – If
True, raises an exception rather than returning failure in the response.wait_for_inclusion (bool) – Whether to wait for the extrinsic to be included in a block.
wait_for_finalization (bool) – Whether to wait for finalization of the extrinsic.
- Returns:
ExtrinsicResponseindicating success or failure. On success, a subnet lease is created (if applicable) and contributor shares are recorded for emissions.- Return type:
Notes
Only the creator can finalize.
Finalization requires
raised == capandcurrent_block >= end.For subnet leases, emissions are swapped to TAO and distributed to contributors’ coldkeys during the lease.
Leftover cap (after subnet lock + proxy deposit) is refunded to contributors pro-rata.
Crowdloans Overview: <https://docs.learnbittensor.org/subnets/crowdloans>
Crowdloan Tutorial: <https://docs.learnbittensor.org/subnets/crowdloans/crowdloans-tutorial#step-5-finalize-the-crowdloan>
Emissions Distribution: <https://docs.learnbittensor.org/subnets/crowdloans#emissions-distribution-during-a-lease>
- async get_admin_freeze_window(block=None, block_hash=None, reuse_block=False)#
Returns the duration, in blocks, of the administrative freeze window at the end of each epoch.
The admin freeze window is a period at the end of each epoch during which subnet owner operations are prohibited. This prevents subnet owners from modifying hyperparameters or performing certain administrative actions right before validators submit weights at the epoch boundary.
- Parameters:
block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
10 blocks, ~2 minutes).
- Return type:
The number of blocks in the administrative freeze window (default
- async get_all_commitments(netuid, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves raw commitment metadata from a given subnet.
This method retrieves all commitment data for all neurons in a specific subnet. This is useful for analyzing the commit-reveal patterns across an entire subnet.
- Parameters:
netuid (int) – The unique identifier of the subnetwork.
block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
commitment with the commitment as a string.
- Return type:
A mapping of the ss58
Example:
# TODO add example of how to handle realistic commitment data
- async get_all_ema_tao_inflow(block=None, block_hash=None, reuse_block=False)#
Retrieves the EMA (exponential moving average) of net TAO flows for all subnets.
The EMA tracks net TAO flows (staking minus unstaking) with a 30-day half-life (~86.8 day window), smoothing out short-term fluctuations while capturing sustained staking trends. This metric determines the subnet’s share of TAO emissions under the current, flow-based model. Positive values indicate net inflow (more staking than unstaking), negative values indicate net outflow. Subnets with negative EMA flows receive zero emissions.
- Parameters:
block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
Dict mapping netuid to (last_updated_block, ema_flow). The Balance represents the EMA of net TAO flow in TAO units. Positive values indicate sustained net inflow, negative values indicate sustained net outflow.
- Return type:
The EMA uses a smoothing factor α ≈ 0.000003209, creating a 30-day half-life and ~86.8 day window. Only direct stake/unstake operations count toward flows; neuron registrations and root claims are excluded. Subnet 0 (root network) does not have an EMA TAO flow value.
Notes
Flow-based emissions: <https://docs.learnbittensor.org/learn/emissions#tao-reserve-injection>
EMA smoothing: <https://docs.learnbittensor.org/learn/ema>
- async get_all_metagraphs_info(all_mechanisms=False, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves a list of MetagraphInfo objects for all subnets
- Parameters:
all_mechanisms (bool) – If True then returns all mechanisms, otherwise only those with index 0 for all subnets.
block (Optional[int]) – The blockchain block number for the query.
block_hash (Optional[str]) – The hash of the blockchain block number at which to perform the query.
reuse_block (bool) – Whether to reuse the last-used block hash when retrieving info.
- Returns:
List of MetagraphInfo objects for all existing subnets.
- Return type:
Optional[list[bittensor.core.chain_data.MetagraphInfo]]
- async get_all_neuron_certificates(netuid, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves the TLS certificates for neurons within a specified subnet (netuid) of the Bittensor network.
- Parameters:
netuid (int) – The unique identifier of the subnet.
block (Optional[int]) – The blockchain block number for the query.
block_hash (Optional[str]) – The hash of the block to retrieve the parameter from. Do not specify if using
blockorreuse_block.reuse_block (bool) – Whether to use the last-used block. Do not set if using
block_hashorblock.
- Returns:
Dictionary mapping neuron hotkey SS58 addresses to their Certificate objects. Only includes neurons that have registered certificates.
- Return type:
Notes
This method is used for certificate discovery to establish mutual TLS communication between neurons. - <https://docs.learnbittensor.org/subnets/neuron-tls-certificates>
- async get_all_revealed_commitments(netuid, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves all revealed commitments for a given subnet.
- Parameters:
netuid (int) – The unique identifier of the subnetwork.
block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
A dictionary mapping hotkey addresses to tuples of (reveal_block, commitment_message) pairs. Each validator can have multiple revealed commitments (up to 10 most recent).
- Return type:
Example:
{ "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY": ( (12, "Alice message 1"), (152, "Alice message 2") ), "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty": ( (12, "Bob message 1"), (147, "Bob message 2") ), }
- async get_all_subnets_info(block=None, block_hash=None, reuse_block=False)[source]#
Retrieves detailed information about all subnets within the Bittensor network.
- Parameters:
block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
A list of SubnetInfo objects, each containing detailed information about a subnet.
- Return type:
list[bittensor.core.chain_data.SubnetInfo]
- async get_all_subnets_netuid(block=None, block_hash=None, reuse_block=False)#
Retrieves the list of all subnet unique identifiers (netuids) currently present in the Bittensor network.
- Parameters:
- Returns:
A list of subnet netuids.
- Return type:
This function provides a comprehensive view of the subnets within the Bittensor network, offering insights into its diversity and scale.
- async get_auto_stakes(coldkey_ss58, block=None, block_hash=None, reuse_block=False)#
Fetches auto stake destinations for a given wallet across all subnets.
- Parameters:
- Returns:
netuid: The unique identifier of the subnet.
hotkey: The hotkey of the wallet.
- Return type:
Dictionary mapping netuid to hotkey, where
- async get_balance(address, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves the balance for given coldkey.
This method queries the System module’s Account storage to get the current balance of a coldkey address. The balance represents the amount of TAO tokens held by the specified address.
- Parameters:
address (str) – The coldkey address in SS58 format.
block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
The balance object containing the account’s TAO balance.
- Return type:
- async get_balances(*addresses, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves the balance for given coldkey(s).
This method efficiently queries multiple coldkey addresses in a single batch operation, returning a dictionary mapping each address to its corresponding balance. This is more efficient than calling get_balance multiple times.
- Parameters:
*addresses (str) – Variable number of coldkey addresses in SS58 format.
block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
A dictionary mapping each address to its Balance object.
- Return type:
- async get_block_hash(block=None)[source]#
Retrieves the hash of a specific block on the Bittensor blockchain.
The block hash is a unique identifier representing the cryptographic hash of the block’s content, ensuring its integrity and immutability. It is a fundamental aspect of blockchain technology, providing a secure reference to each block’s data. It is crucial for verifying transactions, ensuring data consistency, and maintaining the trustworthiness of the blockchain.
- async get_block_info(block=None, block_hash=None)#
Retrieve complete information about a specific block from the Subtensor chain.
This method aggregates multiple low-level RPC calls into a single structured response, returning both the raw on-chain data and high-level decoded metadata for the given block.
- Parameters:
- Returns:
A dataclass containing all available information about the specified block, including:
number: The block number.
hash: The corresponding block hash.
timestamp: The timestamp of the block (based on the Timestamp.Now extrinsic).
header: The raw block header returned by the node RPC.
extrinsics: The list of decoded extrinsics included in the block.
explorer: The link to block explorer service. Always related with finney block data.
- Return type:
BlockInfo instance
- async get_children(hotkey_ss58, netuid, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves the children of a given hotkey and netuid.
This method queries the SubtensorModule’s ChildKeys storage function to get the children and formats them before returning as a tuple. It provides information about the child neurons that a validator has set for weight distribution.
- Parameters:
hotkey_ss58 (str) – The hotkey value.
netuid (int) – The netuid value.
block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
- A tuple containing a boolean indicating success or failure, a list of formatted children with their
proportions, and an error message (if applicable).
- Return type:
Example:
# Get children for a hotkey in subnet 1 success, children, error = await subtensor.get_children(hotkey="5F...", netuid=1) if success: for proportion, child_hotkey in children: print(f"Child {child_hotkey}: {proportion}")
- async get_children_pending(hotkey_ss58, netuid, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves the pending children of a given hotkey and netuid.
This method queries the SubtensorModule’s PendingChildKeys storage function to get children that are pending approval or in a cooldown period. These are children that have been proposed but not yet finalized.
- Parameters:
hotkey_ss58 (str) – The hotkey value.
netuid (int) – The netuid value.
block (Optional[int]) – The block number for which the children are to be retrieved.
block_hash (Optional[str]) – The hash of the block to retrieve the subnet unique identifiers from.
reuse_block (bool) – Whether to reuse the last-used block hash.
- Returns:
A tuple containing:
list[tuple[float, str]]: A list of children with their proportions.
int: The cool-down block number.
- Return type:
- async get_commitment(netuid, uid, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves the on-chain commitment for a specific neuron in the Bittensor network.
This method retrieves the commitment data that a neuron has published to the blockchain. Commitments are used in the commit-reveal mechanism for secure weight setting and other network operations.
- Parameters:
netuid (int) – The unique identifier of the subnetwork.
uid (int) – The unique identifier of the neuron.
block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
The commitment data as a string.
# TODO: add a real example of how to handle realistic commitment data, or chop example
- Return type:
- async get_commitment_metadata(netuid, hotkey_ss58, block=None, block_hash=None, reuse_block=False)#
Fetches raw commitment metadata from specific subnet for given hotkey.
- Parameters:
netuid (int) – The unique subnet identifier.
hotkey_ss58 (str) – The hotkey ss58 address.
block (Optional[int]) – The blockchain block number for the query.
block_hash (Optional[str]) – The hash of the block at which to check the hotkey ownership.
reuse_block (bool) – Whether to reuse the last-used blockchain hash.
- Returns:
The raw commitment metadata. Returns a dict when commitment data exists, or an empty string when no commitment is found for the given hotkey on the subnet.
- Return type:
- async get_crowdloan_by_id(crowdloan_id, block=None, block_hash=None, reuse_block=False)#
Retrieves detailed information about a specific crowdloan campaign.
- Parameters:
crowdloan_id (int) – Unique identifier of the crowdloan (auto-incremented starting from 0).
block (Optional[int]) – The blockchain block number for the query.
block_hash (Optional[str]) – The block hash at which to query. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
campaign ID, creator address, creator’s deposit, minimum contribution amount, end block, funding cap, funds account address, amount raised, optional target address, optional embedded call, finalization status, and contributor count. Returns
Noneif the crowdloan does not exist.- Return type:
CrowdloanInfoobject containing
Notes
Crowdloans Overview: <https://docs.learnbittensor.org/subnets/crowdloans>
- async get_crowdloan_constants(constants=None, block=None, block_hash=None, reuse_block=False)#
Retrieves runtime configuration constants governing crowdloan behavior and limits on the Bittensor blockchain.
If a list of constant names is provided, only those constants will be queried. Otherwise, all known constants defined in CrowdloanConstants.field_names() are fetched.
These constants define requirements and operational limits for crowdloan campaigns:
AbsoluteMinimumContribution: Minimum amount per contribution (TAO).MaxContributors: Maximum number of unique contributors per crowdloan.MaximumBlockDuration: Maximum duration (in blocks) for a crowdloan campaign (60 days = 432,000 blocks on production).MinimumDeposit: Minimum deposit required from the creator (TAO).MinimumBlockDuration: Minimum duration (in blocks) for a crowdloan campaign (7 days = 50,400 blocks on production).RefundContributorsLimit: Maximum number of contributors refunded perrefund_crowdloancall (typically 50).
- Parameters:
constants (Optional[list[str]]) – Specific constant names to query. If
None, retrieves all constants fromCrowdloanConstants.block (Optional[int]) – The blockchain block number for the query.
block_hash (Optional[str]) – The block hash at which to query. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
A
CrowdloanConstantsdata object containing the queried constants. Missing constants returnNone.- Return type:
bittensor.core.chain_data.CrowdloanConstants
Notes
These constants enforce contribution floors, duration bounds, and refund batching limits.
Crowdloans Overview: <https://docs.learnbittensor.org/subnets/crowdloans>
- async get_crowdloan_contributions(crowdloan_id, block=None, block_hash=None, reuse_block=False)#
Retrieves all contributions made to a specific crowdloan campaign.
Returns a mapping of contributor coldkey addresses to their contribution amounts in Rao.
- Parameters:
crowdloan_id (int) – The unique identifier of the crowdloan.
block (Optional[int]) – The blockchain block number for the query.
block_hash (Optional[str]) – The block hash at which to query. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
Dictionary mapping contributor SS58 addresses to their
Balancecontribution amounts (in Rao). Returns empty dictionary if the crowdloan has no contributions or does not exist.- Return type:
Notes
Contributions are clipped to the remaining cap. Once the cap is reached, no further contributions are accepted.
Crowdloans Overview: <https://docs.learnbittensor.org/subnets/crowdloans>
Crowdloan Tutorial: <https://docs.learnbittensor.org/subnets/crowdloans/crowdloans-tutorial#step-4-contribute-to-the-crowdloan>
- async get_crowdloan_next_id(block=None, block_hash=None, reuse_block=False)#
Retrieves the next available crowdloan identifier.
Crowdloan IDs are allocated sequentially starting from 0. This method returns the ID that will be assigned to the next crowdloan created via
create_crowdloan().- Parameters:
- Returns:
The next crowdloan ID (integer) to be assigned.
- Return type:
Notes
Crowdloans Overview: <https://docs.learnbittensor.org/subnets/crowdloans>
Crowdloan Tutorial: <https://docs.learnbittensor.org/subnets/crowdloans/crowdloans-tutorial#get-the-crowdloan-id>
- async get_crowdloans(block=None, block_hash=None, reuse_block=False)#
Retrieves all existing crowdloan campaigns with their metadata.
Returns comprehensive information for all crowdloans registered on the blockchain, including both active and finalized campaigns.
- Parameters:
- Returns:
campaign ID, creator address, creator’s deposit, minimum contribution amount, end block, funding cap, funds account address, amount raised, optional target address, optional embedded call, finalization status, and contributor count. Returns empty list if no crowdloans exist.
- Return type:
List of
CrowdloanInfoobjects, each containing
Notes
Crowdloans Overview: <https://docs.learnbittensor.org/subnets/crowdloans>
Crowdloan Lifecycle: <https://docs.learnbittensor.org/subnets/crowdloans#crowdloan-lifecycle>
- async get_current_block()[source]#
Returns the current block number on the Bittensor blockchain.
This function provides the latest block number, indicating the most recent state of the blockchain.
- Returns:
The current chain block number.
- Return type:
- async get_delegate_by_hotkey(hotkey_ss58, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves detailed information about a delegate neuron (validator) based on its hotkey. This function provides a comprehensive view of the delegate’s status, including its stakes, nominators, and reward distribution.
- Parameters:
hotkey_ss58 (str) – The
SS58address of the delegate’s hotkey.block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
Detailed information about the delegate neuron,
Noneif not found.- Return type:
Optional[bittensor.core.chain_data.DelegateInfo]
- async get_delegate_identities(block=None, block_hash=None, reuse_block=False)[source]#
Fetches delegate identities.
Delegates are validators that accept stake from other TAO holders (nominators/delegators). This method retrieves the on-chain identity information for all delegates, including display name, legal name, web URLs, and other metadata they have set.
- Parameters:
block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
Dictionary mapping delegate SS58 addresses to their ChainIdentity objects.
- Return type:
dict[str, bittensor.core.chain_data.chain_identity.ChainIdentity]
- async get_delegate_take(hotkey_ss58, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves the delegate ‘take’ percentage for a neuron identified by its hotkey. The ‘take’ represents the percentage of rewards that the delegate claims from its nominators’ stakes.
- Parameters:
hotkey_ss58 (str) – The
SS58address of the neuron’s hotkey.block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
The delegate take percentage.
- Return type:
- async get_delegated(coldkey_ss58, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves delegates and their associated stakes for a given nominator coldkey.
This method identifies all delegates (validators) that a specific coldkey has staked tokens to, along with stake amounts and other delegation information. This is useful for account holders to understand their stake allocations and involvement in the network’s delegation and consensus mechanisms.
- Parameters:
coldkey_ss58 (str) – The SS58 address of the account’s coldkey.
block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
List of DelegatedInfo objects containing stake amounts and delegate information. Returns empty list if no delegations exist for the coldkey.
- Return type:
- async get_delegates(block=None, block_hash=None, reuse_block=False)[source]#
Fetches all delegates registered on the chain.
Delegates are validators that accept stake from other TAO holders (nominators/delegators). This method retrieves comprehensive information about all delegates including their hotkeys, total stake, nominator count, take percentage, and other metadata.
- Parameters:
block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
List of DelegateInfo objects containing comprehensive delegate information. Returns empty list if no delegates are registered.
- Return type:
list[bittensor.core.chain_data.DelegateInfo]
- async get_ema_tao_inflow(netuid, block=None)#
Retrieves the EMA (exponential moving average) of net TAO flow for a specific subnet.
The EMA tracks net TAO flows (staking minus unstaking) with a 30-day half-life (~86.8 day window), smoothing out short-term fluctuations while capturing sustained staking trends. This metric determines the subnet’s share of TAO emissions under the current, flow-based model. Positive values indicate net inflow (more staking than unstaking), negative values indicate net outflow. Subnets with negative EMA flows receive zero emissions.
- Parameters:
- Returns:
Tuple of (last_updated_block, ema_flow) where ema_flow is the EMA of net TAO flow in TAO units. Returns None if the subnet does not exist or if querying subnet 0 (root network).
- Return type:
Optional[tuple[int, bittensor.utils.balance.Balance]]
The EMA uses a smoothing factor α ≈ 0.000003209, creating a 30-day half-life and ~86.8 day window. Only direct stake/unstake operations count toward flows; neuron registrations and root claims are excluded. Subnet 0 (root network) does not have an EMA TAO flow value and will return None.
Notes
Flow-based emissions: <https://docs.learnbittensor.org/learn/emissions#tao-reserve-injection>
EMA smoothing: <https://docs.learnbittensor.org/learn/ema>
- async get_existential_deposit(block=None, block_hash=None, reuse_block=False)[source]#
Retrieves the existential deposit amount for the Bittensor blockchain.
The existential deposit is the minimum amount of TAO required for an account to exist on the blockchain. Accounts with balances below this threshold can be reaped (removed) to conserve network resources and prevent blockchain bloat from dust accounts.
- Parameters:
- Returns:
The existential deposit amount in RAO.
- Return type:
- async get_extrinsic_fee(call, keypair)#
Gets the extrinsic fee for a given extrinsic call and keypair.
This method estimates the transaction fee that will be charged for submitting the extrinsic to the blockchain. The fee is returned in Rao (the smallest unit of TAO, where 1 TAO = 1e9 Rao).
- Parameters:
call (scalecodec.GenericCall) – The extrinsic GenericCall object representing the transaction to estimate.
keypair (bittensor_wallet.Keypair) – The keypair associated with the extrinsic (used to determine the account paying the fee).
- Returns:
Balance object representing the extrinsic fee in Rao.
- Return type:
Example:
# Estimate fee before sending a transfer call = await subtensor.compose_call( call_module="Balances", call_function="transfer", call_params={"dest": destination_ss58, "value": amount.rao} ) fee = await subtensor.get_extrinsic_fee(call=call, keypair=wallet.coldkey) print(f"Estimated fee: {fee.tao} TAO")
Notes
To create the GenericCall object, use the
compose_callmethod with proper parameters. - <https://docs.learnbittensor.org/learn/fees>
- async get_hotkey_owner(hotkey_ss58, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves the owner of the given hotkey at a specific block hash. This function queries the blockchain for the owner of the provided hotkey. If the hotkey does not exist at the specified block hash, it returns
None.- Parameters:
- Returns:
The SS58 address of the owner if the hotkey exists, or None if it doesn’t.
- Return type:
Optional[str]
- get_hotkey_stake#
- async get_hyperparameter(param_name, netuid, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves a specified hyperparameter for a specific subnet.
This method queries the blockchain for subnet-specific hyperparameters such as difficulty, tempo, immunity period, and other network configuration values. Return types and units vary by parameter.
- Parameters:
param_name (str) – The name of the hyperparameter storage function to retrieve.
netuid (int) – The unique identifier of the subnet.
block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
The value of the specified hyperparameter if the subnet exists,
Noneotherwise. Return type varies by parameter (int, float, bool, or Balance).- Return type:
Optional[Any]
- async get_last_bonds_reset(netuid, hotkey_ss58, block=None, block_hash=None, reuse_block=False)#
Retrieves the block number when bonds were last reset for a specific hotkey on a subnet.
- Parameters:
netuid (int) – The network uid to fetch from.
hotkey_ss58 (str) – The hotkey of the neuron for which to fetch the last bonds reset.
block (Optional[int]) – The block number to query.
block_hash (Optional[str]) – The hash of the block to retrieve the parameter from. Do not specify if using
blockorreuse_block.reuse_block (bool) – Whether to use the last-used block. Do not set if using
block_hashorblock.
- Returns:
The block number when bonds were last reset, or
Noneif no bonds reset has occurred.
- async get_last_commitment_bonds_reset_block(netuid, uid, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves the last block number when the bonds reset were triggered by publish_metadata for a specific neuron.
- Parameters:
netuid (int) – The unique identifier of the subnetwork.
uid (int) – The unique identifier of the neuron.
block (Optional[int]) – The block number to query.
block_hash (Optional[str]) – The hash of the block to retrieve the parameter from. Do not specify if using
blockorreuse_block.reuse_block (bool) – Whether to use the last-used block. Do not set if using
block_hashorblock.
- Returns:
The block number when the bonds were last reset, or None if not found.
- Return type:
Optional[int]
- async get_liquidity_list(wallet, netuid, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves all liquidity positions for the given wallet on a specified subnet (netuid). Calculates associated fee rewards based on current global and tick-level fee data.
- Parameters:
wallet (bittensor_wallet.Wallet) – Wallet instance to fetch positions for.
netuid (int) – Subnet unique id.
block (Optional[int]) – The block number for which the children are to be retrieved.
block_hash (Optional[str]) – The hash of the block to retrieve the subnet unique identifiers from.
reuse_block (bool) – Whether to reuse the last-used block hash.
- Returns:
List of liquidity positions, or None if subnet does not exist.
- Return type:
Optional[list[bittensor.utils.liquidity.LiquidityPosition]]
- async get_mechanism_count(netuid, block=None, block_hash=None, reuse_block=False)#
Retrieves the number of mechanisms for the given subnet.
- Parameters:
netuid (int) – Subnet identifier.
block (Optional[int]) – The blockchain block number for the query.
block_hash (Optional[str]) – The hash of the block to retrieve the stake from. Do not specify if using
blockorreuse_block.reuse_block (bool) – Whether to use the last-used block. Do not set if using
block_hashorblock.
- Returns:
The number of mechanisms for the given subnet.
- Return type:
- async get_mechanism_emission_split(netuid, block=None, block_hash=None, reuse_block=False)#
Returns the emission percentages allocated to each subnet mechanism.
- Parameters:
netuid (int) – The unique identifier of the subnet.
block (Optional[int]) – The blockchain block number for the query.
block_hash (Optional[str]) – The hash of the block to retrieve the stake from. Do not specify if using
blockorreuse_block.reuse_block (bool) – Whether to use the last-used block. Do not set if using
block_hashorblock.
- Returns:
A list of integers representing the percentage of emission allocated to each subnet mechanism (rounded to whole numbers). Returns None if emission is evenly split or if the data is unavailable.
- Return type:
- async get_metagraph_info(netuid, mechid=0, selected_indices=None, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves full or partial metagraph information for the specified subnet (netuid).
A metagraph is a data structure that contains comprehensive information about the current state of a subnet, including detailed information on all the nodes (neurons) such as subnet validator stakes and subnet weights in the subnet. Metagraph aids in calculating emissions.
- Parameters:
netuid (int) – The unique identifier of the subnet to query.
selected_indices (Optional[Union[list[bittensor.core.chain_data.SelectiveMetagraphIndex], list[int]]]) – Optional list of SelectiveMetagraphIndex or int values specifying which fields to retrieve. If not provided, all available fields will be returned.
block (Optional[int]) – The blockchain block number for the query.
block_hash (Optional[str]) – The hash of the blockchain block number at which to perform the query.
reuse_block (bool) – Whether to reuse the last-used block hash when retrieving info.
mechid (int) – Subnet mechanism unique identifier.
- Returns:
MetagraphInfo object with the requested subnet mechanism data, None if the subnet mechanism does not exist.
- Return type:
Optional[bittensor.core.chain_data.MetagraphInfo]
Example:
# Retrieve all fields from the metagraph from subnet 2 mechanism 0 meta_info = subtensor.get_metagraph_info(netuid=2) # Retrieve all fields from the metagraph from subnet 2 mechanism 1 meta_info = subtensor.get_metagraph_info(netuid=2, mechid=1) # Retrieve selective data from the metagraph from subnet 2 mechanism 0 partial_meta_info = subtensor.get_metagraph_info( netuid=2, selected_indices=[SelectiveMetagraphIndex.Name, SelectiveMetagraphIndex.OwnerHotkeys] ) # Retrieve selective data from the metagraph from subnet 2 mechanism 1 partial_meta_info = subtensor.get_metagraph_info( netuid=2, mechid=1, selected_indices=[SelectiveMetagraphIndex.Name, SelectiveMetagraphIndex.OwnerHotkeys] )
- async get_minimum_required_stake()[source]#
Returns the minimum required stake threshold for nominator cleanup operations.
This threshold is used ONLY for cleanup after unstaking operations. If a nominator’s remaining stake falls below this minimum after an unstake, the remaining stake is forcefully cleared and returned to the coldkey to prevent dust accounts.
This is NOT the minimum checked during staking operations. The actual minimum for staking is determined by DefaultMinStake (typically 0.001 TAO plus fees).
- Returns:
The minimum stake threshold as a Balance object. Nominator stakes below this amount are automatically cleared after unstake operations.
- async get_netuids_for_hotkey(hotkey_ss58, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves a list of subnet UIDs (netuids) where a given hotkey is a member. This function identifies the specific subnets within the Bittensor network where the neuron associated with the hotkey is active.
- Parameters:
hotkey_ss58 (str) – The
SS58address of the neuron’s hotkey.block (Optional[int]) – The blockchain block number for the query.
block_hash (Optional[str]) – The hash of the blockchain block number at which to perform the query.
reuse_block (bool) – Whether to reuse the last-used block hash when retrieving info.
- Returns:
A list of netuids where the neuron is a member.
- Return type:
- async get_neuron_certificate(hotkey_ss58, netuid, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves the TLS certificate for a specific neuron identified by its unique identifier (UID) within a specified subnet (netuid) of the Bittensor network.
- Parameters:
hotkey_ss58 (str) – The SS58 address of the neuron’s hotkey.
netuid (int) – The unique identifier of the subnet.
block (Optional[int]) – The blockchain block number for the query.
block_hash (Optional[str]) – The hash of the block to retrieve the parameter from. Do not specify if using block or reuse_block.
reuse_block (bool) – Whether to use the last-used block. Do not set if using
block_hashorblock.
- Returns:
Certificate object containing the neuron’s TLS public key and algorithm, or
Noneif the neuron has not registered a certificate.- Return type:
Optional[bittensor.utils.Certificate]
This function is used for certificate discovery for setting up mutual tls communication between neurons.
- async get_neuron_for_pubkey_and_subnet(hotkey_ss58, netuid, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves information about a neuron based on its public key (hotkey SS58 address) and the specific subnet UID (netuid). This function provides detailed neuron information for a particular subnet within the Bittensor network.
- Parameters:
hotkey_ss58 (str) – The
SS58address of the neuron’s hotkey.netuid (int) – The unique identifier of the subnet.
block (Optional[int]) – The blockchain block number for the query.
block_hash (Optional[str]) – The blockchain block number at which to perform the query.
reuse_block (bool) – Whether to reuse the last-used blockchain block hash.
- Returns:
Detailed information about the neuron if found,
Noneotherwise.- Return type:
bittensor.core.chain_data.NeuronInfo
This function is crucial for accessing specific neuron data and understanding its status, stake, and other attributes within a particular subnet of the Bittensor ecosystem.
- async get_next_epoch_start_block(netuid, block=None, block_hash=None, reuse_block=False)[source]#
Calculates the first block number of the next epoch for the given subnet.
If
blockis not provided, the current chain block will be used. Epochs are determined based on the subnet’s tempo (i.e., blocks per epoch). The result is the block number at which the next epoch will begin.- Parameters:
netuid (int) – The unique identifier of the subnet.
block (Optional[int]) – The reference block to calculate from. If
None, uses the current chain block height.block_hash (Optional[str]) – The blockchain block number at which to perform the query.
reuse_block (bool) – Whether to reuse the last-used blockchain block hash.
- Returns:
The block number at which the next epoch will start.
- Return type:
- async get_owned_hotkeys(coldkey_ss58, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves all hotkeys owned by a specific coldkey address.
- Parameters:
- Returns:
A list of hotkey SS58 addresses owned by the coldkey.
- Return type:
- async get_parents(hotkey_ss58, netuid, block=None, block_hash=None, reuse_block=False)[source]#
This method retrieves the parent of a given hotkey and netuid. It queries the SubtensorModule’s ParentKeys storage function to get the children and formats them before returning as a tuple.
- Parameters:
hotkey_ss58 (str) – The child hotkey SS58.
netuid (int) – The netuid value.
block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
A list of formatted parents [(proportion, parent)]
- Return type:
Notes
get_children()for retrieving child keys
- async get_proxies(block=None, block_hash=None, reuse_block=False)#
Retrieves all proxy relationships from the chain.
This method queries the Proxy.Proxies storage map across all accounts and returns a dictionary mapping each real account (delegator) to its list of proxy relationships.
- Parameters:
block (Optional[int]) – The blockchain block number for the query. If
None, queries the latest block.block_hash (Optional[str]) – The hash of the block at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
- Dictionary mapping real account SS58 addresses to lists of ProxyInfo objects. Each ProxyInfo contains the
delegate address, proxy type, and delay for that proxy relationship.
- Return type:
Notes
This method queries all proxy relationships on the chain, which may be resource-intensive for large networks. Consider using
get_proxies_for_real_account()for querying specific accounts.
- async get_proxies_for_real_account(real_account_ss58, block=None, block_hash=None, reuse_block=False)#
Returns proxy/ies associated with the provided real account.
This method queries the Proxy.Proxies storage for a specific real account and returns all proxy relationships where this real account is the delegator. It also returns the deposit amount reserved for these proxies.
- Parameters:
real_account_ss58 (str) – SS58 address of the real account (delegator) whose proxies to retrieve.
block (Optional[int]) – The blockchain block number for the query.
block_hash (Optional[str]) – The hash of the block at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
- List of ProxyInfo objects representing all proxy relationships for the real account. Each ProxyInfo
contains delegate address, proxy type, and delay.
- Balance object representing the reserved deposit amount for these proxies. This deposit is held as
long as the proxy relationships exist and is returned when proxies are removed.
- Return type:
Tuple containing
Notes
If the account has no proxies, returns an empty list and a zero balance.
See: <https://docs.learnbittensor.org/keys/proxies/create-proxy>
- async get_proxy_announcement(delegate_account_ss58, block=None, block_hash=None, reuse_block=False)#
Retrieves proxy announcements for a specific delegate account.
This method queries the Proxy.Announcements storage for announcements made by the given delegate proxy account. Announcements allow a proxy to declare its intention to execute a call on behalf of a real account after a delay period.
- Parameters:
delegate_account_ss58 (str) – SS58 address of the delegate proxy account whose announcements to retrieve.
block (Optional[int]) – The blockchain block number for the query. If
None, queries the latest block.block_hash (Optional[str]) – The hash of the block at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
- List of ProxyAnnouncementInfo objects. Each object contains the real account address, call hash, and block
height at which the announcement was made.
- Return type:
list[bittensor.core.chain_data.ProxyAnnouncementInfo]
Notes
If the delegate has no announcements, returns an empty list.
- async get_proxy_announcements(block=None, block_hash=None, reuse_block=False)#
Retrieves all proxy announcements from the chain.
This method queries the Proxy.Announcements storage map across all delegate accounts and returns a dictionary mapping each delegate to its list of pending announcements.
- Parameters:
block (Optional[int]) – The blockchain block number for the query. If
None, queries the latest block.block_hash (Optional[str]) – The hash of the block at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
Dictionary mapping delegate account SS58 addresses to lists of ProxyAnnouncementInfo objects. Each ProxyAnnouncementInfo contains the real account address, call hash, and block height.
- Return type:
dict[str, list[bittensor.core.chain_data.ProxyAnnouncementInfo]]
Notes
This method queries all announcements on the chain, which may be resource-intensive for large networks. Consider using
get_proxy_announcement()for querying specific delegates.
- async get_proxy_constants(constants=None, as_dict=False, block=None, block_hash=None, reuse_block=False)#
Fetches runtime configuration constants from the Proxy pallet.
This method retrieves on-chain configuration constants that define deposit requirements, proxy limits, and announcement constraints for the Proxy pallet. These constants govern how proxy accounts operate within the Subtensor network.
- Parameters:
constants (Optional[list[str]]) – Optional list of specific constant names to fetch. If omitted, all constants defined in ProxyConstants.constants_names() are queried. Valid constant names include: “AnnouncementDepositBase”, “AnnouncementDepositFactor”, “MaxProxies”, “MaxPending”, “ProxyDepositBase”, “ProxyDepositFactor”.
as_dict (bool) – If True, returns the constants as a dictionary instead of a ProxyConstants object.
block (Optional[int]) – The blockchain block number for the query. If
None, queries the latest block.block_hash (Optional[str]) – The hash of the block at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
ProxyConstants object containing all requested constants. If as_dict is True: Dictionary mapping constant names to their values (Balance objects for deposit
constants, integers for limit constants).
- Return type:
If as_dict is False
Notes
All Balance amounts are returned in RAO. Constants reflect the current chain configuration at the specified block.
- async get_revealed_commitment(netuid, uid, block=None)[source]#
Returns uid related revealed commitment for a given netuid.
- Parameters:
- Returns:
A tuple of reveal block and commitment message.
- Return type:
Example:
( (12, "Alice message 1"), (152, "Alice message 2") ) ( (12, "Bob message 1"), (147, "Bob message 2") )
- async get_revealed_commitment_by_hotkey(netuid, hotkey_ss58=None, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves hotkey related revealed commitment for a given subnet.
- Parameters:
netuid (int) – The unique identifier of the subnetwork.
hotkey_ss58 (Optional[str]) – The ss58 address of the committee member.
block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
A tuple of reveal block and commitment message.
- Return type:
# TODO: add example to clarify return ordering and units; @roman can you help w this? .. admonition:: Notes
- async get_root_claim_type(coldkey_ss58, block=None, block_hash=None, reuse_block=False)#
Return the configured root claim type for a given coldkey.
The root claim type controls how dividends from staking to the Root Subnet (subnet 0) are processed when they are claimed:
"Swap"(default): Alpha dividends are swapped to TAO at claim time and restaked on the root subnet."Keep": Alpha dividends remain as Alpha on the originating subnets.
- Parameters:
coldkey_ss58 (str) – The SS58 address of the coldkey whose root claim preference to query.
block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to query the claim type. Do not specify if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not specify if using
blockorblock_hash.
- Returns:
The root claim type as a string, either
"Swap"or"Keep".- Return type:
Notes
The claim type applies to both automatic and manual root claims; it does not affect the original TAO stake on subnet 0, only how Alpha dividends are treated.
See: <https://docs.learnbittensor.org/staking-and-delegation/root-claims>
See also: <https://docs.learnbittensor.org/staking-and-delegation/root-claims/managing-root-claims>
- async get_root_claimable_all_rates(hotkey_ss58, block=None, block_hash=None, reuse_block=False)#
Retrieves all root claimable rates from a given hotkey address for all subnets with this validator.
- Parameters:
hotkey_ss58 (str) – The SS58 address of the root validator hotkey.
block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to query. Do not specify if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not specify if using
blockorblock_hash.
- Returns:
Dictionary mapping
netuidto a float claimable rate (approximately in the range[0.0, 1.0]) for that subnet. Missing entries imply no claimable Alpha dividends for that subnet.- Return type:
- async get_root_claimable_rate(hotkey_ss58, netuid, block=None, block_hash=None, reuse_block=False)#
Return the fraction of root stake currently claimable on a subnet.
This method returns a normalized rate representing how much Alpha dividends are currently claimable on the given subnet relative to the validator’s root stake. It is primarily a low-level helper; most users should call
get_root_claimable_stake()instead to obtain a Balance.- Parameters:
hotkey_ss58 (str) – The SS58 address of the root validator hotkey.
netuid (int) – The unique identifier of the subnet whose claimable rate to compute.
block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to query. Do not specify if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not specify if using
blockorblock_hash.
- Returns:
A float representing the claimable rate for this subnet (approximately in the range
[0.0, 1.0]). A value of 0.0 means there are currently no claimable Alpha dividends on the subnet.- Return type:
Notes
Use
get_root_claimable_stake()to retrieve the actual claimable amount as aBalanceobject.See: <https://docs.learnbittensor.org/staking-and-delegation/root-claims/managing-root-claims>
- async get_root_claimable_stake(coldkey_ss58, hotkey_ss58, netuid, block=None, block_hash=None, reuse_block=False)#
Return the currently claimable Alpha staking dividends for a coldkey from a root validator on a subnet.
- Parameters:
coldkey_ss58 (str) – The SS58 address of the delegator’s coldkey.
hotkey_ss58 (str) – The SS58 address of the root validator hotkey.
netuid (int) – The subnet ID where Alpha dividends will be claimed.
block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to query. Do not specify if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not specify if using
blockorblock_hash.
- Returns:
Balancerepresenting the Alpha stake currently available to claim on the specified subnet (unit is the subnet’s Alpha token).- Return type:
Notes
After a successful manual or automatic claim, this value typically drops to zero for that subnet until new dividends accumulate.
The underlying TAO stake on the Root Subnet remains unaffected; only Alpha dividends are moved or swapped according to the configured root claim type.
See: <https://docs.learnbittensor.org/staking-and-delegation/root-claims>
See also: <https://docs.learnbittensor.org/staking-and-delegation/root-claims/managing-root-claims>
- async get_root_claimed(coldkey_ss58, hotkey_ss58, netuid, block=None, block_hash=None, reuse_block=False)#
Return the total Alpha dividends already claimed for a coldkey from a root validator on a subnet.
- Parameters:
coldkey_ss58 (str) – The SS58 address of the delegator’s coldkey.
hotkey_ss58 (str) – The SS58 address of the root validator hotkey.
netuid (int) – The unique identifier of the subnet.
block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to query. Do not specify if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not specify if using
blockorblock_hash.
- Returns:
Balancerepresenting the cumulative Alpha stake that has already been claimed from the root validator on the specified subnet.- Return type:
- async get_stake(coldkey_ss58, hotkey_ss58, netuid, block=None, block_hash=None, reuse_block=False)[source]#
Returns the stake under a coldkey - hotkey pairing.
- Parameters:
hotkey_ss58 (str) – The SS58 address of the hotkey.
coldkey_ss58 (str) – The SS58 address of the coldkey.
netuid (int) – The subnet ID.
block (Optional[int]) – The block number at which to query the stake information.
block_hash (Optional[str]) – The hash of the block to retrieve the stake from. Do not specify if using block or reuse_block
reuse_block (bool) – Whether to use the last-used block. Do not set if using
block_hashorblock.
- Returns:
The stake under the coldkey - hotkey pairing.
- Return type:
- async get_stake_add_fee(amount, netuid, block=None, block_hash=None, reuse_block=False)[source]#
Calculates the fee for adding new stake to a hotkey.
- Parameters:
amount (bittensor.utils.balance.Balance) – Amount of stake to add in TAO
netuid (int) – Netuid of subnet
block (Optional[int]) – The block number for which the children are to be retrieved.
block_hash (Optional[str]) – The hash of the block to retrieve the subnet unique identifiers from.
reuse_block (bool) – Whether to reuse the last-used block hash.
- Returns:
The calculated stake fee as a Balance object in TAO.
- Return type:
- async get_stake_for_coldkey_and_hotkey(coldkey_ss58, hotkey_ss58, netuids=None, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves all coldkey-hotkey pairing stake across specified (or all) subnets
- Parameters:
coldkey_ss58 (str) – The SS58 address of the coldkey.
hotkey_ss58 (str) – The SS58 address of the hotkey.
netuids (Optional[bittensor.core.types.UIDs]) – The subnet IDs to query for. Set to
Nonefor all subnets.block (Optional[int]) – The block number for which the children are to be retrieved.
block_hash (Optional[str]) – The hash of the block to retrieve the subnet unique identifiers from.
reuse_block (bool) – Whether to reuse the last-used block hash.
- Returns:
A netuid to StakeInfo mapping of all stakes across all subnets.
- Return type:
- async get_stake_for_hotkey(hotkey_ss58, netuid, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves the total stake for a given hotkey on a specific subnet.
- Parameters:
hotkey_ss58 (str) – The SS58 address of the hotkey.
netuid (int) – The subnet ID to query for.
block (Optional[int]) – The blockchain block number for the query.
block_hash (Optional[str]) – The hash of the block to retrieve the stake from.
reuse_block (bool) – Whether to reuse the last-used block hash.
- Returns:
The total stake for the hotkey on the specified subnet.
- Return type:
- async get_stake_info_for_coldkey(coldkey_ss58, block=None, block_hash=None, reuse_block=False)#
Retrieves the stake information for a given coldkey.
- Parameters:
- Returns:
List of StakeInfo objects.
- Return type:
list[bittensor.core.chain_data.StakeInfo]
- async get_stake_info_for_coldkeys(coldkey_ss58s, block=None, block_hash=None, reuse_block=False)#
Retrieves the stake information for multiple coldkeys.
- Parameters:
coldkey_ss58s (list[str]) – A list of SS58 addresses of the coldkeys to query.
block (Optional[int]) – The block number at which to query the stake information.
block_hash (Optional[str]) – The hash of the blockchain block number for the query.
reuse_block (bool) – Whether to reuse the last-used block hash.
- Returns:
The dictionary mapping coldkey addresses to a list of StakeInfo objects.
- Return type:
- async get_stake_movement_fee(origin_netuid, destination_netuid, amount, block=None, block_hash=None, reuse_block=False)[source]#
Calculates the fee for moving stake between hotkeys/subnets/coldkeys.
- Parameters:
origin_netuid (int) – Netuid of source subnet.
destination_netuid (int) – Netuid of the destination subnet.
amount (bittensor.utils.balance.Balance) – Amount of stake to move.
block (Optional[int]) – The block number for which the children are to be retrieved.
block_hash (Optional[str]) – The hash of the block to retrieve the subnet unique identifiers from.
reuse_block (bool) – Whether to reuse the last-used block hash.
- Returns:
The calculated stake fee as a Balance object
- Return type:
- async get_stake_weight(netuid, block=None, block_hash=None, reuse_block=False)#
Retrieves the stake weight for all hotkeys in a given subnet.
- Parameters:
- Returns:
A list of stake weights for all hotkeys in the specified subnet.
- Return type:
- async get_subnet_burn_cost(block=None, block_hash=None, reuse_block=False)[source]#
- Retrieves the burn cost for registering a new subnet within the Bittensor network. This cost represents the
amount of Tao that needs to be locked or burned to establish a new
- Parameters:
- Returns:
The burn cost for subnet registration.
- Return type:
- The subnet burn cost is an important economic parameter, reflecting the network’s mechanisms for controlling
the proliferation of subnets and ensuring their commitment to the network’s long-term viability.
- async get_subnet_hyperparameters(netuid, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves the hyperparameters for a specific subnet within the Bittensor network. These hyperparameters define the operational settings and rules governing the subnet’s behavior.
- Parameters:
- Returns:
The subnet’s hyperparameters, or
Noneif not available.- Return type:
Optional[bittensor.core.chain_data.SubnetHyperparameters]
Understanding the hyperparameters is crucial for comprehending how subnets are configured and managed, and how they interact with the network’s consensus and incentive mechanisms.
- async get_subnet_info(netuid, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves detailed information about subnet within the Bittensor network. This function provides comprehensive data on subnet, including its characteristics and operational parameters.
- Parameters:
- Returns:
A SubnetInfo objects, each containing detailed information about a subnet.
- Return type:
Gaining insights into the subnet’s details assists in understanding the network’s composition, the roles of different subnets, and their unique features.
- async get_subnet_owner_hotkey(netuid, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves the hotkey of the subnet owner for a given network UID.
This function queries the subtensor network to fetch the hotkey of the owner of a subnet specified by its netuid. If no data is found or the query fails, the function returns
None.- Parameters:
netuid (int) – The network UID of the subnet to fetch the owner’s hotkey for.
block (Optional[int]) – The blockchain block number for the query.
block_hash (Optional[str]) – The blockchain block_hash representation of the block id.
reuse_block (bool) – Whether to reuse the last-used blockchain block hash.
- Returns:
The hotkey of the subnet owner if available; None otherwise.
- Return type:
Optional[str]
- async get_subnet_price(netuid, block=None, block_hash=None, reuse_block=False)[source]#
Gets the current Alpha price in TAO for the specified subnet.
- Parameters:
netuid (int) – The unique identifier of the subnet.
block (Optional[int]) – The blockchain block number for the query.
block_hash (Optional[str]) – The hash of the block to retrieve the stake from. Do not specify if using
blockorreuse_block.reuse_block (bool) – Whether to use the last-used block. Do not set if using
block_hashorblock.
- Returns:
The current Alpha price in TAO units for the specified subnet.
- Return type:
Notes
Subnet 0 (root network) always returns 1 TAO since it uses TAO directly rather than Alpha.
- async get_subnet_prices(block=None, block_hash=None, reuse_block=False)[source]#
Gets the current Alpha price in TAO for all subnets.
- Parameters:
- Returns:
A dictionary mapping subnet unique ID (netuid) to the current Alpha price in TAO units.
- Return type:
Notes
Subnet 0 (root network) always has a price of 1 TAO since it uses TAO directly rather than Alpha.
- async get_subnet_reveal_period_epochs(netuid, block=None, block_hash=None)[source]#
Retrieves the SubnetRevealPeriodEpochs hyperparameter for a specified subnet.
This hyperparameter determines the number of epochs that must pass before a committed weight can be revealed in the commit-reveal mechanism.
- Parameters:
- Returns:
The number of epochs in the reveal period for the subnet.
- Return type:
- async get_subnet_validator_permits(netuid, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves the list of validator permits for a given subnet as boolean values.
- Parameters:
- Returns:
A list of boolean values representing validator permits, or None if not available.
- Return type:
- async get_timelocked_weight_commits(netuid, mechid=0, block=None, block_hash=None, reuse_block=False)#
Retrieves CRv4 (Commit-Reveal version 4) weight commit information for a specific subnet.
This method retrieves timelocked weight commitments made by validators using the commit-reveal mechanism. The raw byte/vector encoding from the chain is automatically parsed and converted into a structured format via WeightCommitInfo.
- Parameters:
netuid (int) – The unique identifier of the subnet.
mechid (int) – Subnet mechanism identifier (default 0 for primary mechanism).
block (Optional[int]) – The blockchain block number for the query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
ss58_address: The SS58 address of the committer.
commit_block: The block number when the commitment was made.
commit_message: The commit message (encoded commitment data).
reveal_round: The drand round when the commitment can be revealed.
- Return type:
A list of commit details, where each item is a tuple containing
Notes
The list may be empty if there are no commits found. - <https://docs.learnbittensor.org/resources/glossary#commit-reveal>
- async get_timestamp(block=None, block_hash=None, reuse_block=False)[source]#
Retrieves the datetime timestamp for a given block.
This method queries the Timestamp pallet to get the block’s timestamp. The on-chain timestamp is stored in milliseconds (Unix timestamp in milliseconds), which is automatically converted to a Python datetime object (Unix timestamp in seconds).
- Parameters:
block (Optional[int]) – The blockchain block number for the query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
A datetime object representing the timestamp of the specified block.
- Return type:
- async get_total_subnets(block=None, block_hash=None, reuse_block=False)[source]#
Retrieves the total number of subnets within the Bittensor network as of a specific blockchain block.
- Parameters:
- Returns:
The total number of subnets in the network.
- Return type:
Optional[int]
- async get_transfer_fee(wallet, destination_ss58, amount, keep_alive=True)[source]#
Calculates the transaction fee for transferring tokens from a wallet to a specified destination address. This function simulates the transfer to estimate the associated cost, taking into account the current network conditions and transaction complexity.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet from which the transfer is initiated.
destination_ss58 (str) – The
SS58address of the destination account.amount (bittensor.utils.balance.Balance) – The amount of tokens to be transferred, specified as a Balance object, or in Tao (float) or Rao (int) units.
keep_alive (bool) – Whether the transfer fee should be calculated based on keeping the wallet alive (existential deposit) or not.
- Returns:
- The estimated transaction fee for the transfer, represented as a Balance
object.
- Return type:
- async get_uid_for_hotkey_on_subnet(hotkey_ss58, netuid, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves the unique identifier (UID) for a neuron’s hotkey on a specific subnet.
- Parameters:
hotkey_ss58 (str) – The
SS58address of the neuron’s hotkey.netuid (int) – The unique identifier of the subnet.
block (Optional[int]) – The blockchain block number for the query.
block_hash (Optional[str]) – The blockchain block_hash representation of the block id.
reuse_block (bool) – Whether to reuse the last-used blockchain block hash.
- Returns:
The UID of the neuron if it is registered on the subnet,
Noneotherwise.- Return type:
Optional[int]
The UID is a critical identifier within the network, linking the neuron’s hotkey to its operational and governance activities on a particular subnet.
- async get_unstake_fee(netuid, amount, block=None, block_hash=None, reuse_block=False)[source]#
Calculates the fee for unstaking from a hotkey.
- Parameters:
netuid (int) – The unique identifier of the subnet.
amount (bittensor.utils.balance.Balance) – Amount of stake to unstake in TAO.
block (Optional[int]) – The blockchain block number for the query.
block_hash (Optional[str]) – The blockchain block_hash representation of the block id.
reuse_block (bool) – Whether to reuse the last-used blockchain block hash.
- Returns:
The calculated stake fee as a Balance object in Alpha.
- Return type:
- async get_vote_data(proposal_hash, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves the voting data for a specific proposal on the Bittensor blockchain. This data includes information about how senate members have voted on the proposal.
- Parameters:
proposal_hash (str) – The hash of the proposal for which voting data is requested.
block (Optional[int]) – The blockchain block number for the query.
block_hash (Optional[str]) – The hash of the blockchain block number to query the voting data.
reuse_block (bool) – Whether to reuse the last-used blockchain block hash.
- Returns:
An object containing the proposal’s voting data, or
Noneif not found.- Return type:
Optional[bittensor.core.chain_data.ProposalVoteData]
This function is important for tracking and understanding the decision-making processes within the Bittensor network, particularly how proposals are received and acted upon by the governing body.
- async immunity_period(netuid, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves the ‘ImmunityPeriod’ hyperparameter for a specific subnet. This parameter defines the duration during which new neurons are protected from certain network penalties or restrictions.
- Parameters:
- Returns:
The value of the ‘ImmunityPeriod’ hyperparameter if the subnet exists,
Noneotherwise.- Return type:
Optional[int]
The ‘ImmunityPeriod’ is a critical aspect of the network’s governance system, ensuring that new participants have a grace period to establish themselves and contribute to the network without facing immediate punitive actions.
- async initialize()[source]#
Establishes connection to the blockchain.
This method establishes the connection to the Bittensor blockchain and should be called after creating an AsyncSubtensor instance before making any queries.
When using the
async withcontext manager, this method is called automatically and does not need to be invoked explicitly.- Returns:
The initialized instance (self) for method chaining.
- Return type:
Example:
subtensor = AsyncSubtensor(network="finney") # Initialize the connection await subtensor.initialize() # calls to subtensor await subtensor.close()
- async is_fast_blocks()[source]#
Checks if the node is running with fast blocks enabled.
Fast blocks have a block time of 10 seconds, compared to the standard 12-second block time. This affects transaction timing and network synchronization.
- Returns:
Trueif fast blocks are enabled (10-second block time),Falseotherwise (12-second block time).- Return type:
- async is_hotkey_delegate(hotkey_ss58, block=None, block_hash=None, reuse_block=False)[source]#
Determines whether a given hotkey (public key) is a delegate on the Bittensor network. This function checks if the neuron associated with the hotkey is part of the network’s delegation system.
- Parameters:
- Returns:
Trueif the hotkey is a delegate,Falseotherwise.- Return type:
Being a delegate is a significant status within the Bittensor network, indicating a neuron’s involvement in consensus and governance processes.
- async is_hotkey_registered(hotkey_ss58, netuid=None, block=None, block_hash=None, reuse_block=False)[source]#
Determines whether a given hotkey (public key) is registered in the Bittensor network, either globally across any subnet or specifically on a specified subnet. This function checks the registration status of a neuron identified by its hotkey, which is crucial for validating its participation and activities within the network.
- Parameters:
hotkey_ss58 (str) – The SS58 address of the neuron’s hotkey.
netuid (Optional[int]) – The unique identifier of the subnet to check the registration.
block (Optional[int]) – The block number for which the children are to be retrieved.
block_hash (Optional[str]) – The hash of the block to retrieve the subnet unique identifiers from.
reuse_block (bool) – Whether to reuse the last-used block hash.
- Returns:
Trueif the hotkey is registered in the specified context (either any subnet or a specific subnet),Falseotherwise.
- Return type:
This function is important for verifying the active status of neurons in the Bittensor network. It aids in understanding whether a neuron is eligible to participate in network processes such as consensus, validation, and incentive distribution based on its registration status.
- async is_hotkey_registered_any(hotkey_ss58, block=None, block_hash=None, reuse_block=False)[source]#
Checks if a neuron’s hotkey is registered on any subnet within the Bittensor network.
- Parameters:
- Returns:
Trueif the hotkey is registered on any subnet, False otherwise.- Return type:
- async is_hotkey_registered_on_subnet(hotkey_ss58, netuid, block=None, block_hash=None, reuse_block=False)[source]#
Checks if the hotkey is registered on a given subnet.
- Parameters:
hotkey_ss58 (str) – The SS58 address of the hotkey to check.
netuid (int) – The unique identifier of the subnet.
block (Optional[int]) – The blockchain block number for the query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
Trueif the hotkey is registered on the specified subnet,Falseotherwise.- Return type:
- async is_in_admin_freeze_window(netuid, block=None, block_hash=None, reuse_block=False)#
Returns True if the current block is within the terminal freeze window of the tempo for the given subnet. During this window, admin ops are prohibited to avoid interference with validator weight submissions.
- Parameters:
- Returns:
True if in freeze window, else False.
- Return type:
- async is_subnet_active(netuid, block=None, block_hash=None, reuse_block=False)[source]#
Verifies if a subnet with the provided netuid is active.
A subnet is considered active if the
start_callextrinsic has been executed. A newly registered subnet may exist but not be active until the subnet owner callsstart_callto begin emissions.- Parameters:
netuid (int) – The unique identifier of the subnet.
block (Optional[int]) – The blockchain block number for the query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
Trueif the subnet is active (emissions have started),Falseotherwise.- Return type:
- async kill_pure_proxy(wallet, pure_proxy_ss58, spawner, proxy_type, index, height, ext_index, force_proxy_type=ProxyType.Any, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)#
Kills (removes) a pure proxy account.
This method removes a pure proxy account that was previously created via
create_pure_proxy(). The kill_pure call must be executed through the pure proxy account itself, with the spawner acting as an “Any” proxy. This method automatically handles this by executing the call viaproxy().- Parameters:
wallet (bittensor_wallet.Wallet) – Bittensor wallet object. The wallet.coldkey.ss58_address must be the spawner of the pure proxy (the account that created it via
create_pure_proxy()). The spawner must have an “Any” proxy relationship with the pure proxy.pure_proxy_ss58 (str) – The SS58 address of the pure proxy account to be killed. This is the address that was returned in the
create_pure_proxy()response.spawner (str) – The SS58 address of the spawner account (the account that originally created the pure proxy via
create_pure_proxy()). This should match wallet.coldkey.ss58_address.proxy_type (Union[str, bittensor.core.chain_data.ProxyType]) – The type of proxy permissions. Can be a string or ProxyType enum value. Must match the proxy_type used when creating the pure proxy.
index (int) – The salt value (u16, range
0-65535) originally used increate_pure_proxy()to generate this pure proxy’s address. This value, combined withproxy_type,delay, andspawner, uniquely identifies the pure proxy to be killed. Must match exactly the index used during creation.height (int) – The block number at which the pure proxy was created. This is returned in the “PureCreated” event from
create_pure_proxy()and is required to identify the exact creation transaction.ext_index (int) – The extrinsic index within the block at which the pure proxy was created. This is returned in the “PureCreated” event from
create_pure_proxy()and specifies the position of the creation extrinsic within the block. Together withheight, this uniquely identifies the creation transaction.force_proxy_type (Optional[Union[str, bittensor.core.chain_data.ProxyType]]) – The proxy type relationship to use when executing kill_pure through the proxy mechanism. Since pure proxies are keyless and cannot sign transactions, the spawner must act as a proxy for the pure proxy to execute kill_pure. This parameter specifies which proxy type relationship between the spawner and the pure proxy account should be used. The spawner must have a proxy relationship of this type (or Any) with the pure proxy account. Defaults to ProxyType.Any for maximum compatibility. If None, Substrate will automatically select an available proxy type from the spawner’s proxy relationships.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Whether to wait for the inclusion of the transaction.
wait_for_finalization (bool) – Whether to wait for the finalization of the transaction.
- Returns:
The result object of the extrinsic execution.
- Return type:
Notes
The
kill_purecall must be executed through the pure proxy account itself, with the spawner acting as anAnyproxy. This method automatically handles this by executing the call viaproxy(). The spawner must have anAnyproxy relationship with the pure proxy for this to work.Bittensor proxies: <https://docs.learnbittensor.org/keys/proxies/pure-proxies>
Warning
All access to this account will be lost. Any funds remaining in the pure proxy account will become permanently inaccessible after this operation.
- async last_drand_round()[source]#
Retrieves the last drand round emitted in Bittensor.
Drand (distributed randomness) rounds are used to determine when committed weights can be revealed in the commit-reveal mechanism. This method returns the most recent drand round number, which corresponds to the timing for weight reveals.
- Returns:
The latest drand round number emitted in Bittensor, or
Noneif no round has been stored.- Return type:
Optional[int]
- log_verbose = False#
- async max_weight_limit(netuid, block=None, block_hash=None, reuse_block=False)[source]#
Returns the MaxWeightsLimit hyperparameter for a subnet.
- Parameters:
netuid (int) – The unique identifier of the subnetwork.
block (Optional[int]) – The blockchain block number for the query.
block_hash (Optional[str]) – The hash of the block at which to query. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
- The stored maximum weight limit as a normalized float in [0, 1], or
Noneif the subnetwork does not exist. Note: this value is not actually enforced - the weight validation code uses a hardcoded u16::MAX instead.
- The stored maximum weight limit as a normalized float in [0, 1], or
- Return type:
Optional[float]
Notes
This hyperparameter is now a constant rather than a settable variable.
<https://docs.learnbittensor.org/subnets/subnet-hyperparameters>
- async metagraph(netuid, mechid=0, lite=True, block=None)[source]#
Returns a synced metagraph for a specified subnet within the Bittensor network. The metagraph represents the network’s structure, including neuron connections and interactions.
- Parameters:
- Returns:
The metagraph representing the subnet’s structure and neuron relationships.
- Return type:
The metagraph is an essential tool for understanding the topology and dynamics of the Bittensor network’s decentralized architecture, particularly in relation to neuron interconnectivity and consensus processes.
- async min_allowed_weights(netuid, block=None, block_hash=None, reuse_block=False)[source]#
Returns the MinAllowedWeights hyperparameter for a subnet.
This hyperparameter sets the minimum length of the weights vector that a validator must submit. It checks
weights.len() >= MinAllowedWeights. For example, a validator could submit[1000, 0, 0, 0]to satisfyMinAllowedWeights=4, but this would fail ifMinAllowedWeightswere set to 5. This ensures validators distribute attention across the subnet.- Parameters:
netuid (int) – The unique identifier of the subnetwork.
block (Optional[int]) – The blockchain block number for the query.
block_hash (Optional[str]) – The hash of the block at which to query. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
- The minimum number of required weight connections, or
Noneif the subnetwork does not exist or the parameter is not found.
- The minimum number of required weight connections, or
- Return type:
Optional[int]
- async modify_liquidity(wallet, netuid, position_id, liquidity_delta, hotkey_ss58=None, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)[source]#
Modifies liquidity in liquidity position by adding or removing liquidity from it.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet used to sign the extrinsic (must be unlocked).
netuid (int) – The UID of the target subnet for which the call is being initiated.
position_id (int) – The id of the position record in the pool.
liquidity_delta (bittensor.utils.balance.Balance) – The amount of liquidity to be added or removed (add if positive or remove if negative).
hotkey_ss58 (Optional[str]) – The hotkey with staked TAO in Alpha. If not passed then the wallet hotkey is used.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Whether to wait for the extrinsic to be included in a block.
wait_for_finalization (bool) – Whether to wait for finalization of the extrinsic.
- Returns:
The result object of the extrinsic execution.
- Return type:
Example:
import bittensor as bt subtensor = bt.AsyncSubtensor(network="local") await subtensor.initialize() my_wallet = bt.Wallet() # if `liquidity_delta` is negative my_liquidity_delta = Balance.from_tao(100) * -1 await subtensor.modify_liquidity( wallet=my_wallet, netuid=123, position_id=2, liquidity_delta=my_liquidity_delta ) # if `liquidity_delta` is positive my_liquidity_delta = Balance.from_tao(120) await subtensor.modify_liquidity( wallet=my_wallet, netuid=123, position_id=2, liquidity_delta=my_liquidity_delta )
Note
Modifying is allowed even when user liquidity is enabled in specified subnet. Call toggle_user_liquidity to enable/disable user liquidity.
- async move_stake(wallet, origin_netuid, origin_hotkey_ss58, destination_netuid, destination_hotkey_ss58, amount=None, move_all_stake=False, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)[source]#
Moves stake to a different hotkey and/or subnet.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet to move stake from.
origin_netuid (int) – The netuid of the source subnet.
origin_hotkey_ss58 (str) – The SS58 address of the source hotkey.
destination_netuid (int) – The netuid of the destination subnet.
destination_hotkey_ss58 (str) – The SS58 address of the destination hotkey.
amount (Optional[bittensor.utils.balance.Balance]) – Amount of stake to move.
move_all_stake (bool) – If true, moves all stake from the source hotkey to the destination hotkey.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Waits for the transaction to be included in a block.
wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain.
- Returns:
The result object of the extrinsic execution.
- Return type:
Notes
Price Protection: <https://docs.learnbittensor.org/learn/price-protection>
Rate Limits: <https://docs.learnbittensor.org/learn/chain-rate-limits#staking-operations-rate-limits>
- async neuron_for_uid(uid, netuid, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves detailed information about a specific neuron identified by its unique identifier (UID) within a specified subnet (netuid) of the Bittensor network. This function provides a comprehensive view of a neuron’s attributes, including its stake, rank, and operational status.
- Parameters:
uid (Optional[int]) – The unique identifier of the neuron.
netuid (int) – The unique identifier of the subnet.
block (Optional[int]) – The blockchain block number for the query.
block_hash (Optional[str]) – The hash of the blockchain block number for the query.
reuse_block (bool) – Whether to reuse the last-used blockchain block hash.
- Returns:
Detailed information about the neuron if found, a null neuron otherwise
- Return type:
bittensor.core.chain_data.NeuronInfo
This function is crucial for analyzing individual neurons’ contributions and status within a specific subnet, offering insights into their roles in the network’s consensus and validation mechanisms.
- async neurons(netuid, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves a list of all neurons within a specified subnet of the Bittensor network. This function provides a snapshot of the subnet’s neuron population, including each neuron’s attributes and network interactions.
- Parameters:
- Returns:
A list of NeuronInfo objects detailing each neuron’s characteristics in the subnet.
- Return type:
list[bittensor.core.chain_data.NeuronInfo]
Understanding the distribution and status of neurons within a subnet is key to comprehending the network’s decentralized structure and the dynamics of its consensus and governance processes.
- async neurons_lite(netuid, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves a list of neurons in a ‘lite’ format from a specific subnet of the Bittensor network. This function provides a streamlined view of the neurons, focusing on key attributes such as stake and network participation.
- Parameters:
- Returns:
A list of simplified neuron information for the subnet.
- Return type:
list[bittensor.core.chain_data.NeuronInfoLite]
This function offers a quick overview of the neuron population within a subnet, facilitating efficient analysis of the network’s decentralized structure and neuron dynamics.
- async poke_deposit(wallet, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)#
Adjusts deposits made for proxies and announcements based on current values.
This method recalculates and updates the locked deposit amounts for both proxy relationships and announcements for the signing account. It can be used to potentially lower the locked amount if the deposit requirements have changed (e.g., due to runtime upgrades or changes in the number of proxies/announcements).
- Parameters:
wallet (bittensor_wallet.Wallet) – Bittensor wallet object (the account whose deposits will be adjusted).
period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Whether to wait for the inclusion of the transaction.
wait_for_finalization (bool) – Whether to wait for the finalization of the transaction.
- Returns:
The result object of the extrinsic execution.
- Return type:
Note
This method automatically adjusts deposits for both proxy relationships and announcements. No parameters are needed as it operates on the account’s current state.
- When to use:
After runtime upgrade, if deposit constants have changed.
After removing proxies/announcements, to free up excess locked funds.
Periodically to optimize locked deposit amounts.
- async proxy(wallet, real_account_ss58, force_proxy_type, call, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)#
Executes a call on behalf of the real account through a proxy.
This method allows a proxy account (delegate) to execute a call on behalf of the real account (delegator). The call is subject to the permissions defined by the proxy type and must respect the delay period if one was set when the proxy was added.
- Parameters:
wallet (bittensor_wallet.Wallet) – Bittensor wallet object (should be the proxy account wallet).
real_account_ss58 (str) – The SS58 address of the real account on whose behalf the call is being made.
force_proxy_type (Optional[Union[str, bittensor.core.chain_data.ProxyType]]) – The type of proxy to use for the call. If
None, any proxy type can be used. Otherwise, must match one of the allowed proxy types. Can be a string or ProxyType enum value.call (scalecodec.GenericCall) – The inner call to be executed on behalf of the real account.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Whether to wait for the inclusion of the transaction.
wait_for_finalization (bool) – Whether to wait for the finalization of the transaction.
- Returns:
The result object of the extrinsic execution.
- Return type:
Notes
The call must be permitted by the proxy type. For example, a “NonTransfer” proxy cannot execute transfer calls. The delay period must also have passed since the proxy was added.
- async proxy_announced(wallet, delegate_ss58, real_account_ss58, force_proxy_type, call, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)#
Executes an announced call on behalf of the real account through a proxy.
This method executes a call that was previously announced via
announce_proxy(). The call must match the call_hash that was announced, and the delay period must have passed since the announcement was made. The real account has the opportunity to review and reject the announcement before execution.- Parameters:
wallet (bittensor_wallet.Wallet) – Bittensor wallet object (should be the proxy account wallet that made the announcement).
delegate_ss58 (str) – The SS58 address of the delegate proxy account that made the announcement.
real_account_ss58 (str) – The SS58 address of the real account on whose behalf the call will be made.
force_proxy_type (Optional[Union[str, bittensor.core.chain_data.ProxyType]]) – The type of proxy to use for the call. If
None, any proxy type can be used. Otherwise, must match one of the allowed proxy types. Can be a string or ProxyType enum value.call (scalecodec.GenericCall) – The inner call to be executed on behalf of the real account (must match the announced call_hash).
period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Whether to wait for the inclusion of the transaction.
wait_for_finalization (bool) – Whether to wait for the finalization of the transaction.
- Returns:
The result object of the extrinsic execution.
- Return type:
Notes
The call_hash of the provided call must match the call_hash that was announced. The announcement must not have been rejected by the real account, and the delay period must have passed.
- async query_constant(module_name, constant_name, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves a constant from the specified module on the Bittensor blockchain.
Use this function for nonstandard queries to constants defined within the Bittensor blockchain, if these cannot be accessed through other, standard getter methods.
- Parameters:
module_name (str) – The name of the module containing the constant (e.g.,
"Balances","SubtensorModule").constant_name (str) – The name of the constant to retrieve (e.g.,
"ExistentialDeposit").block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
A SCALE-decoded object if found,
Noneotherwise. Access the actual value using.valueattribute. Common types include int (for counts/blocks), Balance objects (for amounts in Rao), and booleans.- Return type:
Optional[async_substrate_interface.types.ScaleObj]
- async query_identity(coldkey_ss58, block=None, block_hash=None, reuse_block=False)[source]#
Queries the identity of a neuron on the Bittensor blockchain using the given key. This function retrieves detailed identity information about a specific neuron, which is a crucial aspect of the network’s decentralized identity and governance system.
- Parameters:
coldkey_ss58 (str) – Coldkey used to query the neuron’s identity (technically the neuron’s coldkey SS58 address).
block (Optional[int]) – The blockchain block number for the query.
block_hash (Optional[str]) – The hash of the blockchain block number at which to perform the query.
reuse_block (bool) – Whether to reuse the last-used blockchain block hash.
- Returns:
An object containing the identity information of the neuron if found,
Noneotherwise.- Return type:
Optional[bittensor.core.chain_data.chain_identity.ChainIdentity]
The identity information can include various attributes such as the neuron’s stake, rank, and other network-specific details, providing insights into the neuron’s role and status within the Bittensor network.
Note
See the Bittensor CLI documentation for supported identity parameters.
- async query_map(module, name, params=None, block=None, block_hash=None, reuse_block=False)[source]#
Queries map storage from any module on the Bittensor blockchain.
Use this function for nonstandard queries to map storage defined within the Bittensor blockchain, if these cannot be accessed through other, standard getter methods.
- Parameters:
module (str) – The name of the module from which to query the map storage (e.g., “SubtensorModule”, “System”).
name (str) – The specific storage function within the module to query (e.g., “Bonds”, “Weights”).
params (Optional[list]) – Parameters to be passed to the query.
block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
A data structure representing the map storage if found, None otherwise.
- Return type:
AsyncQueryMapResult
- async query_map_subtensor(name, params=None, block=None, block_hash=None, reuse_block=False)[source]#
Queries map storage from the Subtensor module on the Bittensor blockchain.
Use this function for nonstandard queries to map storage defined within the Bittensor blockchain, if these cannot be accessed through other, standard getter methods.
- Parameters:
name (str) – The name of the map storage function to query.
params (Optional[list]) – A list of parameters to pass to the query function.
block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
An object containing the map-like data structure, or
Noneif not found.- Return type:
async_substrate_interface.AsyncQueryMapResult
- async query_module(module, name, params=None, block=None, block_hash=None, reuse_block=False)[source]#
Queries any module storage on the Bittensor blockchain with the specified parameters and block number. This function is a generic query interface that allows for flexible and diverse data retrieval from various blockchain modules. Use this function for nonstandard queries to storage defined within the Bittensor blockchain, if these cannot be accessed through other, standard getter methods.
- Parameters:
module (str) – The name of the module from which to query data.
name (str) – The name of the storage function within the module.
params (Optional[list]) – A list of parameters to pass to the query function.
block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
An object containing the requested data if found,
Noneotherwise.- Return type:
Optional[Union[async_substrate_interface.types.ScaleObj, Any]]
- async query_runtime_api(runtime_api, method, params, block=None, block_hash=None, reuse_block=False)[source]#
Queries the runtime API of the Bittensor blockchain, providing a way to interact with the underlying runtime and retrieve data encoded in Scale Bytes format. Use this function for nonstandard queries to the runtime
environment, if these cannot be accessed through other, standard getter methods.
- Parameters:
runtime_api (str) – The name of the runtime API to query.
method (str) – The specific method within the runtime API to call.
params (Optional[Union[list[Any], dict[str, Any]]]) – The parameters to pass to the method call.
block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
The decoded result from the runtime API call, or
Noneif the call fails.- Return type:
Optional[Any]
- async query_subtensor(name, params=None, block=None, block_hash=None, reuse_block=False)[source]#
Queries named storage from the Subtensor module on the Bittensor blockchain.
Use this function for nonstandard queries to storage defined within the Bittensor blockchain, if these cannot be accessed through other, standard getter methods.
- Parameters:
name (str) – The name of the storage function to query.
params (Optional[list]) – A list of parameters to pass to the query function.
block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
An object containing the requested data.
- Return type:
query_response
- async recycle(netuid, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves the ‘Burn’ hyperparameter for a specified subnet.
The ‘Burn’ parameter represents the amount of TAO that is recycled when registering a neuron on this subnet. Recycled tokens are removed from circulation but can be re-emitted, unlike burned tokens which are permanently removed.
- Parameters:
netuid (int) – The unique identifier of the subnet.
block (Optional[int]) – The blockchain block number for the query.
block_hash (Optional[str]) – The hash of the block at which to query. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
The amount of TAO recycled per neuron registration, or
Noneif the subnet does not exist.- Return type:
Optional[bittensor.utils.balance.Balance]
- async refund_crowdloan(wallet, crowdloan_id, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)#
Refunds contributors from a failed crowdloan campaign that did not reach its cap.
Refunds are batched, processing up to
RefundContributorsLimit(default 50) contributors per call. For campaigns with more contributors, multiple calls are required. Only non-creator contributors are refunded; the creator’s deposit remains until dissolution viadissolve_crowdloan.Only the crowdloan creator can call this method for a non-finalized crowdloan.
- Parameters:
wallet (bittensor_wallet.Wallet) – Bittensor wallet instance used to sign the transaction (must be the crowdloan creator).
crowdloan_id (int) – The unique identifier of the crowdloan to refund.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after submission.
raise_error (bool) – If
True, raises an exception rather than returning failure in the response.wait_for_inclusion (bool) – Whether to wait for the extrinsic to be included in a block.
wait_for_finalization (bool) – Whether to wait for finalization of the extrinsic.
- Returns:
ExtrinsicResponseindicating success or failure, with error details if applicable.- Return type:
Notes
Crowdloans Overview: <https://docs.learnbittensor.org/subnets/crowdloans>
Crowdloan Lifecycle: <https://docs.learnbittensor.org/subnets/crowdloans#crowdloan-lifecycle>
Refund and Dissolve: <https://docs.learnbittensor.org/subnets/crowdloans/crowdloans-tutorial#alternative-path-refund-and-dissolve>
- async register(wallet, netuid, max_allowed_attempts=3, output_in_place=False, cuda=False, dev_id=0, tpb=256, num_processes=None, update_interval=None, log_verbose=False, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)[source]#
Registers a neuron on the Bittensor subnet with provided netuid using the provided wallet.
Registration is a critical step for a neuron to become an active participant in the network, enabling it to stake, set weights, and receive incentives.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet associated with the neuron to be registered.
netuid (int) – The unique identifier of the subnet.
max_allowed_attempts (int) – Maximum number of attempts to register the wallet.
output_in_place (bool) – If true, prints the progress of the proof of work to the console in-place. Meaning the progress is printed on the same lines.
cuda (bool) – If
true, the wallet should be registered using CUDA device(s).dev_id (Union[list[int], int]) – The CUDA device id to use, or a list of device ids.
tpb (int) – The number of threads per block (CUDA).
num_processes (Optional[int]) – The number of processes to use to register.
update_interval (Optional[int]) – The number of nonces to solve between updates.
log_verbose (bool) – If
true, the registration process will log more information.period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Whether to wait for the inclusion of the transaction.
wait_for_finalization (bool) – Whether to wait for the finalization of the transaction.
- Returns:
The result object of the extrinsic execution.
- Return type:
This function facilitates the entry of new neurons into the network, supporting the decentralized growth and scalability of the Bittensor ecosystem.
Notes
- async register_subnet(wallet, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)[source]#
Registers a new subnetwork on the Bittensor network.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet to be used for subnet registration.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Whether to wait for the extrinsic to be included in a block.
wait_for_finalization (bool) – Whether to wait for finalization of the extrinsic.
- Returns:
The result object of the extrinsic execution.
- Return type:
- async reject_proxy_announcement(wallet, delegate_ss58, call_hash, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)#
Rejects an announcement made by a proxy delegate.
This method allows the real account to reject an announcement made by a proxy delegate, preventing the announced call from being executed. Once rejected, the announcement cannot be executed and the announcement deposit is returned to the delegate.
- Parameters:
wallet (bittensor_wallet.Wallet) – Bittensor wallet object (should be the real account wallet).
delegate_ss58 (str) – The SS58 address of the delegate proxy account whose announcement is being rejected.
call_hash (str) – The hash of the call that was announced and is now being rejected.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Whether to wait for the inclusion of the transaction.
wait_for_finalization (bool) – Whether to wait for the finalization of the transaction.
- Returns:
The result object of the extrinsic execution.
- Return type:
Notes
Once rejected, the announcement cannot be executed. The delegate’s announcement deposit is returned.
- async remove_liquidity(wallet, netuid, position_id, hotkey_ss58=None, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)[source]#
Remove liquidity and credit balances back to wallet’s hotkey stake.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet used to sign the extrinsic (must be unlocked).
netuid (int) – The UID of the target subnet for which the call is being initiated.
position_id (int) – The id of the position record in the pool.
hotkey_ss58 (Optional[str]) – The hotkey with staked TAO in Alpha. If not passed then the wallet hotkey is used.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Whether to wait for the extrinsic to be included in a block.
wait_for_finalization (bool) – Whether to wait for finalization of the extrinsic.
- Returns:
The result object of the extrinsic execution.
- Return type:
Note
Adding is allowed even when user liquidity is enabled in specified subnet. Call toggle_user_liquidity extrinsic to enable/disable user liquidity.
To get the position_id use get_liquidity_list method.
- async remove_proxies(wallet, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)#
Removes all proxy relationships for the account in a single transaction.
This method removes all proxy relationships for the signing account in a single call, which is more efficient than removing them one by one using
remove_proxy(). The deposit for all proxies will be returned to the account.- Parameters:
wallet (bittensor_wallet.Wallet) – Bittensor wallet object. The account whose proxies will be removed (the delegator). All proxy relationships where wallet.coldkey.ss58_address is the real account will be removed.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Whether to wait for the inclusion of the transaction.
wait_for_finalization (bool) – Whether to wait for the finalization of the transaction.
- Returns:
The result object of the extrinsic execution.
- Return type:
Notes
This removes all proxy relationships for the account, regardless of proxy type or delegate. Use
remove_proxy()if you need to remove specific proxy relationships selectively.
- async remove_proxy(wallet, delegate_ss58, proxy_type, delay, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)#
Removes a specific proxy relationship.
This method removes a single proxy relationship between the real account and a delegate. The parameters must exactly match those used when the proxy was added via
add_proxy(). The deposit for this proxy will be returned to the account.- Parameters:
wallet (bittensor_wallet.Wallet) – Bittensor wallet object.
delegate_ss58 (str) – The SS58 address of the delegate proxy account to remove.
proxy_type (Union[str, bittensor.core.chain_data.ProxyType]) – The type of proxy permissions to remove. Can be a string or ProxyType enum value.
delay (int) – The announcement delay value (in blocks) for the proxy being removed. Must exactly match the delay value that was set when the proxy was originally added via
add_proxy(). This is a required identifier for the specific proxy relationship, not a delay before removal takes effect (removal is immediate).period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Whether to wait for the inclusion of the transaction.
wait_for_finalization (bool) – Whether to wait for the finalization of the transaction.
- Returns:
The result object of the extrinsic execution.
- Return type:
Notes
The delegate_ss58, proxy_type, and delay parameters must exactly match those used when the proxy was added. Use
get_proxies_for_real_account()to retrieve the exact parameters for existing proxies.
- async remove_proxy_announcement(wallet, real_account_ss58, call_hash, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)#
Removes an announcement made by a proxy account.
This method allows the proxy account to remove its own announcement before it is executed or rejected. This frees up the announcement deposit and prevents the call from being executed. Only the proxy account that made the announcement can remove it.
- Parameters:
wallet (bittensor_wallet.Wallet) – Bittensor wallet object (should be the proxy account wallet that made the announcement).
real_account_ss58 (str) – The SS58 address of the real account on whose behalf the call was announced.
call_hash (str) – The hash of the call that was announced and is now being removed.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Whether to wait for the inclusion of the transaction.
wait_for_finalization (bool) – Whether to wait for the finalization of the transaction.
- Returns:
The result object of the extrinsic execution.
- Return type:
Notes
Only the proxy account that made the announcement can remove it. The real account can reject it via
reject_proxy_announcement(), but cannot remove it directly.
- async reveal_weights(wallet, netuid, uids, weights, salt, mechid=0, max_attempts=5, version_key=version_as_int, period=16, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)[source]#
Reveals the weights for a specific subnet on the Bittensor blockchain using the provided wallet. This action serves as a revelation of the neuron’s previously committed weight distribution.
- Parameters:
wallet (bittensor_wallet.Wallet) – Bittensor Wallet instance.
netuid (int) – The unique identifier of the subnet.
uids (bittensor.core.types.UIDs) – NumPy array of neuron UIDs for which weights are being revealed.
weights (bittensor.core.types.Weights) – NumPy array of weight values corresponding to each UID.
salt (bittensor.core.types.Salt) – NumPy array of salt values corresponding to the hash function.
mechid (int) – The subnet mechanism unique identifier.
max_attempts (int) – The number of maximum attempts to reveal weights.
version_key (int) – Version key for compatibility with the network.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Waits for the transaction to be included in a block.
wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain.
- Returns:
The result object of the extrinsic execution.
- Return type:
This function allows neurons to reveal their previously committed weight distribution, ensuring transparency and accountability within the Bittensor network.
- async root_register(wallet, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)[source]#
Register neuron by recycling some TAO.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet associated with the neuron to be registered.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Waits for the transaction to be included in a block.
wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain.
- Returns:
The result object of the extrinsic execution.
- Return type:
Notes
- async root_set_pending_childkey_cooldown(wallet, cooldown, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)[source]#
Sets the pending childkey cooldown.
- Parameters:
wallet (bittensor_wallet.Wallet) – bittensor wallet instance.
cooldown (int) – the number of blocks to setting pending childkey cooldown.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Waits for the transaction to be included in a block.
wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain.
- Returns:
The result object of the extrinsic execution.
- Return type:
Note
This operation can only be successfully performed if your wallet has root privileges.
- async serve_axon(netuid, axon, certificate=None, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)[source]#
Registers an Axon endpoint on the network for receiving queries from other neurons.
This method publishes your neuron’s IP address, port, and protocol information to the blockchain, making it discoverable by other neurons in the subnet. Optionally, you can include a TLS certificate to enable secure, encrypted communication via mutual TLS (mTLS).
When a certificate is provided, the blockchain stores both your endpoint information and your TLS public key, allowing other neurons to discover your certificate and establish encrypted connections. When re-serving with updated metadata (including a new certificate), the previous values are overwritten.
- Parameters:
netuid (int) – The unique identifier of the subnetwork.
axon (bittensor.core.axon.Axon) – The Axon instance containing your endpoint configuration (IP, port, protocol).
certificate (Optional[bittensor.utils.Certificate]) – Optional TLS certificate for secure communication. Should contain a public key (up to 64 bytes) and algorithm identifier. If
None, standard unencrypted serving is used.period (Optional[int]) – The number of blocks during which the transaction will remain valid after submission. If not included in a block within this period, the transaction expires.
raise_error (bool) – If True, raises an exception on failure instead of returning an error response.
wait_for_inclusion (bool) – If True, waits for the transaction to be included in a block before returning.
wait_for_finalization (bool) – If True, waits for the transaction to be finalized on the blockchain.
- Returns:
ExtrinsicResponse containing the success status and transaction details. On success, the response includes the external IP and port that were registered.
- Return type:
Notes
- async set_auto_stake(wallet, netuid, hotkey_ss58, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)#
Sets the coldkey to automatically stake to the hotkey within specific subnet mechanism.
- Parameters:
wallet (bittensor_wallet.Wallet) – Bittensor Wallet instance.
netuid (int) – The subnet unique identifier.
hotkey_ss58 (str) – The SS58 address of the validator’s hotkey to which the miner automatically stakes all rewards received from the specified subnet immediately upon receipt.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Whether to wait for the inclusion of the transaction.
wait_for_finalization (bool) – Whether to wait for the finalization of the transaction.
- Returns:
The result object of the extrinsic execution.
- Return type:
Note
Use the get_auto_stakes method to get the hotkey address of the validator where auto stake is set.
- async set_children(wallet, hotkey_ss58, netuid, children, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)[source]#
Allows a coldkey to set children-keys.
- Parameters:
wallet (bittensor_wallet.Wallet) – bittensor wallet instance.
hotkey_ss58 (str) – The SS58 address of the neuron’s hotkey.
netuid (int) – The netuid value.
children (list[tuple[float, str]]) – A list of children with their proportions.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Waits for the transaction to be included in a block.
wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain.
- Returns:
The result object of the extrinsic execution.
- Return type:
- Raises:
DuplicateChild – There are duplicates in the list of children.
InvalidChild – Child is the hotkey.
NonAssociatedColdKey – The coldkey does not own the hotkey or the child is the same as the hotkey.
NotEnoughStakeToSetChildkeys – Parent key doesn’t have minimum own stake.
ProportionOverflow – The sum of the proportions does exceed uint64.
RegistrationNotPermittedOnRootSubnet – Attempting to register a child on the root network.
SubnetNotExists – Attempting to register to a non-existent network.
TooManyChildren – Too many children in request.
TxRateLimitExceeded – Hotkey hit the rate limit.
bittensor_wallet.errors.KeyFileError – Failed to decode keyfile data.
bittensor_wallet.errors.PasswordError – Decryption failed or wrong password for decryption provided.
- async set_commitment(wallet, netuid, data, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)#
Commits arbitrary data to the Bittensor network by publishing metadata. # TODO: check with @roman, is this about ‘arbitrary data’ or ‘commit-reveal’? we need a real example here if this is important.
This method allows neurons to publish arbitrary data to the blockchain, which can be used for various purposes such as sharing model updates, configuration data, or other network-relevant information. The data is encoded and stored on-chain as metadata.
- Parameters:
wallet: The wallet associated with the neuron committing the data. netuid: The unique identifier of the subnetwork. data: The data string to be committed to the network. The data will be encoded as bytes before submission. period: The number of blocks during which the transaction will remain valid after it’s submitted. If the
transaction is not included in a block within that number of blocks, it will expire and be rejected.
raise_error: Raises a relevant exception rather than returning False if unsuccessful. wait_for_inclusion: Whether to wait for the inclusion of the transaction. wait_for_finalization: Whether to wait for the finalization of the transaction.
- Returns:
ExtrinsicResponse: The result object of the extrinsic execution.
- Notes:
The data is automatically encoded as bytes before submission. There may be size limits on metadata payloads enforced by the chain.
- async set_delegate_take(wallet, hotkey_ss58, take, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)[source]#
Sets the delegate ‘take’ percentage for a neuron identified by its hotkey. The ‘take’ represents the percentage of rewards that the delegate claims from its nominators’ stakes.
- Parameters:
wallet (bittensor_wallet.Wallet) – bittensor wallet instance.
hotkey_ss58 (str) – The
SS58address of the neuron’s hotkey.take (float) – Percentage reward for the delegate.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Waits for the transaction to be included in a block.
wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain.
- Returns:
The result object of the extrinsic execution.
- Return type:
- Raises:
DelegateTakeTooHigh – Delegate take is too high.
DelegateTakeTooLow – Delegate take is too low.
DelegateTxRateLimitExceeded – A transactor exceeded the rate limit for delegate transaction.
HotKeyAccountNotExists – The hotkey does not exist.
NonAssociatedColdKey – Request to stake, unstake, or subscribe is made by a coldkey that is not associated with the hotkey account.
bittensor_wallet.errors.PasswordError – Decryption failed or wrong password for decryption provided.
bittensor_wallet.errors.KeyFileError – Failed to decode keyfile data.
The delegate take is a critical parameter in the network’s incentive structure, influencing the distribution of rewards among neurons and their nominators.
Notes
- async set_reveal_commitment(wallet, netuid, data, blocks_until_reveal=360, block_time=12, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)[source]#
Commits arbitrary data to the Bittensor network using timelock encryption for reveal scheduling. # TODO: check with @roman, is this about ‘arbitrary data’ or ‘commit-reveal’? we need a real example here if this is important, and documentating a real commit reveal flow.
This method commits data that will be automatically revealed after a specified number of blocks using drand timelock encryption. The data is encrypted using get_encrypted_commitment, which uses drand rounds to ensure the data cannot be revealed before the specified reveal time.
- # TODO how does work, why do you need blocks until reveal? isn’t this automatic for CR? does this allow you commit-reveal arbitrary other data for random reasons, or what?
The blocks_until_reveal parameter should match the subnet’s tempo (blocks per epoch) for epoch-based reveals. For fast blocks (10-second blocks), use block_time=10.0; for standard blocks (12-second blocks), use block_time=12.0.
- Parameters:
wallet: The wallet associated with the neuron committing the data. netuid: The unique identifier of the subnetwork. data: The data string to be committed to the network. blocks_until_reveal: The number of blocks from now after which the data will be revealed. Typically set to
the subnet’s tempo (blocks per epoch) for epoch-aligned reveals.
block_time: The number of seconds between each block (default 12.0 for standard blocks, 10.0 for fast blocks). period: The number of blocks during which the transaction will remain valid after it’s submitted. If the
transaction is not included in a block within that number of blocks, it will expire and be rejected.
raise_error: Raises a relevant exception rather than returning False if unsuccessful. wait_for_inclusion: Whether to wait for the inclusion of the transaction. wait_for_finalization: Whether to wait for the finalization of the transaction.
- Returns:
ExtrinsicResponse: The result object of the extrinsic execution. The response’s “data” field contains {“encrypted”: encrypted, “reveal_round”: reveal_round} on success.
- Notes:
A commitment can be set once per subnet epoch and is reset at the next epoch automatically. The timelock encryption ensures the data cannot be revealed before the specified drand round.
- async set_root_claim_type(wallet, new_root_claim_type, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)#
Submit an extrinsic to set the root claim type for the wallet’s coldkey.
The root claim type determines how future Alpha dividends from subnets are handled when they are claimed for the wallet’s coldkey:
"Swap": Alpha dividends are swapped to TAO at claim time and restaked on the Root Subnet (default)."Keep": Alpha dividends remain as Alpha on the originating subnets.
- Parameters:
wallet (bittensor_wallet.Wallet) – Bittensor
Walletinstance.new_root_claim_type (Literal['Swap', 'Keep']) – The new root claim type to set, either
"Swap"or"Keep".period (Optional[int]) – Number of blocks during which the transaction remains valid after submission. If the extrinsic is not included in a block within this window, it will expire and be rejected.
raise_error (bool) – Whether to raise a Python exception instead of returning a failed
ExtrinsicResponse.wait_for_inclusion (bool) – Whether to wait until the extrinsic is included in a block before returning.
wait_for_finalization (bool) – Whether to wait for finalization of the extrinsic in a block before returning.
- Returns:
ExtrinsicResponsedescribing the result of the extrinsic execution.
Notes
This setting applies to both automatic and manual root claims going forward; it does not retroactively change how already-claimed dividends were processed.
Only the treatment of Alpha dividends is affected; the underlying TAO stake on the Root Subnet is unchanged.
See: <https://docs.learnbittensor.org/staking-and-delegation/root-claims>
See also: <https://docs.learnbittensor.org/staking-and-delegation/root-claims/managing-root-claims>
- async set_subnet_identity(wallet, netuid, subnet_identity, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)[source]#
Sets the identity of a subnet for a specific wallet and network.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet instance that will authorize the transaction.
netuid (int) – The unique ID of the network on which the operation takes place.
subnet_identity (bittensor.core.chain_data.SubnetIdentity) – The identity data of the subnet including attributes like name, GitHub repository, contact, URL, discord, description, and any additional metadata.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Waits for the transaction to be included in a block.
wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain.
- Returns:
The result object of the extrinsic execution.
- Return type:
- async set_weights(wallet, netuid, uids, weights, mechid=0, block_time=12.0, commit_reveal_version=4, max_attempts=5, version_key=version_as_int, period=8, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)[source]#
Sets the weight vector for a neuron acting as a validator, specifying the weights assigned to subnet miners based on their performance evaluation.
This method allows subnet validators to submit their weight vectors, which rank the value of each subnet miner’s work. These weight vectors are used by the Yuma Consensus algorithm to compute emissions for both validators and miners.
The method automatically handles both commit-reveal-enabled subnets (CRv4) and direct weight setting. For commit-reveal subnets, weights are committed first and then revealed after the reveal period. The method respects rate limiting constraints enforced by _blocks_weight_limit.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet associated with the subnet validator setting the weights.
netuid (int) – The unique identifier of the subnet.
uids (bittensor.core.types.UIDs) – The list of subnet miner neuron UIDs that the weights are being set for.
weights (bittensor.core.types.Weights) – The corresponding weights to be set for each UID, representing the validator’s evaluation of each miner’s performance.
mechid (int) – The subnet mechanism unique identifier (default 0 for primary mechanism).
block_time (float) – The block duration in seconds (default 12.0). Used for timing calculations in commit-reveal operations.
commit_reveal_version (int) – The version of the commit-reveal protocol to use (default 4 for CRv4).
max_attempts (int) – The maximum number of attempts to set weights if rate limiting is encountered (default 5).
version_key (int) – Version key for compatibility with the network.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Waits for the transaction to be included in a block.
wait_for_finalization (bool) – Waits for the transaction to be finalized on the blockchain.
- Returns:
The result object of the extrinsic execution.
- Return type:
Example:
# Set weights directly (for non-commit-reveal subnets) response = await subtensor.set_weights( wallet=wallet, netuid=1, uids=[0, 1, 2], weights=[0.5, 0.3, 0.2] ) # For commit-reveal subnets, the method automatically handles commit and reveal phases
Notes
This function is crucial in the Yuma Consensus mechanism, where each validator’s weight vector contributes to the overall weight matrix used to calculate emissions and maintain network consensus.
- async sign_and_send_extrinsic(call, wallet, sign_with='coldkey', use_nonce=False, nonce_key='hotkey', period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=False, calling_function=None)[source]#
Helper method to sign and submit an extrinsic call to chain.
- Parameters:
call (scalecodec.GenericCall) – a prepared Call object
wallet (bittensor_wallet.Wallet) – the wallet whose coldkey will be used to sign the extrinsic
sign_with (str) – the wallet’s keypair to use for the signing. Options are “coldkey”, “hotkey”, “coldkeypub”
use_nonce (bool) – unique identifier for the transaction related with hot/coldkey.
nonce_key (str) – the type on nonce to use. Options are “hotkey” or “coldkey”.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – raises the relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – whether to wait until the extrinsic call is included on the chain
wait_for_finalization (bool) – whether to wait until the extrinsic call is finalized on the chain
calling_function (Optional[str]) – the name of the calling function.
- Returns:
The result object of the extrinsic execution.
- Return type:
- Raises:
SubstrateRequestException – Substrate request exception.
- async sim_swap(origin_netuid, destination_netuid, amount, block_hash=None)#
Simulates a swap/stake operation and calculates the fees and resulting amounts.
This method queries the SimSwap Runtime API to calculate the swap fees (in Alpha or TAO) and the quantities of Alpha or TAO tokens expected as output from the transaction. This simulation does NOT include the blockchain extrinsic transaction fee (the fee to submit the transaction itself).
When moving stake between subnets, the operation may involve swapping Alpha (subnet-specific stake token) to TAO (the base network token), then TAO to Alpha on the destination subnet. For subnet 0 (root network), all stake is in TAO.
- Parameters:
origin_netuid (int) – Netuid of the source subnet (0 if add stake).
destination_netuid (int) – Netuid of the destination subnet.
amount (bittensor.utils.balance.Balance) – Amount to swap/stake as a Balance object. Use
Balance.from_tao(...)orBalance.from_rao(...)to create the amount.block_hash (Optional[str]) – The hash of the blockchain block for the query. If
None, uses the current chain head.
- Returns:
Object containing
alpha_fee,tao_fee,alpha_amount, andtao_amountfields representing the swap fees and output amounts.- Return type:
Example:
# Simulate staking 100 TAO stake to subnet 1 result = await subtensor.sim_swap( origin_netuid=0, destination_netuid=1, amount=Balance.from_tao(100) ) print(f"Fee: {result.tao_fee.tao} TAO, Output: {result.alpha_amount} Alpha")
Notes
Alpha: Subnet-specific stake token (dynamic TAO)
TAO: Base network token; subnet 0 uses TAO directly
The returned fees do NOT include the extrinsic transaction fee
Transaction Fees: <https://docs.learnbittensor.org/learn/fees>
Glossary: <https://docs.learnbittensor.org/glossary>
- async start_call(wallet, netuid, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=False)[source]#
Submits a start_call extrinsic to the blockchain to trigger emission start for a subnet.
This method initiates the emission mechanism for a newly registered subnet. Once called, the subnet becomes “active” and begins receiving TAO emissions. Only the subnet owner (the wallet that registered the subnet) is authorized to call this method.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet used to sign the extrinsic (must be unlocked and must be the subnet owner).
netuid (int) – The unique identifier of the target subnet for which emissions are being started.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Whether to wait for the inclusion of the transaction.
wait_for_finalization (bool) – Whether to wait for the finalization of the transaction.
- Returns:
The result object of the extrinsic execution.
- Return type:
Notes
Only the subnet owner can call this method. After successful execution, the subnet becomes active and eligible for TAO emissions.
- async state_call(method, data, block=None, block_hash=None, reuse_block=False)[source]#
Makes a state call to the Bittensor blockchain, allowing for direct queries of the blockchain’s state. This function is typically used for advanced, nonstandard queries not provided by other getter methods.
Use this method when you need to query runtime APIs or storage functions that don’t have dedicated wrapper methods in the SDK. For standard queries, prefer the specific getter methods (e.g.,
get_balance,get_stake) which provide better type safety and error handling.- Parameters:
method (str) – The runtime API method name (e.g., “SubnetInfoRuntimeApi”, “get_metagraph”).
data (str) – Hex-encoded string of the SCALE-encoded parameters to pass to the method.
block (Optional[int]) – The block number to query. Do not specify if using
block_hashorreuse_block.block_hash (Optional[str]) – The block hash at which to check the parameter. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
The result of the rpc call.
- Return type:
dict[Any, Any]
- async subnet(netuid, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves the subnet information for a single subnet in the Bittensor network.
- Parameters:
- Returns:
A DynamicInfo object, containing detailed information about a subnet.
- Return type:
Optional[bittensor.core.chain_data.DynamicInfo]
- async subnet_exists(netuid, block=None, block_hash=None, reuse_block=False)[source]#
Checks if a subnet with the specified unique identifier (netuid) exists within the Bittensor network.
- Parameters:
- Returns:
Trueif the subnet exists,Falseotherwise.- Return type:
This function is critical for verifying the presence of specific subnets in the network, enabling a deeper understanding of the network’s structure and composition.
- async subnetwork_n(netuid, block=None, block_hash=None, reuse_block=False)[source]#
Returns the current number of registered neurons (UIDs) in a subnet.
- Parameters:
netuid (int) – The unique identifier of the subnetwork.
block (Optional[int]) – The blockchain block number for the query.
block_hash (Optional[str]) – The hash of the block at which to query. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
The current number of registered neurons in the subnet, or
Noneif the subnetwork does not exist.- Return type:
Optional[int]
- substrate#
- async swap_stake(wallet, hotkey_ss58, origin_netuid, destination_netuid, amount, safe_swapping=False, allow_partial_stake=False, rate_tolerance=0.005, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)[source]#
Moves stake between subnets while keeping the same coldkey-hotkey pair ownership.
This method swaps stake from one subnet to another, effectively moving the same stake amount (minus fees) from the origin subnet to the destination subnet. Like subnet hopping - same owner, same hotkey, just changing which subnet the stake is in.
The amount parameter is specified as a Balance object (in TAO or Alpha units depending on the subnet). The actual amount received may be less due to swap fees and potential slippage. When safe_swapping is enabled, the method uses price ratio checks to protect against unfavorable price movements during the swap.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet to swap stake from.
hotkey_ss58 (str) – The SS58 address of the hotkey whose stake is being swapped.
origin_netuid (int) – The netuid from which stake is removed.
destination_netuid (int) – The netuid to which stake is added.
amount (bittensor.utils.balance.Balance) – The amount to swap as a Balance object (in TAO or Alpha units). The actual amount received may be less due to swap fees and slippage.
safe_swapping (bool) – If
True, enables price safety checks to protect against fluctuating prices. The swap will only execute if the price ratio between subnets doesn’t exceed the rate tolerance.allow_partial_stake (bool) – If
Trueandsafe_swappingis enabled, allows partial stake swaps when the full amount would exceed the price tolerance. IfFalse, the entire swap fails if it would exceed the tolerance.rate_tolerance (float) – The maximum allowed increase in the price ratio between subnets (origin_price/destination_price). For example, 0.005 = 0.5% maximum increase. Only used when
safe_swappingisTrue.period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Whether to wait for the inclusion of the transaction.
wait_for_finalization (bool) – Whether to wait for the finalization of the transaction.
- Returns:
The result object of the extrinsic execution.
- Return type:
Notes
The price ratio for swap_stake in safe mode is calculated as: origin_subnet_price / destination_subnet_price. When
safe_swappingis enabled, the swap will only execute if: - Withallow_partial_stake=False: The entire swap amount can be executed without the price ratioincreasing more than
rate_tolerance.With
allow_partial_stake=True: A partial amount will be swapped up to the point where the price ratio would increase byrate_tolerance.Price Protection: <https://docs.learnbittensor.org/learn/price-protection>
Rate Limits: <https://docs.learnbittensor.org/learn/chain-rate-limits#staking-operations-rate-limits>
<https://docs.learnbittensor.org/navigating-subtensor/swap-stake>
- async tempo(netuid, block=None, block_hash=None, reuse_block=False)[source]#
Returns the Tempo hyperparameter for a subnet.
Tempo determines the length of an epoch in blocks. It defines how frequently the subnet’s consensus mechanism runs, calculating emissions and updating rankings. A tempo of 360 blocks equals approximately 72 minutes (360 blocks × 12 seconds per block).
- Parameters:
netuid (int) – The unique identifier of the subnetwork.
block (Optional[int]) – The blockchain block number for the query.
block_hash (Optional[str]) – The hash of the block at which to query. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
The tempo value in blocks, or
Noneif the subnetwork does not exist.- Return type:
Optional[int]
- async toggle_user_liquidity(wallet, netuid, enable, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)[source]#
Toggles the user liquidity feature for a specified subnet.
This method enables or disables user liquidity positions for a subnet. Only the subnet owner (the wallet that registered the subnet) is authorized to call this method.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet used to sign the extrinsic (must be unlocked and must be the subnet owner).
netuid (int) – The unique identifier of the target subnet for which user liquidity is being toggled.
enable (bool) – Boolean indicating whether to enable (
True) or disable (False) user liquidity.period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Whether to wait for the extrinsic to be included in a block.
wait_for_finalization (bool) – Whether to wait for finalization of the extrinsic.
- Returns:
The result object of the extrinsic execution.
- Return type:
Notes
Only the subnet owner can execute this call successfully.
- async transfer(wallet, destination_ss58, amount, transfer_all=False, keep_alive=True, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=False)[source]#
Transfers TAO tokens from the source wallet to a destination address.
This method transfers TAO tokens from the wallet’s coldkey to the specified destination address. The amount is specified as a Balance object (in TAO or Rao units). Use get_transfer_fee to pre-estimate the transaction fee before sending.
When keep_alive=True, the transfer ensures the source account maintains at least the existential deposit amount. If keep_alive=False, the transfer may reduce the source account balance below the existential deposit, which could result in the account being reaped (removed) from the chain.
- Parameters:
wallet (bittensor_wallet.Wallet) – Source wallet for the transfer (must be unlocked).
destination_ss58 (str) – Destination SS58 address for the transfer.
amount (Optional[bittensor.utils.balance.Balance]) – Amount of TAO to transfer as a Balance object. If
Noneandtransfer_all=True, transfers all available balance minus fees and existential deposit (ifkeep_alive=True).transfer_all (bool) – If
True, transfers all available tokens (minus fees and existential deposit ifkeep_alive=True). Ignored ifamountis specified.keep_alive (bool) – If
True, ensures the source account maintains at least the existential deposit amount. IfFalse, the transfer may reduce the balance below the existential deposit, potentially causing the account to be reaped.period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Whether to wait for the extrinsic to be included in a block.
wait_for_finalization (bool) – Whether to wait for finalization of the extrinsic.
- Returns:
The result object of the extrinsic execution.
- Return type:
Notes
The existential deposit is the minimum balance required to keep an account alive on the chain. Use
get_existential_deposit()to query the current value.
- async transfer_stake(wallet, destination_coldkey_ss58, hotkey_ss58, origin_netuid, destination_netuid, amount, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)[source]#
Transfers stake from one subnet to another while changing the coldkey owner.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet to transfer stake from.
destination_coldkey_ss58 (str) – The destination coldkey SS58 address.
hotkey_ss58 (str) – The hotkey SS58 address associated with the stake.
origin_netuid (int) – The source subnet UID.
destination_netuid (int) – The destination subnet UID.
amount (bittensor.utils.balance.Balance) – Amount to transfer.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Whether to wait for the extrinsic to be included in a block.
wait_for_finalization (bool) – Whether to wait for finalization of the extrinsic.
- Returns:
The result object of the extrinsic execution.
- Return type:
Notes
Price Protection: <https://docs.learnbittensor.org/learn/price-protection>
Rate Limits: <https://docs.learnbittensor.org/learn/chain-rate-limits#staking-operations-rate-limits>
- async tx_rate_limit(block=None, block_hash=None, reuse_block=False)[source]#
Retrieves the transaction rate limit for the Bittensor network as of a specific blockchain block. This rate limit sets the maximum number of transactions that can be processed within a given time frame.
- Parameters:
- Returns:
The transaction rate limit of the network,
Noneif not available.- Return type:
Optional[int]
The transaction rate limit is an essential parameter for ensuring the stability and scalability of the Bittensor network. It helps in managing network load and preventing congestion, thereby maintaining efficient and timely transaction processing.
- async unstake(wallet, netuid, hotkey_ss58, amount, allow_partial_stake=False, safe_unstaking=False, rate_tolerance=0.005, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)[source]#
Removes a specified amount of stake from a single hotkey account. This function is critical for adjusting individual neuron stakes within the Bittensor network.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet associated with the neuron from which the stake is being removed.
netuid (int) – The unique identifier of the subnet.
hotkey_ss58 (str) – The
SS58address of the hotkey account to unstake from.amount (bittensor.utils.balance.Balance) – The amount of alpha to unstake. If not specified, unstakes all. Alpha amount.
allow_partial_stake (bool) – If true and safe_staking is enabled, allows partial unstaking when the full amount would exceed the price tolerance. If false, the entire unstake fails if it would exceed the tolerance.
rate_tolerance (float) – The maximum allowed price change ratio when unstaking. For example, 0.005 = 0.5% maximum price decrease. Only used when safe_staking is True.
safe_unstaking (bool) – If true, enables price safety checks to protect against fluctuating prices. The unstake will only execute if the price change doesn’t exceed the rate tolerance.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Whether to wait for the extrinsic to be included in a block.
wait_for_finalization (bool) – Whether to wait for finalization of the extrinsic.
- Returns:
The result object of the extrinsic execution.
- Return type:
This function supports flexible stake management, allowing neurons to adjust their network participation and potential reward accruals.
Notes
Price Protection: <https://docs.learnbittensor.org/learn/price-protection>
Rate Limits: <https://docs.learnbittensor.org/learn/chain-rate-limits#staking-operations-rate-limits>
- async unstake_all(wallet, netuid, hotkey_ss58, rate_tolerance=0.005, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)[source]#
Unstakes all TAO/Alpha associated with a hotkey from the specified subnet on the Bittensor network.
This method unstakes all stake from a hotkey on a specific subnet. When rate_tolerance is specified, the method uses safe unstaking behavior to protect against unfavorable price movements due to liquidity/price impact. The rate_tolerance parameter limits the maximum price change ratio during the unstaking operation.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet of the stake owner (must be unlocked).
netuid (int) – The unique identifier of the subnet.
hotkey_ss58 (str) – The SS58 address of the hotkey to unstake from.
rate_tolerance (Optional[float]) – The maximum allowed price change ratio when unstaking (default 0.005 = 0.5% maximum price decrease). If
None, unstaking proceeds without price limit protection. Only used for subnets with liquidity pools where price impact may occur.period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Whether to wait for the extrinsic to be included in a block.
wait_for_finalization (bool) – Whether to wait for finalization of the extrinsic.
- Returns:
The result object of the extrinsic execution.
- Return type:
Example:
# If you would like to unstake all stakes in all subnets safely, use default `rate_tolerance` or pass your # value: import bittensor as bt subtensor = bt.AsyncSubtensor() wallet = bt.Wallet("my_wallet") netuid = 14 hotkey = "5%SOME_HOTKEY_WHERE_IS_YOUR_STAKE_NOW%" wallet_stakes = await subtensor.get_stake_info_for_coldkey(coldkey_ss58=wallet.coldkey.ss58_address) for stake in wallet_stakes: result = await subtensor.unstake_all( wallet=wallet, hotkey_ss58=stake.hotkey_ss58, netuid=stake.netuid, ) print(result) # If you would like to unstake all stakes in all subnets unsafely, use `rate_tolerance=None`: import bittensor as bt subtensor = bt.AsyncSubtensor() wallet = bt.Wallet("my_wallet") netuid = 14 hotkey = "5%SOME_HOTKEY_WHERE_IS_YOUR_STAKE_NOW%" wallet_stakes = await subtensor.get_stake_info_for_coldkey(coldkey_ss58=wallet.coldkey.ss58_address) for stake in wallet_stakes: result = await subtensor.unstake_all( wallet=wallet, hotkey_ss58=stake.hotkey_ss58, netuid=stake.netuid, rate_tolerance=None, ) print(result)
Notes
Slippage: <https://docs.learnbittensor.org/learn/slippage>
Price Protection: <https://docs.learnbittensor.org/learn/price-protection>
Rate Limits: <https://docs.learnbittensor.org/learn/chain-rate-limits#staking-operations-rate-limits>
Managing Stake with SDK: <https://docs.learnbittensor.org/staking-and-delegation/managing-stake-sdk>
- async unstake_multiple(wallet, netuids, hotkey_ss58s, amounts=None, unstake_all=False, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)[source]#
Performs batch unstaking from multiple hotkey accounts, allowing a neuron to reduce its staked amounts efficiently. This function is useful for managing the distribution of stakes across multiple neurons.
- Parameters:
wallet (bittensor_wallet.Wallet) – The wallet linked to the coldkey from which the stakes are being withdrawn.
netuids (bittensor.core.types.UIDs) – Subnets unique IDs.
hotkey_ss58s (list[str]) – A list of hotkey SS58 addresses to unstake from.
amounts (Optional[list[bittensor.utils.balance.Balance]]) – The amounts of TAO to unstake from each hotkey. If not provided, unstakes all.
unstake_all (bool) – If true, unstakes all tokens. If True amounts are ignored.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after it’s submitted. If the transaction is not included in a block within that number of blocks, it will expire and be rejected. You can think of it as an expiration date for the transaction.
raise_error (bool) – Raises a relevant exception rather than returning False if unsuccessful.
wait_for_inclusion (bool) – Whether to wait for the extrinsic to be included in a block.
wait_for_finalization (bool) – Whether to wait for finalization of the extrinsic.
- Returns:
The result object of the extrinsic execution.
- Return type:
Notes
Slippage: <https://docs.learnbittensor.org/learn/slippage>
Price Protection: <https://docs.learnbittensor.org/learn/price-protection>
Rate Limits: <https://docs.learnbittensor.org/learn/chain-rate-limits#staking-operations-rate-limits>
Managing Stake with SDK: <https://docs.learnbittensor.org/staking-and-delegation/managing-stake-sdk>
- async update_cap_crowdloan(wallet, crowdloan_id, new_cap, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)#
Updates the fundraising cap of an active (non-finalized) crowdloan.
Allows the creator to adjust the maximum total contribution amount before finalization. The new cap must be at least equal to the amount already raised. This is useful for adjusting campaign goals based on contributor feedback or changing subnet costs.
- Parameters:
wallet (bittensor_wallet.Wallet) – Bittensor wallet instance used to sign the transaction (must be the creator’s coldkey).
crowdloan_id (int) – The unique identifier of the crowdloan to update.
new_cap (bittensor.utils.balance.Balance) – The new fundraising cap (TAO). Must be
>= raised.period (Optional[int]) – The number of blocks during which the transaction will remain valid after submission.
raise_error (bool) – If
True, raises an exception rather than returning failure in the response.wait_for_inclusion (bool) – Whether to wait for the extrinsic to be included in a block.
wait_for_finalization (bool) – Whether to wait for finalization of the extrinsic.
- Returns:
ExtrinsicResponseindicating success or failure, with error details if applicable.- Return type:
Notes
Only the creator can update the cap.
The crowdloan must not be finalized.
The new cap must be
>=the total funds already raised.Crowdloans Overview: <https://docs.learnbittensor.org/subnets/crowdloans>
Update Parameters: <https://docs.learnbittensor.org/subnets/crowdloans#crowdloan-lifecycle>
- async update_end_crowdloan(wallet, crowdloan_id, new_end, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)#
Updates the end block of an active (non-finalized) crowdloan.
Allows the creator to extend (or shorten) the contribution period before finalization. The new end block must be in the future and respect the minimum and maximum duration bounds defined in the runtime constants. This is useful for extending campaigns that need more time to reach their cap or shortening campaigns with sufficient contributions.
- Parameters:
wallet (bittensor_wallet.Wallet) – Bittensor wallet instance used to sign the transaction (must be the creator’s coldkey).
crowdloan_id (int) – The unique identifier of the crowdloan to update.
new_end (int) – The new block number at which the crowdloan will end. Must be between
MinimumBlockDuration(7 days = 50,400 blocks) andMaximumBlockDuration(60 days = 432,000 blocks) from the current block.period (Optional[int]) – The number of blocks during which the transaction will remain valid after submission.
raise_error (bool) – If
True, raises an exception rather than returning failure in the response.wait_for_inclusion (bool) – Whether to wait for the extrinsic to be included in a block.
wait_for_finalization (bool) – Whether to wait for finalization of the extrinsic.
- Returns:
ExtrinsicResponseindicating success or failure, with error details if applicable.- Return type:
Notes
Only the creator can update the end block.
The crowdloan must not be finalized.
The new end block must respect duration bounds (
MinimumBlockDurationtoMaximumBlockDuration).Crowdloans Overview: <https://docs.learnbittensor.org/subnets/crowdloans>
Update Parameters: <https://docs.learnbittensor.org/subnets/crowdloans#crowdloan-lifecycle>
- async update_min_contribution_crowdloan(wallet, crowdloan_id, new_min_contribution, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)#
Updates the minimum contribution amount of an active (non-finalized) crowdloan.
Allows the creator to adjust the minimum per-contribution amount before finalization. The new value must meet or exceed the
AbsoluteMinimumContributionconstant. This is useful for adjusting contribution requirements based on the number of expected contributors or campaign strategy.- Parameters:
wallet (bittensor_wallet.Wallet) – Bittensor wallet instance used to sign the transaction (must be the creator’s coldkey).
crowdloan_id (int) – The unique identifier of the crowdloan to update.
new_min_contribution (bittensor.utils.balance.Balance) – The new minimum contribution amount (TAO). Must be
>= AbsoluteMinimumContribution.period (Optional[int]) – The number of blocks during which the transaction will remain valid after submission.
raise_error (bool) – If
True, raises an exception rather than returning failure in the response.wait_for_inclusion (bool) – Whether to wait for the extrinsic to be included in a block.
wait_for_finalization (bool) – Whether to wait for finalization of the extrinsic.
- Returns:
ExtrinsicResponseindicating success or failure, with error details if applicable.- Return type:
Notes
Only the creator can update the minimum contribution.
The crowdloan must not be finalized.
The new minimum must be
>= AbsoluteMinimumContribution(check viaget_crowdloan_constants).Crowdloans Overview: <https://docs.learnbittensor.org/subnets/crowdloans>
Update Parameters: <https://docs.learnbittensor.org/subnets/crowdloans#crowdloan-lifecycle>
- async validate_extrinsic_params(call_module, call_function, call_params, block=None, block_hash=None, reuse_block=False)#
Validate and filter extrinsic parameters against on-chain metadata.
This method checks that the provided parameters match the expected signature of the given extrinsic (module and function) as defined in the Substrate metadata. It raises explicit errors for missing or invalid parameters and silently ignores any extra keys not present in the function definition.
- Parameters:
call_module (str) – The pallet name, e.g. “SubtensorModule” or “AdminUtils”.
call_function (str) – The extrinsic function name, e.g. “set_weights” or “sudo_set_tempo”.
call_params (dict[str, Any]) – A dictionary of parameters to validate.
block (Optional[int]) – The blockchain block number for the query.
block_hash (Optional[str]) – The blockchain block_hash representation of the block id.
reuse_block (bool) – Whether to reuse the last-used blockchain block hash.
- Returns:
A filtered dictionary containing only the parameters that are valid for the specified extrinsic.
- Raises:
ValueError – If the given module or function is not found in the chain metadata.
KeyError – If one or more required parameters are missing.
Notes
This method does not compose or submit the extrinsic. It only ensures that call_params conforms to the expected schema derived from on-chain metadata. See also compose_call and sign_and_send_extrinsic.
- async wait_for_block(block=None)[source]#
Waits until a specific block is reached on the chain. If no block is specified, waits for the next block.
- Parameters:
block (Optional[int]) – The block number to wait for. If
None, waits for the next block.- Returns:
Trueif the target block was reached,Falseif timeout occurred.- Return type:
Example:
# Waits for a specific block await subtensor.wait_for_block(block=1234)
- async weights(netuid, mechid=0, block=None, block_hash=None, reuse_block=False)[source]#
Retrieves the weight distribution set by neurons within a specific subnet of the Bittensor network. This function maps each neuron’s UID to the weights it assigns to other neurons, reflecting the network’s trust and value assignment mechanisms.
- Parameters:
netuid (int) – Subnet unique identifier.
mechid (int) – Subnet mechanism unique identifier.
block (Optional[int]) – The blockchain block number for the query.
block_hash (Optional[str]) – The blockchain block_hash representation of the block id.
reuse_block (bool) – Whether to reuse the last-used blockchain block hash.
- Returns:
A list of tuples mapping each neuron’s UID to its assigned weights.
- Return type:
The weight distribution is a key factor in the network’s consensus algorithm and the ranking of neurons, influencing their influence and reward allocation within the subnet.
- async weights_rate_limit(netuid, block=None, block_hash=None, reuse_block=False)[source]#
Returns the WeightsSetRateLimit hyperparameter for a subnet.
This hyperparameter limits how many times a validator can set weights per epoch. It prevents validators from spamming weight updates and ensures stable consensus calculations. Once the limit is reached, validators must wait until the next epoch to set weights again.
- Parameters:
netuid (int) – The unique identifier of the subnetwork.
block (Optional[int]) – The blockchain block number for the query.
block_hash (Optional[str]) – The hash of the block at which to query. Do not set if using
blockorreuse_block.reuse_block (bool) – Whether to reuse the last-used block hash. Do not set if using
block_hashorblock.
- Returns:
- The maximum number of weight set operations allowed per epoch, or
Noneif the subnetwork does not exist or the parameter is not found.
- The maximum number of weight set operations allowed per epoch, or
- Return type:
Optional[int]
- async withdraw_crowdloan(wallet, crowdloan_id, period=DEFAULT_PERIOD, raise_error=False, wait_for_inclusion=True, wait_for_finalization=True)#
Withdraws a contribution from an active (not yet finalized or dissolved) crowdloan.
Contributors can withdraw their contributions at any time before finalization. For regular contributors, the full contribution amount is returned. For the creator, only amounts exceeding the initial deposit can be withdrawn; the deposit itself remains locked until dissolution.
- Parameters:
wallet (bittensor_wallet.Wallet) – Bittensor wallet instance used to sign the transaction (coldkey must match a contributor).
crowdloan_id (int) – The unique identifier of the crowdloan to withdraw from.
period (Optional[int]) – The number of blocks during which the transaction will remain valid after submission, after which it will be rejected.
raise_error (bool) – If
True, raises an exception rather than returning False in the response, in case the transaction fails.wait_for_inclusion (bool) – Whether to wait for the extrinsic to be included in a block.
wait_for_finalization (bool) – Whether to wait for finalization of the extrinsic.
- Returns:
ExtrinsicResponseindicating success or failure, with error details if applicable.- Return type:
Notes
Crowdloans Overview: <https://docs.learnbittensor.org/subnets/crowdloans>
Crowdloan Lifecycle: <https://docs.learnbittensor.org/subnets/crowdloans#crowdloan-lifecycle>
Withdraw: <https://docs.learnbittensor.org/subnets/crowdloans/crowdloans-tutorial#optional-withdraw>
- async bittensor.core.async_subtensor.get_async_subtensor(network=None, config=None, mock=False, log_verbose=False)[source]#
Factory method to create an initialized AsyncSubtensor instance.
This function creates an AsyncSubtensor instance and automatically initializes the connection to the blockchain. This is useful when you don’t want to manually call
await subtensor.initialize()after instantiation.- Parameters:
network (Optional[str]) – The network name to connect to (e.g.,
"finney"for Bittensor mainnet,"test"for test network,"local"for a locally deployed blockchain). IfNone, uses the default network from config.config (Optional[bittensor.core.config.Config]) – Configuration object for the AsyncSubtensor instance. If
None, uses the default configuration.mock (bool) – Whether this is a mock instance. FOR TESTING ONLY.
log_verbose (bool) – Enables or disables verbose logging.
- Returns:
An initialized AsyncSubtensor instance ready for use.
- Return type:
Example:
# Create and initialize in one step subtensor = await get_async_subtensor(network="finney") # Ready to use immediately block = await subtensor.get_current_block()