Bittensor sdk

From jiayaoqijia/cryptoskill · View interactive version

Bittensor sdk is an AI agent skill from the GitHub repository jiayaoqijia/cryptoskill. 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 bit

How to use this skill

Skill file

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:

Registration:

Weights:

Serving:

Proxy & Delegation:

Coldkey Swaps:

Root Operations:

Children (Child-Hotkeys):

Queries (read-only, no wallet needed):

~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:

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:

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:

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:

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):

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:

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)

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

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

Key Constants

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

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.