Bittensor SDK
Bittensor Python SDK skill covers the full v8.x API: Subtensor (~130 methods for staking, registration, weights, liquidity, proxy, coldkey swaps), AsyncSubtensor, Metagraph (5 variants), Axon/Dendrite/Synapse networking stack, 26 chain data models, 18 sync + 18 async extrinsic modules, SubtensorApi wrapper with 14 sub-APIs, dev test framework (~184 call blueprints), Drand timelock encryption, and all utils (Balance, btlogging state machine, weight processing, Uniswap V3 liquidity math, etc.).
ๆ่ฝ่ฏดๆ
name: bittensor-sdk description: "Complete Bittensor SDK reference โ Subtensor, AsyncSubtensor, Metagraph, Axon, Dendrite, Synapse, chain_data models, extrinsics (sync + async), extras (subtensor_api, dev_framework, timelock), and utils (balance, btlogging, weight_utils, registration, liquidity, networking, version). Use for any bittensor operation: wallet management, staking, subnet ops, neuron registration, metagraph queries, emissions tracking, liquidity management, MEV protection, proxy delegation, coldkey swaps, crowdloans, weight setting, and more." license: MIT compatibility: Requires Python 3.8+, bittensor>=8.0.0, network access to Bittensor network endpoints metadata: author: taoli twitter: taoleeh github: taoleeh website: bittensor.quest version: "2.0.0"
Bittensor SDK โ Complete API Reference
Comprehensive reference for the Bittensor Python SDK. Based on the full autoapi documentation.
Package Structure
bittensor/
โโโ core/
โ โโโ subtensor โ Synchronous blockchain interface (main class)
โ โโโ async_subtensor โ Asynchronous blockchain interface
โ โโโ metagraph โ Subnet state representation (sync/async/torch/nontorch)
โ โโโ axon โ Server-side neuron endpoint (FastAPI)
โ โโโ dendrite โ Client-side network request sender
โ โโโ synapse โ Communication schema between neurons (Pydantic)
โ โโโ stream โ Streaming response model
โ โโโ tensor โ Tensor serialization utilities
โ โโโ threadpool โ Priority thread pool for Axon
โ โโโ config โ Configuration management
โ โโโ settings โ Default settings
โ โโโ types โ Shared type aliases and mixins
โ โโโ errors โ Exception hierarchy
โ โโโ chain_data/ โ 26 data models for chain state
โ โโโ extrinsics/ โ Sync + async extrinsic operations + pallet definitions
โโโ extras/
โ โโโ subtensor_api/ โ High-level SubtensorApi wrapper with 14 sub-APIs
โ โโโ dev_framework/ โ Test framework with ~184 namedtuple call blueprints
โ โโโ timelock/ โ Drand-based time-lock encryption
โโโ utils/
โโโ balance โ Balance type (TAO/Rao conversion)
โโโ btlogging/ โ Custom logging subsystem (6 modules)
โโโ weight_utils โ Weight normalization/conversion (12 functions)
โโโ registration/ โ Registration utilities + torch compat
โโโ liquidity โ Uniswap V3-style liquidity math
โโโ networking โ IP/port utilities
โโโ formatting โ Human-readable number formatting
โโโ subnets โ Community SubnetsAPI base class
โโโ version โ PyPI version checker
โโโ axon_utils โ Nonce window calculations
โโโ easy_imports โ Centralized import hub
Quick Start
import bittensor as bt
# Connect to network
subtensor = bt.Subtensor(network="finney")
# or async:
# subtensor = bt.AsyncSubtensor(network="finney")
# Wallet
wallet = bt.Wallet(name="my_wallet", hotkey="my_hotkey")
# Metagraph
metagraph = subtensor.metagraph(netuid=1)
# Stake
from bittensor import Balance
subtensor.add_stake(wallet, netuid=1, hotkey_ss58=wallet.hotkey.ss58_address,
amount=Balance.from_tao(10.0))
# Set weights
import numpy as np
subtensor.set_weights(wallet, netuid=1, uids=np.array([0,1,2]),
weights=np.array([0.3, 0.4, 0.3]))
Core Modules
bittensor.core.subtensor โ Subtensor (Synchronous)
Subtensor(network=None, config=None, log_verbose=False, fallback_endpoints=None,
retry_forever=False, archive_endpoints=None, mock=False)
Staking & Liquidity:
add_stake(wallet, netuid, hotkey_ss58, amount, safe_staking=False, allow_partial_stake=False, rate_tolerance=0.005, ...)โ Stake TAOadd_stake_burn(wallet, netuid, hotkey_ss58, amount, limit_price=None, ...)โ Subnet buybackadd_stake_multiple(wallet, netuids, hotkey_ss58s, amounts, ...)โ Bulk stakeadd_liquidity(wallet, netuid, liquidity, price_low, price_high, hotkey_ss58=None, ...)โ Add liquidityremove_liquidity(wallet, netuid, position_id, hotkey_ss58=None, ...)โ Remove liquiditymodify_liquidity(wallet, netuid, position_id, liquidity_delta, hotkey_ss58=None, ...)โ Modify positionmove_stake(wallet, origin_netuid, origin_hotkey, dest_netuid, dest_hotkey, amount, ...)โ Move stake between subnetsswap_stake(wallet, origin_netuid, dest_netuid, hotkey_ss58, amount, limit_price=None, ...)โ Swap Alpha between subnetstransfer_stake(wallet, origin_netuid, dest_netuid, dest_coldkey, hotkey_ss58, amount, ...)โ Transfer stake to new ownerunstake(wallet, netuid, hotkey_ss58, amount, ...)โ Unstake partialunstake_all(wallet, hotkey_ss58, ...)โ Unstake allunstake_multiple(wallet, netuids, hotkey_ss58s, amounts, ...)โ Bulk unstake
Registration:
register(wallet, netuid, ...)โ POW registrationburned_register(wallet, netuid, ...)โ Burn registration (recycle TAO)register_limit(wallet, netuid, limit_price, ...)โ Registration with price caproot_register(wallet, ...)โ Root network registration
Weights:
set_weights(wallet, netuid, uids, weights, version_key=..., ...)โ Direct weight settingcommit_weights(wallet, netuid, salt, uids, weights, mechid=0, ...)โ Commit-reveal step 1reveal_weights(wallet, netuid, uids, weights, salt, ...)โ Commit-reveal step 2commit_reveal_enabled(netuid, block=None)โ Check if commit-reveal is active
Serving:
serve_axon(wallet, netuid, ip, port, protocol, version, ...)โ Register axon endpointserve_axon_tls(wallet, netuid, ip, port, protocol, version, certificate, ...)โ Register TLS axonserve_prometheus(wallet, netuid, ip, port, version, ...)โ Register Prometheus endpoint
Proxy & Delegation:
add_proxy(wallet, delegate_ss58, proxy_type, delay, ...)โ Add proxy relationshipremove_proxy(wallet, delegate_ss58, proxy_type, delay, ...)โ Remove proxyremove_proxies(wallet, ...)โ Remove all proxiesannounce_proxy(wallet, real_account_ss58, call_hash, ...)โ Announce proxy callproxy(wallet, real_account_ss58, call, ...)โ Execute via proxy
Coldkey Swaps:
announce_coldkey_swap(wallet, new_coldkey_ss58, ...)โ Announce swap intentswap_coldkey_announced(wallet, new_coldkey_ss58, ...)โ Execute announced swapclear_coldkey_swap_announcement(wallet, ...)โ Withdraw announcementdispute_coldkey_swap(wallet, ...)โ Dispute active swap
Root Operations:
claim_root(wallet, netuids, ...)โ Claim root dividendsset_root_claim_type(wallet, new_root_claim_type, ...)โ Set root claim mechanism
Children (Child-Hotkeys):
set_children(wallet, netuid, hotkey, children, ...)โ Set child hotkeysget_children(netuid, hotkey_ss58, block=None)โ Get children of hotkey
Queries (read-only, no wallet needed):
metagraph(netuid, block=None)โ Get metagraphget_subnet_info(netuid, block=None)โ Get subnet detailsall_subnets(block=None)โ All subnets with parametersget_balance(address, block=None)โ Get coldkey balanceget_stake(coldkey_ss58, hotkey_ss58, netuid, block=None)โ Get stake amountget_total_subnets(block=None)โ Total subnet countsubnet_exists(netuid, block=None)โ Check subnet existsis_hotkey_registered(netuid, hotkey_ss58, block=None)โ Check registrationget_uid_for_hotkey(netuid, hotkey_ss58, block=None)โ Get neuron UIDbonds(netuid, mechid=0, block=None)โ Bond distributionweights(netuid, mechid=0, block=None)โ Weight matrixtempo(netuid, block=None)โ Subnet tempodifficulty(netuid, block=None)โ POW difficultyimmunity_period(netuid, block=None)โ Immunity periodblocks_since_last_step(netuid, block=None)โ Blocks since last epochblocks_until_next_epoch(netuid, block=None)โ Blocks until next epochget_subnet_burn_cost(netuid, block=None)โ Burn registration costget_subnet_price(netuid, block=None)โ Current Alpha/TAO priceget_subnet_prices(block=None)โ All subnet pricesget_subnet_hyperparameters(netuid, block=None)โ Hyperparametersget_subnet_reveal_period_epochs(netuid, block=None)โ Reveal periodget_delegate_by_hotkey(hotkey_ss58, block=None)โ Delegate infoget_delegates(block=None)โ All delegatesget_delegated(coldkey_ss58, block=None)โ Delegation statusget_coldkey_swap_announcement(coldkey_ss58)โ Swap announcementget_mev_shield_current_key()โ MEV shield keyclose()โ Close connection
~130+ total methods on Subtensor class. Many methods accept these common keyword args:
mev_protection=DEFAULT_MEV_PROTECTION, period=DEFAULT_PERIOD, raise_error=False,
wait_for_inclusion=True, wait_for_finalization=True, wait_for_revealed_execution=True
bittensor.core.async_subtensor โ AsyncSubtensor
Identical API to Subtensor but all methods are async. Takes same constructor args:
AsyncSubtensor(network=None, config=None, log_verbose=False, fallback_endpoints=None,
retry_forever=False, archive_endpoints=None, websocket_shutdown_timer=5.0, mock=False)
All ~130+ methods match Subtensor but are await-able. Use when building async applications (FastAPI miners/validators).
bittensor.core.metagraph โ Metagraph
Metagraph(netuid, mechid=0, network=DEFAULT_NETWORK, lite=True, sync=True, subtensor=None)
AsyncMetagraph(netuid, mechid=0, network=DEFAULT_NETWORK, lite=True, sync=True, subtensor=None)
TorchMetagraph(netuid, ...) # PyTorch tensor attributes
NonTorchMetagraph(netuid, ...) # NumPy array attributes
MetagraphMixin(netuid, ...) # Abstract base
Key attributes: n, S (stake), R (rewards), I (incentive), T (trust), C (consensus), hotkeys, coldkeys, uids, axon_infos, neurons, W (weights), bonds, emission, dividends, active, last_update, block
Methods: sync(block=None, lite=None, subtensor=None), save(root_dir=None), load(root_dir=None), state_dict(), metadata()
Factory: async_metagraph(netuid, ...) โ Creates pre-synced AsyncMetagraph
bittensor.core.axon โ Axon (Server)
Axon(wallet=None, config=None, port=None, ip=None, external_ip=None,
external_port=None, max_workers=None)
Key methods:
attach(forward_fn, blacklist_fn=None, priority_fn=None, verify_fn=None)โ Register handlersserve(netuid, subtensor=None, certificate=None)โ Register on-chainstart()/stop()โ Server lifecycleinfo()โ Get AxonInfodefault_verify(synapse)โ Signature verification middlewareverify_body_integrity(request)โ Request body integrity check
Also: AxonMiddleware (Starlette middleware for request processing), FastAPIThreadedServer (uvicorn in a thread)
bittensor.core.dendrite โ Dendrite (Client)
Dendrite(wallet=None)
DendriteMixin(wallet=None) # Shared base
Key methods:
query(target_axon, synapse, timeout=12.0)โ Sync query to axon(s)aquery(target_axon, synapse, timeout=12.0)โ Async querypreprocess_synapse_for_request(target_axon_info, synapse, timeout=12.0)โ Build headers + signprocess_server_response(server_response, json_response, local_synapse)โ Merge server stateclose_session()/aclose_session()โ Cleanup
bittensor.core.synapse โ Synapse
Synapse() # Base (Pydantic BaseModel)
TerminalInfo() # Neuron metadata carrier
Synapse methods: deserialize(), get_total_size(), to_headers(), from_headers(headers), body_hash(), parse_headers_to_inputs(headers), get_required_fields()
TerminalInfo: cast_float(raw), cast_int(raw), get_size(obj)
bittensor.core.stream โ BTStreamingResponseModel
Streaming response support for large data transfers between neurons.
bittensor.core.threadpool โ PriorityThreadPoolExecutor
Priority-based thread pool used internally by Axon for request handling.
bittensor.core.tensor
Tensor serialization utilities for network communication.
bittensor.core.config โ Config
Configuration object parsed from CLI args. Used throughout the framework.
bittensor.core.settings โ DEFAULTS
Default settings: axon (ip, port, max_workers), logging (debug, trace, info, logging_dir), priority (max_workers, maxsize), subtensor (chain_endpoint, network), wallet (name, hotkey, path).
bittensor.core.types
Shared types: AxonInfo, PrometheusInfo, SubnetInfo, NeuronInfo, NeuronInfoLite, DelegateInfo, StakeInfo, ProposalVoteData, etc. Also SubtensorMixin base class.
bittensor.core.errors
Exception hierarchy: ChainConnectionError, ChainTransactionError, IdentityError, StakeError, MetadataError, PriorityException, AxonException, DendriteException, SynapseException, StreamException, ConfigException, etc.
Chain Data Models (26 modules)
All under bittensor.core.chain_data:
| Model | Description |
|---|---|
AxonInfo | Neuron axon endpoint: ip, port, ip_type, protocol, version, placeholder1/2 |
ChainIdentity | On-chain identity: name, url, description, discord, github_repo, additional |
ColdkeySwap | Coldkey swap execution data |
CrowdloanInfo | Crowdloan details: id, cap, raised, end, min_contribution, target |
DelegateInfo | Delegate: hotkey_ss58, total_stake, take, nominators, owner_ss58 |
DelegateInfoLite | Lightweight delegate info |
DynamicInfo | Subnet dynamic parameters |
InfoBase | Base dataclass for all info types |
IPInfo | IP: ip, ip_type, port, protocol |
MetagraphInfo | Metagraph metadata |
NeuronInfo | Full neuron: hotkey, coldkey, uid, netuid, stake, rank, trust, incentive, emission, axon_info, prometheus_info, etc. |
NeuronInfoLite | Lightweight neuron info |
PrometheusInfo | Prometheus endpoint: ip, port, version |
ProposalVoteData | Governance proposal vote data |
Proxy | Proxy relationship: delegate, proxy_type, delay |
RootClaim | Root claim data |
ScheduledColdkeySwapInfo | Scheduled swap details |
SimSwap | Simulated swap result |
StakeInfo | Stake: hotkey_ss58, coldkey_ss58, stake |
SubnetHyperparameters | Full hyperparameter set for a subnet |
SubnetIdentity | Subnet identity: subnet_name, subnet_url, subnet_contact, logo_url, description, discord, github_repo, additional |
SubnetInfo | Subnet: netuid, owner, tempo, emission, dynamic_info |
SubnetState | Subnet state data |
WeightCommitInfo | Weight commit-reveal info |
utils | Chain data utility functions |
Extrinsics โ Pallet Operations
Sync Extrinsics (bittensor.core.extrinsics)
Each module provides functions that compose and submit extrinsics:
stakingโ add_stake, add_stake_burn, add_stake_multiple, move_stake, swap_stake, transfer_stake, unstake, unstake_all, unstake_multipleunstakingโ remove_stake, remove_stake_limit, remove_stake_full_limit, unstake_all_alpharegistrationโ burned_register, register, register_limit, root_registerweightsโ set_weights, commit_weights, reveal_weights, batch_set_weights, batch_commit_weights, batch_reveal_weightsservingโ serve_axon, serve_axon_tls, serve_prometheusrootโ claim_root, root_register, root_dissolve_network, set_root_claim_typeproxyโ add_proxy, remove_proxy, remove_proxies, announce_proxy, proxy, proxy_announcedtransferโ transfer, transfer_stakecoldkey_swapโ announce_coldkey_swap, swap_coldkey, swap_coldkey_announced, clear_coldkey_swap_announcement, dispute_coldkey_swapcrowdloanโ create, contribute, dissolve, finalize, refund, update_cap, update_end, update_min_contribution, withdrawliquidityโ add_liquidity, remove_liquidity, modify_liquidity, toggle_user_liquidity, swap_stakemev_shieldโ mev_submit_encryptedtakeโ increase_take, decrease_takechildrenโ set_children, swap_hotkeysudoโ Admin/root operationsstart_callโ Start callmove_stakeโ move_stake, swap_stake, transfer_stakeutilsโ Helper utilities
Async Extrinsics (bittensor.core.extrinsics.asyncex)
Identical module structure but async versions. All functions are async def.
Pallet Definitions (bittensor.core.extrinsics.pallets)
Constants for pallet names used in extrinsics:
admin_utilsโ Admin utility pallet constantsbalancesโ Balance transfer constants (Transfer, TransferKeepAlive, TransferAllowDeath, etc.)baseโ Base pallet shared typescommitmentsโ Commitment palletcrowdloanโ Crowdloan palletmev_shieldโ MEV shield palletproxyโ Proxy pallet typessubtensor_moduleโ Main SubtensorModule palletsudoโ Sudo palletswapโ Swap pallet
Extras
bittensor.extras.subtensor_api โ SubtensorApi
High-level wrapper providing a unified interface over both Subtensor and AsyncSubtensor:
SubtensorApi(network=None, config=None, async_subtensor=False, legacy_methods=False,
fallback_endpoints=None, retry_forever=False, log_verbose=False,
mock=False, archive_endpoints=None, websocket_shutdown_timer=5.0)
Properties (each returns a sub-API instance):
.chainโChain: get_current_block, get_block_hash, get_timestamp, state_call, tx_rate_limit, is_fast_blocks, last_drand_round, get_existential_deposit, get_minimum_required_stake, etc. (15 methods).commitmentsโCommitments: get_commitment, get_all_commitments, set_commitment, commit_reveal_enabled, etc. (12 methods).crowdloansโCrowdloans: create_crowdloan, contribute_crowdloan, dissolve_crowdloan, finalize_crowdloan, get_crowdloans, etc. (14 methods).delegatesโDelegates: get_delegates, get_delegate_by_hotkey, get_delegate_take, set_delegate_take, get_delegated, etc. (7 methods).extrinsicsโExtrinsics: add_stake, set_weights, burned_register, serve_axon, etc. (45 methods).metagraphsโMetagraphs: metagraph, get_metagraph_info, get_all_metagraphs_info.mev_shieldโMevShield: get_mev_shield_current_key, get_mev_shield_next_key, mev_submit_encrypted.neuronsโNeurons: neurons, neurons_lite, neuron_for_uid, query_identity, get_neuron_certificate.proxiesโProxy: add_proxy, remove_proxy, get_proxies, etc. (16 methods).queriesโQueries: query_subtensor, query_map, query_constant, query_module, query_runtime_api.stakingโStaking: add_stake, unstake, move_stake, swap_stake, claim_root, get_stake, etc. (30 methods).subnetsโSubnets: all_subnets, get_subnet_info, get_subnet_hyperparameters, register, etc. (45 methods).utilsโ Utility functions.walletsโWallets: get_balance, get_balances, transfer, get_stake, is_hotkey_registered, etc. (35 methods)
Each sub-API class takes subtensor: Union[Subtensor, AsyncSubtensor] and supports both sync and async.
bittensor.extras.dev_framework โ Test Framework
calls module: ~184 namedtuple call blueprints for constructing extrinsics. Divided into:
non_sudo_calls(~100 namedtuples): ADD_STAKE, SET_WEIGHTS, REGISTER, BURNED_REGISTER, COMMIT_WEIGHTS, REVEAL_WEIGHTS, TRANSFER, etc.sudo_calls(~84 namedtuples): SUDO_SET_TEMPO, SUDO_SET_DIFFICULTY, SUDO_SET_MAX_ALLOWED_UIDS, etc.pallets(string constants): AdminUtils, Balances, Commitments, Crowdloan, MevShield, Proxy, SubtensorModule, Sudo, Swap, etc.
subnet module: TestSubnet class for test subnet lifecycle management.
utils module: ActivateSubnet, RegisterNeuron, RegisterSubnet helpers.
bittensor.extras.timelock โ Time-Lock Encryption
Drand QuickNet-based TLE:
encrypt(data, n_blocks, block_time=12.0) -> tuple # (encrypted_data, reveal_round)
decrypt(encrypted_data, no_errors=True, return_str=False)
wait_reveal_and_decrypt(encrypted_data, reveal_round=None, no_errors=True, return_str=False) -> bytes
Use block_time=0.25 for fast-blocks nodes.
Utils
bittensor.utils.balance โ Balance
Balance(balance: int | float) # int=rao, float=tao
Static methods: from_tao(amount), from_rao(amount), from_float(amount), get_unit(netuid)
Properties: tao (float), rao (int), unit (str), rao_unit (str)
Helpers: tao(amount, netuid=0) -> Balance, rao(amount, netuid=0) -> Balance
bittensor.utils.btlogging โ Logging
Custom logging subsystem with state machine:
LoggingMachine(config, name="bittensor") # StateMachine + logging.Logger
States: Default, Debug, Trace, Info, Warning, Disabled
Methods: debug(), info(), warning(), error(), success(), trace(), critical(), exception()
Toggle: set_debug(on), set_trace(on), set_info(on), on(), off()
Console: BittensorConsole with info(), success(), warning(), error(), critical(), debug()
Formatters: BtFileFormatter, BtStreamFormatter (colors, emojis, millisecond timestamps)
Config: LoggingConfig namedtuple โ debug, info, trace, record_log, logging_dir, enable_third_party_loggers
Global toggles: btlogging.debug(on), btlogging.trace(on), btlogging.info(on), btlogging.warning(on)
bittensor.utils.weight_utils โ Weight Processing (12 functions)
normalize_max_weight(x, limit=0.1)โ Normalize with max capprocess_weights(uids, weights, num_neurons, min_allowed_weights, max_weight_limit, exclude_quantile=0)โ Full weight processingprocess_weights_for_netuid(uids, weights, netuid, subtensor, metagraph=None, exclude_quantile=0)โ Subnet-aware processingconvert_weights_and_uids_for_emit(uids, weights)โ To chain formatconvert_weight_uids_and_vals_to_tensor(n, uids, weights)โ From chain formatconvert_root_weight_uids_and_vals_to_tensor(n, uids, weights, subnets)โ Root weightsgenerate_weight_hash(address, netuid, uids, values, version_key, salt)โ Commit hash
bittensor.utils.liquidity โ Liquidity Math
Uniswap V3-style: price_to_tick(price), tick_to_price(tick), calculate_fees(...), get_fees(...)
LiquidityPosition dataclass: id, netuid, liquidity, price_low, price_high, fees_tao, fees_alpha
Method: to_token_amounts(current_subnet_price) -> (alpha_amount, tao_amount)
bittensor.utils.networking
get_external_ip(), get_formatted_ws_endpoint_url(url), int_to_ip(int), ip_to_int(str), ip_version(str)
bittensor.utils.registration.torch_utils
LazyLoadedTorch โ lazy torch import proxy
legacy_torch_api_compat(func) โ Decorator for torchโnumpy compatibility
use_torch() โ Check/enable torch mode
bittensor.utils.axon_utils
allowed_nonce_window_ns(current_time_ns, synapse_timeout) โ Nonce window
calculate_diff_seconds(current_time, synapse_timeout, synapse_nonce) โ Time diff
Other Utils
bittensor.utils.version:check_version(timeout),get_and_save_latest_version(timeout)bittensor.utils.formatting:get_human_readable(num),millify(n)bittensor.utils.subnets:SubnetsAPI(wallet)โ Community ABC for subnet queryingbittensor.utils:unlock_key(wallet),is_valid_ss58_address(addr),decode_hex_identity_dict(d),format_error_message(err),strtobool(val),float_to_u64(val),u16_normalized_float(x),determine_chain_endpoint_and_network(network)
Common Patterns
MEV Protection
Most extrinsic methods accept these keyword args:
mev_protection=DEFAULT_MEV_PROTECTION # Enable MEV shielding
period=DEFAULT_PERIOD # Blocks to wait for inclusion
raise_error=False # Raise on failure instead of returning error
wait_for_inclusion=True # Wait for block inclusion
wait_for_finalization=True # Wait for block finalization
wait_for_revealed_execution=True # Wait for MEV reveal period
Safe Staking
subtensor.add_stake(wallet, netuid=1, hotkey_ss58=addr, amount=amount,
safe_staking=True, # Price protection
allow_partial_stake=True, # Accept partial fill
rate_tolerance=0.005) # 0.5% slippage
Async Pattern
async with bt.AsyncSubtensor(network="finney") as subtensor:
metagraph = await subtensor.metagraph(netuid=1)
result = await subtensor.add_stake(wallet, netuid=1, ...)
Using SubtensorApi (Recommended for new code)
api = bt.SubtensorApi(network="finney")
block = api.block
info = api.subnets.get_subnet_info(netuid=1)
stake = api.staking.add_stake(wallet, netuid=1, ...)
Network Types
finneyโ Mainnettestโ Testnetlocalโ Local dev chain
Key Constants
RAOPERTAO = 1_000_000_000.0(1 TAO = 1e9 Rao)U16_MAX = 65535,U32_MAX = 4294967295,U64_MAX = 18446744073709551615GLOBAL_MAX_SUBNET_COUNT = 4096
Examples
Complete Miner
import bittensor as bt
subtensor = bt.Subtensor(network="finney")
wallet = bt.Wallet(name="miner", hotkey="hk1")
# Register
subtensor.burned_register(wallet, netuid=1, wait_for_inclusion=True)
# Check position
mg = subtensor.metagraph(netuid=1)
uid = mg.hotkeys.index(wallet.hotkey.ss58_address)
print(f"UID: {uid}, Stake: {mg.S[uid]}, Emission: {mg.emission[uid]}")
Complete Validator
import bittensor as bt
import numpy as np
subtensor = bt.Subtensor(network="finney")
wallet = bt.Wallet(name="validator", hotkey="vk1")
mg = subtensor.metagraph(netuid=1)
weights = np.random.rand(mg.n)
weights = weights / weights.sum()
subtensor.set_weights(wallet, netuid=1, uids=np.arange(mg.n),
weights=weights,
wait_for_inclusion=True, wait_for_finalization=True)
Axon Server
import bittensor as bt
def forward(synapse): ...
def blacklist(synapse): ...
def priority(synapse): ...
wallet = bt.Wallet(name="miner", hotkey="hk1")
axon = bt.Axon(wallet=wallet, port=8091)
axon.attach(forward_fn=forward, blacklist_fn=blacklist, priority_fn=priority)
axon.serve(netuid=1)
axon.start()
Dendrite Client
import bittensor as bt
dendrite = bt.Dendrite(wallet=bt.Wallet(name="validator", hotkey="vk1"))
metagraph = bt.Subtensor(network="finney").metagraph(netuid=1)
responses = dendrite.query(metagraph.axons, bt.Synapse(), timeout=12)
Liquidity Management
subtensor.add_liquidity(wallet, netuid=1,
liquidity=bt.Balance.from_tao(100),
price_low=bt.Balance.from_tao(50),
price_high=bt.Balance.from_tao(200),
wait_for_inclusion=True)
Time-Lock Encryption
from bittensor.extras.timelock import encrypt, decrypt, wait_reveal_and_decrypt
encrypted, reveal_round = encrypt(b"secret data", n_blocks=100)
# Later, after enough blocks...
data = wait_reveal_and_decrypt(encrypted)
Troubleshooting
Connection issues: Use fallback endpoints and retry_forever=True
subtensor = bt.Subtensor(network="finney",
fallback_endpoints=["wss://entrypoint-finney.opentensor.ai:443"],
retry_forever=True)
Registration fails: Check balance, try alternative method. Use register_limit() for price protection.
Weight setting fails: Verify commit-reveal cycle. Check commit_reveal_enabled(netuid) first.
Rate limiting: Space out extrinsics. Use period= parameter to control inclusion window.
Wallet not found: Use bt.Wallet(name="...").create_if_non_existing() or bt.Wallet(name="...", hotkey="...").regenerate_coldkey(...).
References
- Bittensor Docs
- Bittensor SDK Reference
- Learn Bittensor
- Taostats API
- Bittensor GitHub
- Full autoapi:
references/autoapi/index.md(133 files, complete SDK API docs)
ๅฆไฝไฝฟ็จใBittensor SDKใ๏ผ
- ๆๅผๅฐ้พ่พAI๏ผWeb ๆ iOS App๏ผ
- ็นๅปไธๆนใ็ซๅณไฝฟ็จใๆ้ฎ๏ผๆๅจๅฏน่ฏๆกไธญ่พๅ ฅไปปๅกๆ่ฟฐ
- ๅฐ้พ่พAI ไผ่ชๅจๅน้ ๅนถ่ฐ็จใBittensor SDKใๆ่ฝๅฎๆไปปๅก
- ็ปๆๅณๆถๅ็ฐ๏ผๆฏๆ็ปง็ปญๅฏน่ฏไผๅ