Source code for bittensor.core.chain_data.metagraph_info
-from dataclasses import dataclass
+from enum import Enum
+
+from dataclasses import dataclass
from typing import Optional, Union
+from bittensor.core import settings
from bittensor.core.chain_data.axon_info import AxonInfo
from bittensor.core.chain_data.chain_identity import ChainIdentity
from bittensor.core.chain_data.info_base import InfoBase
@@ -346,9 +352,11 @@ Source code for bittensor.core.chain_data.metagraph_info
from bittensor.utils.balance import Balance, fixed_to_float
-# to balance with unit (just shortcut)
-def _tbwu(val: int, netuid: Optional[int] = 0) -> Balance:
+# to balance with unit (shortcut)
+def _tbwu(val: Optional[int], netuid: Optional[int] = 0) -> Optional[Balance]:
"""Returns a Balance object from a value and unit."""
+ if val is None:
+ return None
return Balance.from_rao(val, netuid)
@@ -359,10 +367,12 @@ Source code for bittensor.core.chain_data.metagraph_info
[docs]
-def process_nested(data: Union[tuple, dict], chr_transform):
+def process_nested(
+ data: Union[tuple, dict], chr_transform
+) -> Optional[Union[list, dict]]:
"""Processes nested data structures by applying a transformation function to their elements."""
if isinstance(data, (list, tuple)):
- if len(data) > 0 and isinstance(data[0], dict):
+ if len(data) > 0:
return [
{k: chr_transform(v) for k, v in item.items()}
if item is not None
@@ -371,7 +381,8 @@ Source code for bittensor.core.chain_data.metagraph_info
]
return {}
elif isinstance(data, dict):
- return {k: chr_transform(v) for k, v in data.items()}
+ return {k: chr_transform(v) for k, v in data.items()}
+ return None
@@ -389,8 +400,8 @@ Source code for bittensor.core.chain_data.metagraph_info
network_registered_at: int
# Keys for owner.
- owner_hotkey: str # hotkey
- owner_coldkey: str # coldkey
+ owner_hotkey: Optional[str] # hotkey
+ owner_coldkey: Optional[str] # coldkey
# Tempo terms.
block: int # block at call.
@@ -479,6 +490,9 @@ Source code for bittensor.core.chain_data.metagraph_info
tuple[str, Balance]
] # List of dividend payout in alpha via subnet.
+ # List of validators
+ validators: list[str]
+
@classmethod
def _from_dict(cls, decoded: dict) -> "MetagraphInfo":
"""Returns a MetagraphInfo object from decoded chain data."""
@@ -486,9 +500,20 @@ Source code for bittensor.core.chain_data.metagraph_info
_netuid = decoded["netuid"]
# Name and symbol
- decoded.update({"name": bytes(decoded.get("name")).decode()})
- decoded.update({"symbol": bytes(decoded.get("symbol")).decode()})
- for key in ["identities", "identity"]:
+ if name := decoded.get("name"):
+ decoded.update({"name": bytes(name).decode()})
+
+ if symbol := decoded.get("symbol"):
+ decoded.update({"symbol": bytes(symbol).decode()})
+
+ ii_list = []
+ if decoded.get("identity") is not None:
+ ii_list.append("identity")
+
+ if decoded.get("identities") is not None:
+ ii_list.append("identities")
+
+ for key in ii_list:
raw_data = decoded.get(key)
processed = process_nested(raw_data, _chr_str)
decoded.update({key: processed})
@@ -502,8 +527,16 @@ Source code for bittensor.core.chain_data.metagraph_info
identity=decoded["identity"],
network_registered_at=decoded["network_registered_at"],
# Keys for owner.
- owner_hotkey=decoded["owner_hotkey"],
- owner_coldkey=decoded["owner_coldkey"],
+ owner_hotkey=(
+ decode_account_id(decoded["owner_hotkey"][0])
+ if decoded.get("owner_hotkey") is not None
+ else None
+ ),
+ owner_coldkey=(
+ decode_account_id(decoded["owner_coldkey"][0])
+ if decoded.get("owner_coldkey") is not None
+ else None
+ ),
# Tempo terms.
block=decoded["block"],
tempo=decoded["tempo"],
@@ -520,15 +553,25 @@ Source code for bittensor.core.chain_data.metagraph_info
pending_alpha_emission=_tbwu(decoded["pending_alpha_emission"], _netuid),
pending_root_emission=_tbwu(decoded["pending_root_emission"]),
subnet_volume=_tbwu(decoded["subnet_volume"], _netuid),
- moving_price=Balance.from_tao(
- fixed_to_float(decoded.get("moving_price"), 32)
+ moving_price=(
+ Balance.from_tao(fixed_to_float(decoded.get("moving_price"), 32))
+ if decoded.get("moving_price") is not None
+ else None
),
# Hparams for epoch
rho=decoded["rho"],
kappa=decoded["kappa"],
# Validator params
- min_allowed_weights=u16tf(decoded["min_allowed_weights"]),
- max_weights_limit=u16tf(decoded["max_weights_limit"]),
+ min_allowed_weights=(
+ u16tf(decoded["min_allowed_weights"])
+ if decoded.get("min_allowed_weights") is not None
+ else None
+ ),
+ max_weights_limit=(
+ u16tf(decoded["max_weights_limit"])
+ if decoded["max_weights_limit"] is not None
+ else None
+ ),
weights_version=decoded["weights_version"],
weights_rate_limit=decoded["weights_rate_limit"],
activity_cutoff=decoded["activity_cutoff"],
@@ -537,15 +580,31 @@ Source code for bittensor.core.chain_data.metagraph_info
num_uids=decoded["num_uids"],
max_uids=decoded["max_uids"],
burn=_tbwu(decoded["burn"]),
- difficulty=u64tf(decoded["difficulty"]),
+ difficulty=(
+ u64tf(decoded["difficulty"])
+ if decoded["difficulty"] is not None
+ else None
+ ),
registration_allowed=decoded["registration_allowed"],
pow_registration_allowed=decoded["pow_registration_allowed"],
immunity_period=decoded["immunity_period"],
- min_difficulty=u64tf(decoded["min_difficulty"]),
- max_difficulty=u64tf(decoded["max_difficulty"]),
+ min_difficulty=(
+ u64tf(decoded["min_difficulty"])
+ if decoded["min_difficulty"] is not None
+ else None
+ ),
+ max_difficulty=(
+ u64tf(decoded["max_difficulty"])
+ if decoded["max_difficulty"] is not None
+ else None
+ ),
min_burn=_tbwu(decoded["min_burn"]),
max_burn=_tbwu(decoded["max_burn"]),
- adjustment_alpha=u64tf(decoded["adjustment_alpha"]),
+ adjustment_alpha=(
+ u64tf(decoded["adjustment_alpha"])
+ if decoded["adjustment_alpha"] is not None
+ else None
+ ),
adjustment_interval=decoded["adjustment_interval"],
target_regs_per_interval=decoded["target_regs_per_interval"],
max_regs_per_block=decoded["max_regs_per_block"],
@@ -555,37 +614,111 @@ Source code for bittensor.core.chain_data.metagraph_info
commit_reveal_period=decoded["commit_reveal_period"],
# Bonds
liquid_alpha_enabled=decoded["liquid_alpha_enabled"],
- alpha_high=u16tf(decoded["alpha_high"]),
- alpha_low=u16tf(decoded["alpha_low"]),
- bonds_moving_avg=u64tf(decoded["bonds_moving_avg"]),
+ alpha_high=(
+ u16tf(decoded["alpha_high"])
+ if decoded["alpha_high"] is not None
+ else None
+ ),
+ alpha_low=(
+ u16tf(decoded["alpha_low"])
+ if decoded["alpha_low"] is not None
+ else None
+ ),
+ bonds_moving_avg=(
+ u64tf(decoded["bonds_moving_avg"])
+ if decoded["bonds_moving_avg"] is not None
+ else None
+ ),
# Metagraph info.
- hotkeys=[decode_account_id(ck) for ck in decoded.get("hotkeys", [])],
- coldkeys=[decode_account_id(hk) for hk in decoded.get("coldkeys", [])],
+ hotkeys=(
+ [decode_account_id(ck) for ck in decoded.get("hotkeys", [])]
+ if decoded.get("hotkeys") is not None
+ else None
+ ),
+ coldkeys=(
+ [decode_account_id(hk) for hk in decoded.get("coldkeys", [])]
+ if decoded.get("coldkeys") is not None
+ else None
+ ),
identities=decoded["identities"],
axons=decoded.get("axons", []),
active=decoded["active"],
validator_permit=decoded["validator_permit"],
- pruning_score=[u16tf(ps) for ps in decoded.get("pruning_score", [])],
+ pruning_score=(
+ [u16tf(ps) for ps in decoded.get("pruning_score", [])]
+ if decoded.get("pruning_score") is not None
+ else None
+ ),
last_update=decoded["last_update"],
- emission=[_tbwu(em, _netuid) for em in decoded.get("emission", [])],
- dividends=[u16tf(dv) for dv in decoded.get("dividends", [])],
- incentives=[u16tf(ic) for ic in decoded.get("incentives", [])],
- consensus=[u16tf(cs) for cs in decoded.get("consensus", [])],
- trust=[u16tf(tr) for tr in decoded.get("trust", [])],
- rank=[u16tf(rk) for rk in decoded.get("rank", [])],
+ emission=(
+ [_tbwu(em, _netuid) for em in decoded.get("emission", [])]
+ if decoded.get("emission") is not None
+ else None
+ ),
+ dividends=(
+ [u16tf(dv) for dv in decoded.get("dividends", [])]
+ if decoded.get("dividends") is not None
+ else None
+ ),
+ incentives=(
+ [u16tf(ic) for ic in decoded.get("incentives", [])]
+ if decoded.get("incentives") is not None
+ else None
+ ),
+ consensus=(
+ [u16tf(cs) for cs in decoded.get("consensus", [])]
+ if decoded.get("consensus") is not None
+ else None
+ ),
+ trust=(
+ [u16tf(tr) for tr in decoded.get("trust", [])]
+ if decoded.get("trust") is not None
+ else None
+ ),
+ rank=(
+ [u16tf(rk) for rk in decoded.get("rank", [])]
+ if decoded.get("rank") is not None
+ else None
+ ),
block_at_registration=decoded["block_at_registration"],
- alpha_stake=[_tbwu(ast, _netuid) for ast in decoded["alpha_stake"]],
- tao_stake=[_tbwu(ts) for ts in decoded["tao_stake"]],
- total_stake=[_tbwu(ts, _netuid) for ts in decoded["total_stake"]],
+ alpha_stake=(
+ [_tbwu(ast, _netuid) for ast in decoded["alpha_stake"]]
+ if decoded.get("alpha_stake") is not None
+ else None
+ ),
+ tao_stake=(
+ [
+ _tbwu(ts) * settings.ROOT_TAO_STAKE_WEIGHT
+ for ts in decoded["tao_stake"]
+ ]
+ if decoded.get("tao_stake") is not None
+ else None
+ ),
+ total_stake=(
+ [_tbwu(ts, _netuid) for ts in decoded["total_stake"]]
+ if decoded.get("total_stake") is not None
+ else None
+ ),
# Dividend break down
- tao_dividends_per_hotkey=[
- (decode_account_id(alpha[0]), _tbwu(alpha[1]))
- for alpha in decoded["tao_dividends_per_hotkey"]
- ],
- alpha_dividends_per_hotkey=[
- (decode_account_id(adphk[0]), _tbwu(adphk[1], _netuid))
- for adphk in decoded["alpha_dividends_per_hotkey"]
- ],
+ tao_dividends_per_hotkey=(
+ [
+ (decode_account_id(alpha[0]), _tbwu(alpha[1]))
+ for alpha in decoded["tao_dividends_per_hotkey"]
+ ]
+ if decoded.get("tao_dividends_per_hotkey") is not None
+ else None
+ ),
+ alpha_dividends_per_hotkey=(
+ [
+ (decode_account_id(adphk[0]), _tbwu(adphk[1], _netuid))
+ for adphk in decoded["alpha_dividends_per_hotkey"]
+ ]
+ if decoded.get("alpha_dividends_per_hotkey") is not None
+ else None
+ ),
+ validators=[v for v in decoded["validators"]]
+ if decoded.get("validators") is not None
+ else None,
)
@@ -653,6 +786,92 @@ Source code for bittensor.core.chain_data.metagraph_info
weights_rate_limit: int
weights_version: int
+
+
+
+[docs]
+class SelectiveMetagraphIndex(Enum):
+ Netuid = 0
+ Name = 1
+ Symbol = 2
+ Identity = 3
+ NetworkRegisteredAt = 4
+ OwnerHotkey = 5
+ OwnerColdkey = 6
+ Block = 7
+ Tempo = 8
+ LastStep = 9
+ BlocksSinceLastStep = 10
+ SubnetEmission = 11
+ AlphaIn = 12
+ AlphaOut = 13
+ TaoIn = 14
+ AlphaOutEmission = 15
+ AlphaInEmission = 16
+ TaoInEmission = 17
+ PendingAlphaEmission = 18
+ PendingRootEmission = 19
+ SubnetVolume = 20
+ MovingPrice = 21
+ Rho = 22
+ Kappa = 23
+ MinAllowedWeights = 24
+ MaxWeightsLimit = 25
+ WeightsVersion = 26
+ WeightsRateLimit = 27
+ ActivityCutoff = 28
+ MaxValidators = 29
+ NumUids = 30
+ MaxUids = 31
+ Burn = 32
+ Difficulty = 33
+ RegistrationAllowed = 34
+ PowRegistrationAllowed = 35
+ ImmunityPeriod = 36
+ MinDifficulty = 37
+ MaxDifficulty = 38
+ MinBurn = 39
+ MaxBurn = 40
+ AdjustmentAlpha = 41
+ AdjustmentInterval = 42
+ TargetRegsPerInterval = 43
+ MaxRegsPerBlock = 44
+ ServingRateLimit = 45
+ CommitRevealWeightsEnabled = 46
+ CommitRevealPeriod = 47
+ LiquidAlphaEnabled = 48
+ AlphaHigh = 49
+ AlphaLow = 50
+ BondsMovingAvg = 51
+ Hotkeys = 52
+ Coldkeys = 53
+ Identities = 54
+ Axons = 55
+ Active = 56
+ ValidatorPermit = 57
+ PruningScore = 58
+ LastUpdate = 59
+ Emission = 60
+ Dividends = 61
+ Incentives = 62
+ Consensus = 63
+ Trust = 64
+ Rank = 65
+ BlockAtRegistration = 66
+ AlphaStake = 67
+ TaoStake = 68
+ TotalStake = 69
+ TaoDividendsPerHotkey = 70
+ AlphaDividendsPerHotkey = 71
+ Validators = 72
+
+
+[docs]
+ @staticmethod
+ def all_indices() -> list[int]:
+ return [member.value for member in SelectiveMetagraphIndex]
+
+
diff --git a/static/python-api/html/_modules/bittensor/core/chain_data/neuron_info.html b/static/python-api/html/_modules/bittensor/core/chain_data/neuron_info.html
index 70da10b637..a3a875c0ee 100644
--- a/static/python-api/html/_modules/bittensor/core/chain_data/neuron_info.html
+++ b/static/python-api/html/_modules/bittensor/core/chain_data/neuron_info.html
@@ -160,25 +160,28 @@
bittensor.core.settings
bittensor.core.stream
bittensor.core.subtensor
-bittensor.core.subtensor_api
bittensor.core.synapse
bittensor.core.tensor
bittensor.core.threadpool
-bittensor.core.timelock
bittensor.core.types
+bittensor.extras
bittensor.utils
- bittensor.utils.axon_utils
- bittensor.utils.balance
- bittensor.utils.btlogging
- bittensor.utils.easy_imports
- bittensor.utils.formatting
-- bittensor.utils.mock
+- bittensor.utils.liquidity
- bittensor.utils.networking
- bittensor.utils.registration
- bittensor.utils.subnets
-- bittensor.utils.substrate_utils
- bittensor.utils.version
- bittensor.utils.weight_utils
diff --git a/static/python-api/html/_modules/bittensor/core/chain_data/neuron_info_lite.html b/static/python-api/html/_modules/bittensor/core/chain_data/neuron_info_lite.html
index f1915aa255..1a48696d7b 100644
--- a/static/python-api/html/_modules/bittensor/core/chain_data/neuron_info_lite.html
+++ b/static/python-api/html/_modules/bittensor/core/chain_data/neuron_info_lite.html
@@ -160,25 +160,28 @@
bittensor.core.settings
bittensor.core.stream
bittensor.core.subtensor
-bittensor.core.subtensor_api
bittensor.core.synapse
bittensor.core.tensor
bittensor.core.threadpool
-bittensor.core.timelock
bittensor.core.types
+bittensor.extras
bittensor.utils
- bittensor.utils.axon_utils
- bittensor.utils.balance
- bittensor.utils.btlogging
- bittensor.utils.easy_imports
- bittensor.utils.formatting
-- bittensor.utils.mock
+- bittensor.utils.liquidity
- bittensor.utils.networking
- bittensor.utils.registration
- bittensor.utils.subnets
-- bittensor.utils.substrate_utils
- bittensor.utils.version
- bittensor.utils.weight_utils
diff --git a/static/python-api/html/_modules/bittensor/core/chain_data/prometheus_info.html b/static/python-api/html/_modules/bittensor/core/chain_data/prometheus_info.html
index efa3d9a30f..c5b18481e2 100644
--- a/static/python-api/html/_modules/bittensor/core/chain_data/prometheus_info.html
+++ b/static/python-api/html/_modules/bittensor/core/chain_data/prometheus_info.html
@@ -160,25 +160,28 @@
bittensor.core.settings
bittensor.core.stream
bittensor.core.subtensor
-bittensor.core.subtensor_api
bittensor.core.synapse
bittensor.core.tensor
bittensor.core.threadpool
-bittensor.core.timelock
bittensor.core.types
+bittensor.extras
bittensor.utils
- bittensor.utils.axon_utils
- bittensor.utils.balance
- bittensor.utils.btlogging
- bittensor.utils.easy_imports
- bittensor.utils.formatting
-- bittensor.utils.mock
+- bittensor.utils.liquidity
- bittensor.utils.networking
- bittensor.utils.registration
- bittensor.utils.subnets
-- bittensor.utils.substrate_utils
- bittensor.utils.version
- bittensor.utils.weight_utils
diff --git a/static/python-api/html/_modules/bittensor/core/chain_data/proposal_vote_data.html b/static/python-api/html/_modules/bittensor/core/chain_data/proposal_vote_data.html
index 2e5cb11742..872ddceda5 100644
--- a/static/python-api/html/_modules/bittensor/core/chain_data/proposal_vote_data.html
+++ b/static/python-api/html/_modules/bittensor/core/chain_data/proposal_vote_data.html
@@ -160,25 +160,28 @@
bittensor.core.settings
bittensor.core.stream
bittensor.core.subtensor
-bittensor.core.subtensor_api
bittensor.core.synapse
bittensor.core.tensor
bittensor.core.threadpool
-bittensor.core.timelock
bittensor.core.types
+bittensor.extras
bittensor.utils
- bittensor.utils.axon_utils
- bittensor.utils.balance
- bittensor.utils.btlogging
- bittensor.utils.easy_imports
- bittensor.utils.formatting
-- bittensor.utils.mock
+- bittensor.utils.liquidity
- bittensor.utils.networking
- bittensor.utils.registration
- bittensor.utils.subnets
-- bittensor.utils.substrate_utils
- bittensor.utils.version
- bittensor.utils.weight_utils
@@ -334,30 +337,38 @@
Source code for bittensor.core.chain_data.proposal_vote_data
-from bittensor.core.chain_data.utils import decode_account_id
+from dataclasses import dataclass
+
+from bittensor.core.chain_data.info_base import InfoBase
+from bittensor.core.chain_data.utils import decode_account_id
-# Senate / Proposal data
[docs]
-class ProposalVoteData:
+@dataclass
+class ProposalVoteData(InfoBase):
+ """
+ Senate / Proposal data
+ """
+
index: int
threshold: int
ayes: list[str]
nays: list[str]
end: int
- def __init__(self, proposal_dict: dict) -> None:
- self.index = proposal_dict["index"]
- self.threshold = proposal_dict["threshold"]
- self.ayes = self.decode_ss58_tuples(proposal_dict["ayes"])
- self.nays = self.decode_ss58_tuples(proposal_dict["nays"])
- self.end = proposal_dict["end"]
-
- @staticmethod
- def decode_ss58_tuples(line: tuple):
- """Decodes a tuple of ss58 addresses formatted as bytes tuples."""
- return [decode_account_id(line[x][0]) for x in range(len(line))]
+
+[docs]
+ @classmethod
+ def from_dict(cls, proposal_dict: dict) -> "ProposalVoteData":
+ return cls(
+ ayes=[decode_account_id(key) for key in proposal_dict["ayes"]],
+ end=proposal_dict["end"],
+ index=proposal_dict["index"],
+ nays=[decode_account_id(key) for key in proposal_dict["nays"]],
+ threshold=proposal_dict["threshold"],
+ )
+
diff --git a/static/python-api/html/_modules/bittensor/core/chain_data/scheduled_coldkey_swap_info.html b/static/python-api/html/_modules/bittensor/core/chain_data/scheduled_coldkey_swap_info.html
index 4f9326c8b0..f8dacd51bb 100644
--- a/static/python-api/html/_modules/bittensor/core/chain_data/scheduled_coldkey_swap_info.html
+++ b/static/python-api/html/_modules/bittensor/core/chain_data/scheduled_coldkey_swap_info.html
@@ -160,25 +160,28 @@
bittensor.core.settings
bittensor.core.stream
bittensor.core.subtensor
-bittensor.core.subtensor_api
bittensor.core.synapse
bittensor.core.tensor
bittensor.core.threadpool
-bittensor.core.timelock
bittensor.core.types
+bittensor.extras
bittensor.utils
- bittensor.utils.axon_utils
- bittensor.utils.balance
- bittensor.utils.btlogging
- bittensor.utils.easy_imports
- bittensor.utils.formatting
-- bittensor.utils.mock
+- bittensor.utils.liquidity
- bittensor.utils.networking
- bittensor.utils.registration
- bittensor.utils.subnets
-- bittensor.utils.substrate_utils
- bittensor.utils.version
- bittensor.utils.weight_utils
diff --git a/static/python-api/html/_modules/bittensor/core/chain_data/stake_info.html b/static/python-api/html/_modules/bittensor/core/chain_data/stake_info.html
index 8c56171bac..73aa5ad176 100644
--- a/static/python-api/html/_modules/bittensor/core/chain_data/stake_info.html
+++ b/static/python-api/html/_modules/bittensor/core/chain_data/stake_info.html
@@ -160,25 +160,28 @@
bittensor.core.settings
bittensor.core.stream
bittensor.core.subtensor
-bittensor.core.subtensor_api
bittensor.core.synapse
bittensor.core.tensor
bittensor.core.threadpool
-bittensor.core.timelock
bittensor.core.types
+bittensor.extras
bittensor.utils
- bittensor.utils.axon_utils
- bittensor.utils.balance
- bittensor.utils.btlogging
- bittensor.utils.easy_imports
- bittensor.utils.formatting
-- bittensor.utils.mock
+- bittensor.utils.liquidity
- bittensor.utils.networking
- bittensor.utils.registration
- bittensor.utils.subnets
-- bittensor.utils.substrate_utils
- bittensor.utils.version
- bittensor.utils.weight_utils
diff --git a/static/python-api/html/_modules/bittensor/core/chain_data/subnet_hyperparameters.html b/static/python-api/html/_modules/bittensor/core/chain_data/subnet_hyperparameters.html
index a118e1f5aa..58c486e43d 100644
--- a/static/python-api/html/_modules/bittensor/core/chain_data/subnet_hyperparameters.html
+++ b/static/python-api/html/_modules/bittensor/core/chain_data/subnet_hyperparameters.html
@@ -160,25 +160,28 @@
bittensor.core.settings
bittensor.core.stream
bittensor.core.subtensor
-bittensor.core.subtensor_api
bittensor.core.synapse
bittensor.core.tensor
bittensor.core.threadpool
-bittensor.core.timelock
bittensor.core.types
+bittensor.extras
bittensor.utils
- bittensor.utils.axon_utils
- bittensor.utils.balance
- bittensor.utils.btlogging
- bittensor.utils.easy_imports
- bittensor.utils.formatting
-- bittensor.utils.mock
+- bittensor.utils.liquidity
- bittensor.utils.networking
- bittensor.utils.registration
- bittensor.utils.subnets
-- bittensor.utils.substrate_utils
- bittensor.utils.version
- bittensor.utils.weight_utils
@@ -335,7 +338,7 @@
Source code for bittensor.core.chain_data.subnet_hyperparameters
from dataclasses import dataclass
-
+from bittensor.utils.balance import fixed_to_float
from bittensor.core.chain_data.info_base import InfoBase
@@ -374,6 +377,12 @@ Source code for bittensor.core.chain_data.subnet_hyperparameters
alpha_high (int): High value of alpha.
alpha_low (int): Low value of alpha.
liquid_alpha_enabled (bool): Flag indicating if liquid alpha is enabled.
+ alpha_sigmoid_steepness (float):
+ yuma_version (int): Version of yuma.
+ subnet_is_active (bool): Indicates if subnet is active after START CALL.
+ transfers_enabled (bool): Flag indicating if transfers are enabled.
+ bonds_reset_enabled (bool): Flag indicating if bonds are reset enabled.
+ user_liquidity_enabled (bool): Flag indicating if user liquidity is enabled.
"""
rho: int
@@ -403,6 +412,12 @@ Source code for bittensor.core.chain_data.subnet_hyperparameters
alpha_high: int
alpha_low: int
liquid_alpha_enabled: bool
+ alpha_sigmoid_steepness: float
+ yuma_version: int
+ subnet_is_active: bool
+ transfers_enabled: bool
+ bonds_reset_enabled: bool
+ user_liquidity_enabled: bool
@classmethod
def _from_dict(cls, decoded: dict) -> "SubnetHyperparameters":
@@ -413,7 +428,11 @@ Source code for bittensor.core.chain_data.subnet_hyperparameters
adjustment_interval=decoded["adjustment_interval"],
alpha_high=decoded["alpha_high"],
alpha_low=decoded["alpha_low"],
+ alpha_sigmoid_steepness=fixed_to_float(
+ decoded["alpha_sigmoid_steepness"], frac_bits=32
+ ),
bonds_moving_avg=decoded["bonds_moving_avg"],
+ bonds_reset_enabled=decoded["bonds_reset_enabled"],
commit_reveal_weights_enabled=decoded["commit_reveal_weights_enabled"],
commit_reveal_period=decoded["commit_reveal_period"],
difficulty=decoded["difficulty"],
@@ -431,10 +450,14 @@ Source code for bittensor.core.chain_data.subnet_hyperparameters
registration_allowed=decoded["registration_allowed"],
rho=decoded["rho"],
serving_rate_limit=decoded["serving_rate_limit"],
+ subnet_is_active=decoded["subnet_is_active"],
target_regs_per_interval=decoded["target_regs_per_interval"],
tempo=decoded["tempo"],
+ transfers_enabled=decoded["transfers_enabled"],
+ user_liquidity_enabled=decoded["user_liquidity_enabled"],
weights_rate_limit=decoded["weights_rate_limit"],
weights_version=decoded["weights_version"],
+ yuma_version=decoded["yuma_version"],
)
diff --git a/static/python-api/html/_modules/bittensor/core/chain_data/subnet_identity.html b/static/python-api/html/_modules/bittensor/core/chain_data/subnet_identity.html
index 345b6370c3..f16b251e71 100644
--- a/static/python-api/html/_modules/bittensor/core/chain_data/subnet_identity.html
+++ b/static/python-api/html/_modules/bittensor/core/chain_data/subnet_identity.html
@@ -160,25 +160,28 @@
bittensor.core.settings
bittensor.core.stream
bittensor.core.subtensor
-bittensor.core.subtensor_api
bittensor.core.synapse
bittensor.core.tensor
bittensor.core.threadpool
-bittensor.core.timelock
bittensor.core.types
+bittensor.extras
bittensor.utils
- bittensor.utils.axon_utils
- bittensor.utils.balance
- bittensor.utils.btlogging
- bittensor.utils.easy_imports
- bittensor.utils.formatting
-- bittensor.utils.mock
+- bittensor.utils.liquidity
- bittensor.utils.networking
- bittensor.utils.registration
- bittensor.utils.subnets
-- bittensor.utils.substrate_utils
- bittensor.utils.version
- bittensor.utils.weight_utils
@@ -347,6 +350,7 @@ Source code for bittensor.core.chain_data.subnet_identity
github_repo: str
subnet_contact: str
subnet_url: str
+ logo_url: str
discord: str
description: str
additional: str
@@ -359,6 +363,7 @@ Source code for bittensor.core.chain_data.subnet_identity
github_repo=decoded["github_repo"],
subnet_contact=decoded["subnet_contact"],
subnet_url=decoded["subnet_url"],
+ logo_url=decoded["logo_url"],
discord=decoded["discord"],
description=decoded["description"],
additional=decoded["additional"],
diff --git a/static/python-api/html/_modules/bittensor/core/chain_data/subnet_info.html b/static/python-api/html/_modules/bittensor/core/chain_data/subnet_info.html
index bec2415972..63ec5790c5 100644
--- a/static/python-api/html/_modules/bittensor/core/chain_data/subnet_info.html
+++ b/static/python-api/html/_modules/bittensor/core/chain_data/subnet_info.html
@@ -160,25 +160,28 @@
bittensor.core.settings
bittensor.core.stream
bittensor.core.subtensor
-bittensor.core.subtensor_api
bittensor.core.synapse
bittensor.core.tensor
bittensor.core.threadpool
-bittensor.core.timelock
bittensor.core.types
+bittensor.extras
bittensor.utils
- bittensor.utils.axon_utils
- bittensor.utils.balance
- bittensor.utils.btlogging
- bittensor.utils.easy_imports
- bittensor.utils.formatting
-- bittensor.utils.mock
+- bittensor.utils.liquidity
- bittensor.utils.networking
- bittensor.utils.registration
- bittensor.utils.subnets
-- bittensor.utils.substrate_utils
- bittensor.utils.version
- bittensor.utils.weight_utils
diff --git a/static/python-api/html/_modules/bittensor/core/chain_data/subnet_state.html b/static/python-api/html/_modules/bittensor/core/chain_data/subnet_state.html
index ed4b533243..ff6335edfb 100644
--- a/static/python-api/html/_modules/bittensor/core/chain_data/subnet_state.html
+++ b/static/python-api/html/_modules/bittensor/core/chain_data/subnet_state.html
@@ -160,25 +160,28 @@
bittensor.core.settings
bittensor.core.stream
bittensor.core.subtensor
-bittensor.core.subtensor_api
bittensor.core.synapse
bittensor.core.tensor
bittensor.core.threadpool
-bittensor.core.timelock
bittensor.core.types
+bittensor.extras
bittensor.utils
- bittensor.utils.axon_utils
- bittensor.utils.balance
- bittensor.utils.btlogging
- bittensor.utils.easy_imports
- bittensor.utils.formatting
-- bittensor.utils.mock
+- bittensor.utils.liquidity
- bittensor.utils.networking
- bittensor.utils.registration
- bittensor.utils.subnets
-- bittensor.utils.substrate_utils
- bittensor.utils.version
- bittensor.utils.weight_utils
diff --git a/static/python-api/html/_modules/bittensor/core/chain_data/utils.html b/static/python-api/html/_modules/bittensor/core/chain_data/utils.html
index 5642ae8a0b..4f6eb8e9b8 100644
--- a/static/python-api/html/_modules/bittensor/core/chain_data/utils.html
+++ b/static/python-api/html/_modules/bittensor/core/chain_data/utils.html
@@ -160,25 +160,28 @@
bittensor.core.settings
bittensor.core.stream
bittensor.core.subtensor
-bittensor.core.subtensor_api
bittensor.core.synapse
bittensor.core.tensor
bittensor.core.threadpool
-bittensor.core.timelock
bittensor.core.types
+bittensor.extras
bittensor.utils
- bittensor.utils.axon_utils
- bittensor.utils.balance
- bittensor.utils.btlogging
- bittensor.utils.easy_imports
- bittensor.utils.formatting
-- bittensor.utils.mock
+- bittensor.utils.liquidity
- bittensor.utils.networking
- bittensor.utils.registration
- bittensor.utils.subnets
-- bittensor.utils.substrate_utils
- bittensor.utils.version
- bittensor.utils.weight_utils
@@ -337,15 +340,19 @@ Source code for bittensor.core.chain_data.utils
<
"""Chain data helper functions and data."""
from enum import Enum
-from typing import Optional, Union
+from typing import Optional, Union, TYPE_CHECKING
from scalecodec.base import RuntimeConfiguration, ScaleBytes
+from async_substrate_interface.types import ScaleObj
from scalecodec.type_registry import load_type_registry_preset
from scalecodec.utils.ss58 import ss58_encode
from bittensor.core.settings import SS58_FORMAT
from bittensor.utils.balance import Balance
+if TYPE_CHECKING:
+ from async_substrate_interface.sync_substrate import QueryMapResult
+
[docs]
@@ -486,9 +493,78 @@ Source code for bittensor.core.chain_data.utils
<
[docs]
def decode_metadata(metadata: dict) -> str:
commitment = metadata["info"]["fields"][0][0]
- bytes_tuple = commitment[next(iter(commitment.keys()))][0]
+ bytes_tuple_ = commitment[next(iter(commitment.keys()))]
+ bytes_tuple = bytes_tuple_[0] if len(bytes_tuple_) > 0 else bytes_tuple_
return bytes(bytes_tuple).decode()
+
+
+
+[docs]
+def decode_block(data: bytes) -> int:
+ """
+ Decode the block data from the given input if it is not None.
+
+ Arguments:
+ data (bytes): The block data to decode.
+
+ Returns:
+ int: The decoded block.
+ """
+ return int(data.value) if isinstance(data, ScaleObj) else data
+
+
+
+
+[docs]
+def decode_revealed_commitment(encoded_data) -> tuple[int, str]:
+ """
+ Decode the revealed commitment data from the given input if it is not None.
+
+ Arguments:
+ encoded_data (tuple[bytes, int]): A tuple containing the revealed message and the block number.
+
+ Returns:
+ tuple[int, str]: A tuple containing the revealed block number and decoded commitment message.
+ """
+
+ def scale_decode_offset(data: bytes) -> int:
+ """Decodes the scale offset from a given byte data sequence."""
+ first_byte = data[0]
+ mode = first_byte & 0b11
+ if mode == 0:
+ return 1
+ elif mode == 1:
+ return 2
+ else:
+ return 4
+
+ com_bytes, revealed_block = encoded_data
+ offset = scale_decode_offset(com_bytes)
+
+ revealed_commitment = bytes(com_bytes[offset:]).decode("utf-8", errors="ignore")
+ return revealed_block, revealed_commitment
+
+
+
+
+[docs]
+def decode_revealed_commitment_with_hotkey(
+ encoded_data: "QueryMapResult",
+) -> tuple[str, tuple[tuple[int, str], ...]]:
+ """
+ Decode revealed commitment using a hotkey.
+
+ Returns:
+ tuple[str, tuple[tuple[int, str], ...]]: A tuple containing the hotkey (ss58 address) and a tuple of block
+ numbers and their corresponding revealed commitments.
+ """
+ key, data = encoded_data
+
+ ss58_address = decode_account_id(next(iter(key)))
+ block_data = tuple(decode_revealed_commitment(p) for p in data.value)
+ return ss58_address, block_data
+
diff --git a/static/python-api/html/_modules/bittensor/core/chain_data/weight_commit_info.html b/static/python-api/html/_modules/bittensor/core/chain_data/weight_commit_info.html
index 985cf9f507..d2e6295800 100644
--- a/static/python-api/html/_modules/bittensor/core/chain_data/weight_commit_info.html
+++ b/static/python-api/html/_modules/bittensor/core/chain_data/weight_commit_info.html
@@ -160,25 +160,28 @@
bittensor.core.settings
bittensor.core.stream
bittensor.core.subtensor
-bittensor.core.subtensor_api
bittensor.core.synapse
bittensor.core.tensor
bittensor.core.threadpool
-bittensor.core.timelock
bittensor.core.types
+bittensor.extras
bittensor.utils
- bittensor.utils.axon_utils
- bittensor.utils.balance
- bittensor.utils.btlogging
- bittensor.utils.easy_imports
- bittensor.utils.formatting
-- bittensor.utils.mock
+- bittensor.utils.liquidity
- bittensor.utils.networking
- bittensor.utils.registration
- bittensor.utils.subnets
-- bittensor.utils.substrate_utils
- bittensor.utils.version
- bittensor.utils.weight_utils
diff --git a/static/python-api/html/_modules/bittensor/core/config.html b/static/python-api/html/_modules/bittensor/core/config.html
index 13690507f0..af4f3664e1 100644
--- a/static/python-api/html/_modules/bittensor/core/config.html
+++ b/static/python-api/html/_modules/bittensor/core/config.html
@@ -160,25 +160,28 @@
bittensor.core.settings
bittensor.core.stream
bittensor.core.subtensor
-bittensor.core.subtensor_api
bittensor.core.synapse
bittensor.core.tensor
bittensor.core.threadpool
-bittensor.core.timelock
bittensor.core.types
+bittensor.extras
bittensor.utils
- bittensor.utils.axon_utils
- bittensor.utils.balance
- bittensor.utils.btlogging
- bittensor.utils.easy_imports
- bittensor.utils.formatting
-- bittensor.utils.mock
+- bittensor.utils.liquidity
- bittensor.utils.networking
- bittensor.utils.registration
- bittensor.utils.subnets
-- bittensor.utils.substrate_utils
- bittensor.utils.version
- bittensor.utils.weight_utils
@@ -590,19 +593,13 @@ Source code for bittensor.core.config
T = TypeVar("T", bound="DefaultConfig")
-
-[docs]
class DefaultConfig(Config):
"""A Config with a set of default values."""
-
-[docs]
@classmethod
def default(cls: Type[T]) -> T:
"""Get default config."""
- raise NotImplementedError("Function default is not implemented.")
-
-
+ raise NotImplementedError("Function default is not implemented.")
diff --git a/static/python-api/html/_modules/bittensor/core/dendrite.html b/static/python-api/html/_modules/bittensor/core/dendrite.html
index 08d045f3f4..e9f546397e 100644
--- a/static/python-api/html/_modules/bittensor/core/dendrite.html
+++ b/static/python-api/html/_modules/bittensor/core/dendrite.html
@@ -160,25 +160,28 @@
bittensor.core.settings
bittensor.core.stream
bittensor.core.subtensor
-bittensor.core.subtensor_api
bittensor.core.synapse
bittensor.core.tensor
bittensor.core.threadpool
-bittensor.core.timelock
bittensor.core.types
+bittensor.extras
bittensor.utils
- bittensor.utils.axon_utils
- bittensor.utils.balance
- bittensor.utils.btlogging
- bittensor.utils.easy_imports
- bittensor.utils.formatting
-- bittensor.utils.mock
+- bittensor.utils.liquidity
- bittensor.utils.networking
- bittensor.utils.registration
- bittensor.utils.subnets
-- bittensor.utils.substrate_utils
- bittensor.utils.version
- bittensor.utils.weight_utils
@@ -607,7 +610,7 @@ Source code for bittensor.core.dendrite
"""
error_id = str(uuid.uuid4())
error_type = exception.__class__.__name__
- if isinstance(exception, (aiohttp.ClientConnectorError, asyncio.TimeoutError)):
+ if isinstance(exception, (aiohttp.ClientOSError, asyncio.TimeoutError)):
logging.debug(f"{error_type}#{error_id}: {exception}")
else:
logging.error(f"{error_type}#{error_id}: {exception}")
@@ -1257,7 +1260,14 @@ Source code for bittensor.core.dendrite
# ... some operations ...
del dendrite # This will implicitly invoke the __del__ method and close the session.
"""
- self.close_session()
+ try:
+ self.close_session()
+ except RuntimeError:
+ if self._session:
+ logging.debug(
+ "A Dendrite session was unable to be closed during garbage-collection of the Dendrite object. This "
+ "usually indicates that you were not using the async context manager."
+ )
diff --git a/static/python-api/html/_modules/bittensor/core/errors.html b/static/python-api/html/_modules/bittensor/core/errors.html
index c8e4a9ab43..8e4092ca5e 100644
--- a/static/python-api/html/_modules/bittensor/core/errors.html
+++ b/static/python-api/html/_modules/bittensor/core/errors.html
@@ -160,25 +160,28 @@
bittensor.core.settings
bittensor.core.stream
bittensor.core.subtensor
-bittensor.core.subtensor_api
bittensor.core.synapse
bittensor.core.tensor
bittensor.core.threadpool
-bittensor.core.timelock
bittensor.core.types
+bittensor.extras
bittensor.utils
- bittensor.utils.axon_utils
- bittensor.utils.balance
- bittensor.utils.btlogging
- bittensor.utils.easy_imports
- bittensor.utils.formatting
-- bittensor.utils.mock
+- bittensor.utils.liquidity
- bittensor.utils.networking
- bittensor.utils.registration
- bittensor.utils.subnets
-- bittensor.utils.substrate_utils
- bittensor.utils.version
- bittensor.utils.weight_utils
@@ -353,6 +356,21 @@ Source code for bittensor.core.errors
ExtrinsicNotFound = ExtrinsicNotFound
+class _ChainErrorMeta(type):
+ _exceptions: dict[str, Exception] = {}
+
+ def __new__(mcs, name, bases, attrs):
+ cls = super().__new__(mcs, name, bases, attrs)
+
+ mcs._exceptions.setdefault(cls.__name__, cls)
+
+ return cls
+
+ @classmethod
+ def get_exception_class(mcs, exception_name):
+ return mcs._exceptions[exception_name]
+
+
[docs]
class MaxSuccessException(Exception):
@@ -369,8 +387,22 @@ Source code for bittensor.core.errors
[docs]
-class ChainError(SubstrateRequestException):
- """Base error for any chain related errors."""
+class ChainError(SubstrateRequestException, metaclass=_ChainErrorMeta):
+ """Base error for any chain related errors."""
+
+
+[docs]
+ @classmethod
+ def from_error(cls, error):
+ try:
+ error_cls = _ChainErrorMeta.get_exception_class(
+ error["name"],
+ )
+ except KeyError:
+ return cls(error)
+ else:
+ return error_cls(" ".join(error["docs"]))
+
@@ -388,80 +420,216 @@ Source code for bittensor.core.errors
-
+
-
-[docs]
-class StakeError(ChainTransactionError):
- """Error raised when a stake transaction fails."""
+
-
-[docs]
-class UnstakeError(ChainTransactionError):
- """Error raised when an unstake transaction fails."""
+
+[docs]
+class DuplicateChild(ChainTransactionError):
+ """
+ Duplicate child when setting children.
+ """
+
+
+
+
+[docs]
+class HotKeyAccountNotExists(ChainTransactionError):
+ """
+ The hotkey does not exist.
+ """
[docs]
class IdentityError(ChainTransactionError):
- """Error raised when an identity transaction fails."""
+ """
+ Error raised when an identity transaction fails.
+ """
+
+
+
+
+[docs]
+class InvalidChild(ChainTransactionError):
+ """
+ Attempting to set an invalid child for a hotkey on a network.
+ """
+
+
+
+
+[docs]
+class MetadataError(ChainTransactionError):
+ """
+ Error raised when metadata commitment transaction fails.
+ """
[docs]
class NominationError(ChainTransactionError):
- """Error raised when a nomination transaction fails."""
+ """
+ Error raised when a nomination transaction fails.
+ """
-
-[docs]
-class TakeError(ChainTransactionError):
- """Error raised when an increase / decrease take transaction fails."""
+
+[docs]
+class NonAssociatedColdKey(ChainTransactionError):
+ """
+ Request to stake, unstake or subscribe is made by a coldkey that is not associated with the hotkey account.
+ """
-
-[docs]
-class TransferError(ChainTransactionError):
- """Error raised when a transfer transaction fails."""
+
+[docs]
+class NotEnoughStakeToSetChildkeys(ChainTransactionError):
+ """
+ The parent hotkey doesn't have enough own stake to set childkeys.
+ """
+
+
+
+
+[docs]
+class NotRegisteredError(ChainTransactionError):
+ """
+ Error raised when a neuron is not registered, and the transaction requires it to be.
+ """
+
+
+
+
+[docs]
+class ProportionOverflow(ChainTransactionError):
+ """
+ Proportion overflow when setting children.
+ """
[docs]
class RegistrationError(ChainTransactionError):
- """Error raised when a neuron registration transaction fails."""
+ """
+ Error raised when a neuron registration transaction fails.
+ """
-
-[docs]
-class NotRegisteredError(ChainTransactionError):
- """Error raised when a neuron is not registered, and the transaction requires it to be."""
+
+[docs]
+class RegistrationNotPermittedOnRootSubnet(ChainTransactionError):
+ """
+ Operation is not permitted on the root subnet.
+ """
+
+
+
+
+[docs]
+class StakeError(ChainTransactionError):
+ """
+ Error raised when a stake transaction fails.
+ """
[docs]
class NotDelegateError(StakeError):
- """Error raised when a hotkey you are trying to stake to is not a delegate."""
+ """
+ Error raised when a hotkey you are trying to stake to is not a delegate.
+ """
-
-[docs]
-class MetadataError(ChainTransactionError):
- """Error raised when metadata commitment transaction fails."""
+class SubNetworkDoesNotExist(ChainTransactionError):
+ """
+ The subnet does not exist.
+ """
+
+
+
+[docs]
+class TakeError(ChainTransactionError):
+ """
+ Error raised when an increase / decrease take transaction fails.
+ """
+
+
+
+
+[docs]
+class TransferError(ChainTransactionError):
+ """
+ Error raised when a transfer transaction fails.
+ """
+
+
+
+
+
+
+
+
+[docs]
+class TxRateLimitExceeded(ChainTransactionError):
+ """
+ Default transaction rate limit exceeded.
+ """
+
+
+
+
+[docs]
+class DelegateTxRateLimitExceeded(TxRateLimitExceeded):
+ """
+ A transactor exceeded the rate limit for delegate transaction.
+ """
+
+
+
+
+[docs]
+class UnstakeError(ChainTransactionError):
+ """
+ Error raised when an unstake transaction fails.
+ """
+
+
+
+
diff --git a/static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/commit_reveal.html b/static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/children.html
similarity index 55%
rename from static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/commit_reveal.html
rename to static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/children.html
index c77f652ac8..8748b08682 100644
--- a/static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/commit_reveal.html
+++ b/static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/children.html
@@ -7,7 +7,7 @@
- bittensor.core.extrinsics.asyncex.commit_reveal — Bittensor SDK Docs documentation
+ bittensor.core.extrinsics.asyncex.children — Bittensor SDK Docs documentation
@@ -44,7 +44,7 @@
-
+
@@ -160,25 +160,28 @@
bittensor.core.settings
bittensor.core.stream
bittensor.core.subtensor
-bittensor.core.subtensor_api
bittensor.core.synapse
bittensor.core.tensor
bittensor.core.threadpool
-bittensor.core.timelock
bittensor.core.types
+bittensor.extras
bittensor.utils
- bittensor.utils.axon_utils
- bittensor.utils.balance
- bittensor.utils.btlogging
- bittensor.utils.easy_imports
- bittensor.utils.formatting
-- bittensor.utils.mock
+- bittensor.utils.liquidity
- bittensor.utils.networking
- bittensor.utils.registration
- bittensor.utils.subnets
-- bittensor.utils.substrate_utils
- bittensor.utils.version
- bittensor.utils.weight_utils
@@ -263,7 +266,7 @@
-
- Source code for bittensor.core.extrinsics.asyncex.commit_reveal
-"""This module provides async functionality for commit reveal in the Bittensor network."""
-
-from typing import Optional, Union, TYPE_CHECKING
-
-import numpy as np
-from bittensor_commit_reveal import get_encrypted_commit
-from numpy.typing import NDArray
-
-from bittensor.core.settings import version_as_int
-from bittensor.utils.btlogging import logging
-from bittensor.utils.weight_utils import convert_weights_and_uids_for_emit
+ Source code for bittensor.core.extrinsics.asyncex.children
+from typing import TYPE_CHECKING, Optional
+from bittensor.utils import float_to_u64, unlock_key
if TYPE_CHECKING:
from bittensor_wallet import Wallet
from bittensor.core.async_subtensor import AsyncSubtensor
- from bittensor.utils.registration import torch
-async def _do_commit_reveal_v3(
+
+[docs]
+async def set_children_extrinsic(
subtensor: "AsyncSubtensor",
wallet: "Wallet",
+ hotkey: str,
netuid: int,
- commit: bytes,
- reveal_round: int,
- wait_for_inclusion: bool = False,
+ children: list[tuple[float, str]],
+ wait_for_inclusion: bool = True,
wait_for_finalization: bool = False,
-) -> tuple[bool, Optional[str]]:
+ raise_error: bool = False,
+ period: Optional[int] = None,
+):
"""
- Executes the commit-reveal phase 3 for a given netuid and commit, and optionally waits for extrinsic inclusion or
- finalization.
+ Allows a coldkey to set children-keys.
Arguments:
- subtensor: An instance of the AsyncSubtensor class.
- wallet: Wallet An instance of the Wallet class containing the user's keypair.
- netuid: int The network unique identifier.
- commit bytes The commit data in bytes format.
- reveal_round: int The round number for the reveal phase.
- wait_for_inclusion: bool, optional Flag indicating whether to wait for the extrinsic to be included in a block.
- wait_for_finalization: bool, optional Flag indicating whether to wait for the extrinsic to be finalized.
+ subtensor: bittensor subtensor.
+ wallet: bittensor wallet instance.
+ hotkey: The ``SS58`` address of the neuron's hotkey.
+ netuid: The netuid value.
+ children: A list of children with their proportions.
+ wait_for_inclusion: Waits for the transaction to be included in a block.
+ wait_for_finalization: Waits for the transaction to be finalized on the blockchain.
+ raise_error: Raises a relevant exception rather than returning `False` if unsuccessful.
+ 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. You can
+ think of it as an expiration date for the transaction.
Returns:
- A tuple where the first element is a boolean indicating success or failure, and the second element is an
- optional string containing error message if any.
+ tuple[bool, str]: A tuple where the first element is a boolean indicating success or failure of the operation,
+ and the second element is a message providing additional information.
+
+ 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.
+ SubNetworkDoesNotExist: 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.
"""
- logging.info(
- f"Committing weights hash [blue]{commit.hex()}[/blue] for subnet #[blue]{netuid}[/blue] with "
- f"reveal round [blue]{reveal_round}[/blue]..."
- )
-
- call = await subtensor.substrate.compose_call(
- call_module="SubtensorModule",
- call_function="commit_crv3_weights",
- call_params={
- "netuid": netuid,
- "commit": commit,
- "reveal_round": reveal_round,
- },
- )
- return await subtensor.sign_and_send_extrinsic(
- call, wallet, wait_for_inclusion, wait_for_finalization, sign_with="hotkey"
- )
-
-
-
-[docs]
-async def commit_reveal_v3_extrinsic(
+ unlock = unlock_key(wallet, raise_error=raise_error)
+
+ if not unlock.success:
+ return False, unlock.message
+
+ async with subtensor.substrate as substrate:
+ call = await substrate.compose_call(
+ call_module="SubtensorModule",
+ call_function="set_children",
+ call_params={
+ "children": [
+ (
+ float_to_u64(proportion),
+ child_hotkey,
+ )
+ for proportion, child_hotkey in children
+ ],
+ "hotkey": hotkey,
+ "netuid": netuid,
+ },
+ )
+
+ success, message = await subtensor.sign_and_send_extrinsic(
+ call=call,
+ wallet=wallet,
+ wait_for_inclusion=wait_for_inclusion,
+ wait_for_finalization=wait_for_finalization,
+ raise_error=raise_error,
+ period=period,
+ )
+
+ if not wait_for_finalization and not wait_for_inclusion:
+ return True, message
+
+ if success:
+ return True, "Success with `set_children_extrinsic` response."
+
+ return True, message
+
+
+
+
+[docs]
+async def root_set_pending_childkey_cooldown_extrinsic(
subtensor: "AsyncSubtensor",
wallet: "Wallet",
- netuid: int,
- uids: Union[NDArray[np.int64], "torch.LongTensor", list],
- weights: Union[NDArray[np.float32], "torch.FloatTensor", list],
- version_key: int = version_as_int,
- wait_for_inclusion: bool = False,
+ cooldown: int,
+ wait_for_inclusion: bool = True,
wait_for_finalization: bool = False,
+ period: Optional[int] = None,
) -> tuple[bool, str]:
"""
- Commits and reveals weights for given subtensor and wallet with provided uids and weights.
+ Allows a coldkey to set children-keys.
+ """
+ unlock = unlock_key(wallet)
- Arguments:
- subtensor: The AsyncSubtensor instance.
- wallet: The wallet to use for committing and revealing.
- netuid: The id of the network.
- uids: The uids to commit.
- weights: The weights associated with the uids.
- version_key: The version key to use for committing and revealing. Default is version_as_int.
- wait_for_inclusion: Whether to wait for the inclusion of the transaction. Default is False.
- wait_for_finalization: Whether to wait for the finalization of the transaction. Default is False.
+ if not unlock.success:
+ return False, unlock.message
- Returns:
- tuple[bool, str]: A tuple where the first element is a boolean indicating success or failure, and the second
- element is a message associated with the result
- """
- try:
- # Convert uids and weights
- if isinstance(uids, list):
- uids = np.array(uids, dtype=np.int64)
- if isinstance(weights, list):
- weights = np.array(weights, dtype=np.float32)
-
- # Reformat and normalize.
- uids, weights = convert_weights_and_uids_for_emit(uids, weights)
-
- current_block = await subtensor.substrate.get_block(None)
- subnet_hyperparameters = await subtensor.get_subnet_hyperparameters(
- netuid, block_hash=current_block["header"]["hash"]
+ async with subtensor.substrate as substrate:
+ call = await substrate.compose_call(
+ call_module="SubtensorModule",
+ call_function="set_pending_childkey_cooldown",
+ call_params={"cooldown": cooldown},
)
- tempo = subnet_hyperparameters.tempo
- subnet_reveal_period_epochs = subnet_hyperparameters.commit_reveal_period
-
- # Encrypt `commit_hash` with t-lock and `get reveal_round`
- commit_for_reveal, reveal_round = get_encrypted_commit(
- uids=uids,
- weights=weights,
- version_key=version_key,
- tempo=tempo,
- current_block=current_block["header"]["number"],
- netuid=netuid,
- subnet_reveal_period_epochs=subnet_reveal_period_epochs,
+
+ sudo_call = await substrate.compose_call(
+ call_module="Sudo",
+ call_function="sudo",
+ call_params={"call": call},
)
- success, message = await _do_commit_reveal_v3(
- subtensor=subtensor,
+ success, message = await subtensor.sign_and_send_extrinsic(
+ call=sudo_call,
wallet=wallet,
- netuid=netuid,
- commit=commit_for_reveal,
- reveal_round=reveal_round,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
+ period=period,
)
- if success is not True:
- logging.error(message)
- return False, message
+ if not wait_for_finalization and not wait_for_inclusion:
+ return True, message
- logging.success(
- f"[green]Finalized![/green] Weights committed with reveal round [blue]{reveal_round}[/blue]."
- )
- return True, f"reveal_round:{reveal_round}"
+ if success:
+ return (
+ True,
+ "Success with `root_set_pending_childkey_cooldown_extrinsic` response.",
+ )
- except Exception as e:
- logging.error(f":cross_mark: [red]Failed. Error:[/red] {e}")
- return False, str(e)
+ return True, message
diff --git a/static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/liquidity.html b/static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/liquidity.html
new file mode 100644
index 0000000000..fc6b9a551e
--- /dev/null
+++ b/static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/liquidity.html
@@ -0,0 +1,657 @@
+
+
+
+
+
+
+
+
+
+ bittensor.core.extrinsics.asyncex.liquidity — Bittensor SDK Docs documentation
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Source code for bittensor.core.extrinsics.asyncex.liquidity
+from typing import Optional, TYPE_CHECKING
+
+from bittensor.utils import unlock_key
+from bittensor.utils.balance import Balance
+from bittensor.utils.btlogging import logging
+from bittensor.utils.liquidity import price_to_tick
+
+if TYPE_CHECKING:
+ from bittensor_wallet import Wallet
+ from bittensor.core.async_subtensor import AsyncSubtensor
+
+
+
+[docs]
+async def add_liquidity_extrinsic(
+ subtensor: "AsyncSubtensor",
+ wallet: "Wallet",
+ netuid: int,
+ liquidity: Balance,
+ price_low: Balance,
+ price_high: Balance,
+ hotkey: Optional[str] = None,
+ wait_for_inclusion: bool = True,
+ wait_for_finalization: bool = False,
+ period: Optional[int] = None,
+) -> tuple[bool, str]:
+ """
+ Adds liquidity to the specified price range.
+
+ Arguments:
+ subtensor: The Subtensor client instance used for blockchain interaction.
+ wallet: The wallet used to sign the extrinsic (must be unlocked).
+ netuid: The UID of the target subnet for which the call is being initiated.
+ liquidity: The amount of liquidity to be added.
+ price_low: The lower bound of the price tick range.
+ price_high: The upper bound of the price tick range.
+ hotkey: The hotkey with staked TAO in Alpha. If not passed then the wallet hotkey is used. Defaults to `None`.
+ wait_for_inclusion: Whether to wait for the extrinsic to be included in a block. Defaults to True.
+ wait_for_finalization: Whether to wait for finalization of the extrinsic. Defaults to False.
+ 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.
+ You can think of it as an expiration date for the transaction.
+
+ Returns:
+ Tuple[bool, str]:
+ - True and a success message if the extrinsic is successfully submitted or processed.
+ - False and an error message if the submission fails or the wallet cannot be unlocked.
+
+ Note: Adding is allowed even when user liquidity is enabled in specified subnet. Call
+ `toggle_user_liquidity_extrinsic` to enable/disable user liquidity.
+ """
+ if not (unlock := unlock_key(wallet)).success:
+ logging.error(unlock.message)
+ return False, unlock.message
+
+ tick_low = price_to_tick(price_low.tao)
+ tick_high = price_to_tick(price_high.tao)
+
+ call = await subtensor.substrate.compose_call(
+ call_module="Swap",
+ call_function="add_liquidity",
+ call_params={
+ "hotkey": hotkey or wallet.hotkey.ss58_address,
+ "netuid": netuid,
+ "tick_low": tick_low,
+ "tick_high": tick_high,
+ "liquidity": liquidity.rao,
+ },
+ )
+
+ return await subtensor.sign_and_send_extrinsic(
+ call=call,
+ wallet=wallet,
+ wait_for_inclusion=wait_for_inclusion,
+ wait_for_finalization=wait_for_finalization,
+ use_nonce=True,
+ period=period,
+ )
+
+
+
+
+[docs]
+async def modify_liquidity_extrinsic(
+ subtensor: "AsyncSubtensor",
+ wallet: "Wallet",
+ netuid: int,
+ position_id: int,
+ liquidity_delta: Balance,
+ hotkey: Optional[str] = None,
+ wait_for_inclusion: bool = True,
+ wait_for_finalization: bool = False,
+ period: Optional[int] = None,
+) -> tuple[bool, str]:
+ """Modifies liquidity in liquidity position by adding or removing liquidity from it.
+
+ Arguments:
+ subtensor: The Subtensor client instance used for blockchain interaction.
+ wallet: The wallet used to sign the extrinsic (must be unlocked).
+ netuid: The UID of the target subnet for which the call is being initiated.
+ position_id: The id of the position record in the pool.
+ liquidity_delta: The amount of liquidity to be added or removed (add if positive or remove if negative).
+ hotkey: The hotkey with staked TAO in Alpha. If not passed then the wallet hotkey is used. Defaults to `None`.
+ wait_for_inclusion: Whether to wait for the extrinsic to be included in a block. Defaults to True.
+ wait_for_finalization: Whether to wait for finalization of the extrinsic. Defaults to False.
+ 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.
+ You can think of it as an expiration date for the transaction.
+
+ Returns:
+ Tuple[bool, str]:
+ - True and a success message if the extrinsic is successfully submitted or processed.
+ - False and an error message if the submission fails or the wallet cannot be unlocked.
+
+ Note: Modifying is allowed even when user liquidity is enabled in specified subnet.
+ Call `toggle_user_liquidity_extrinsic` to enable/disable user liquidity.
+ """
+ if not (unlock := unlock_key(wallet)).success:
+ logging.error(unlock.message)
+ return False, unlock.message
+
+ call = await subtensor.substrate.compose_call(
+ call_module="Swap",
+ call_function="modify_position",
+ call_params={
+ "hotkey": hotkey or wallet.hotkey.ss58_address,
+ "netuid": netuid,
+ "position_id": position_id,
+ "liquidity_delta": liquidity_delta.rao,
+ },
+ )
+
+ return await subtensor.sign_and_send_extrinsic(
+ call=call,
+ wallet=wallet,
+ wait_for_inclusion=wait_for_inclusion,
+ wait_for_finalization=wait_for_finalization,
+ use_nonce=True,
+ period=period,
+ )
+
+
+
+
+[docs]
+async def remove_liquidity_extrinsic(
+ subtensor: "AsyncSubtensor",
+ wallet: "Wallet",
+ netuid: int,
+ position_id: int,
+ hotkey: Optional[str] = None,
+ wait_for_inclusion: bool = True,
+ wait_for_finalization: bool = False,
+ period: Optional[int] = None,
+) -> tuple[bool, str]:
+ """Remove liquidity and credit balances back to wallet's hotkey stake.
+
+ Arguments:
+ subtensor: The Subtensor client instance used for blockchain interaction.
+ wallet: The wallet used to sign the extrinsic (must be unlocked).
+ netuid: The UID of the target subnet for which the call is being initiated.
+ position_id: The id of the position record in the pool.
+ hotkey: The hotkey with staked TAO in Alpha. If not passed then the wallet hotkey is used. Defaults to `None`.
+ wait_for_inclusion: Whether to wait for the extrinsic to be included in a block. Defaults to True.
+ wait_for_finalization: Whether to wait for finalization of the extrinsic. Defaults to False.
+ 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.
+ You can think of it as an expiration date for the transaction.
+
+ Returns:
+ Tuple[bool, str]:
+ - True and a success message if the extrinsic is successfully submitted or processed.
+ - False and an error message if the submission fails or the wallet cannot be unlocked.
+
+ Note: Adding is allowed even when user liquidity is enabled in specified subnet.
+ Call `toggle_user_liquidity_extrinsic` to enable/disable user liquidity.
+ """
+ if not (unlock := unlock_key(wallet)).success:
+ logging.error(unlock.message)
+ return False, unlock.message
+
+ call = await subtensor.substrate.compose_call(
+ call_module="Swap",
+ call_function="remove_liquidity",
+ call_params={
+ "hotkey": hotkey or wallet.hotkey.ss58_address,
+ "netuid": netuid,
+ "position_id": position_id,
+ },
+ )
+
+ return await subtensor.sign_and_send_extrinsic(
+ call=call,
+ wallet=wallet,
+ wait_for_inclusion=wait_for_inclusion,
+ wait_for_finalization=wait_for_finalization,
+ use_nonce=True,
+ period=period,
+ )
+
+
+
+
+[docs]
+async def toggle_user_liquidity_extrinsic(
+ subtensor: "AsyncSubtensor",
+ wallet: "Wallet",
+ netuid: int,
+ enable: bool,
+ wait_for_inclusion: bool = True,
+ wait_for_finalization: bool = False,
+ period: Optional[int] = None,
+) -> tuple[bool, str]:
+ """Allow to toggle user liquidity for specified subnet.
+
+ Arguments:
+ subtensor: The Subtensor client instance used for blockchain interaction.
+ wallet: The wallet used to sign the extrinsic (must be unlocked).
+ netuid: The UID of the target subnet for which the call is being initiated.
+ enable: Boolean indicating whether to enable user liquidity.
+ wait_for_inclusion: Whether to wait for the extrinsic to be included in a block. Defaults to True.
+ wait_for_finalization: Whether to wait for finalization of the extrinsic. Defaults to False.
+ 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.
+ You can think of it as an expiration date for the transaction.
+
+ Returns:
+ Tuple[bool, str]:
+ - True and a success message if the extrinsic is successfully submitted or processed.
+ - False and an error message if the submission fails or the wallet cannot be unlocked.
+ """
+ if not (unlock := unlock_key(wallet)).success:
+ logging.error(unlock.message)
+ return False, unlock.message
+
+ call = await subtensor.substrate.compose_call(
+ call_module="Swap",
+ call_function="toggle_user_liquidity",
+ call_params={"netuid": netuid, "enable": enable},
+ )
+
+ return await subtensor.sign_and_send_extrinsic(
+ call=call,
+ wallet=wallet,
+ wait_for_inclusion=wait_for_inclusion,
+ wait_for_finalization=wait_for_finalization,
+ period=period,
+ )
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/move_stake.html b/static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/move_stake.html
index 171b5353e1..64ba07a0e1 100644
--- a/static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/move_stake.html
+++ b/static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/move_stake.html
@@ -160,25 +160,28 @@
bittensor.core.settings
bittensor.core.stream
bittensor.core.subtensor
-bittensor.core.subtensor_api
bittensor.core.synapse
bittensor.core.tensor
bittensor.core.threadpool
-bittensor.core.timelock
bittensor.core.types
+bittensor.extras
bittensor.utils
- bittensor.utils.axon_utils
- bittensor.utils.balance
- bittensor.utils.btlogging
- bittensor.utils.easy_imports
- bittensor.utils.formatting
-- bittensor.utils.mock
+- bittensor.utils.liquidity
- bittensor.utils.networking
- bittensor.utils.registration
- bittensor.utils.subnets
-- bittensor.utils.substrate_utils
- bittensor.utils.version
- bittensor.utils.weight_utils
@@ -335,7 +338,7 @@
Source code for bittensor.core.extrinsics.asyncex.move_stake
import asyncio
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Optional
from bittensor.utils.balance import Balance
from bittensor.utils.btlogging import logging
@@ -354,6 +357,7 @@ Source code for bittensor.core.extrinsics.asyncex.move_stake
origin_netuid: int,
destination_netuid: int,
) -> tuple[Balance, Balance]:
+ """Gets the current stake balances for both origin and destination addresses in their respective subnets."""
block_hash = await subtensor.substrate.get_chain_head()
stake_in_origin, stake_in_destination = await asyncio.gather(
subtensor.get_stake(
@@ -384,6 +388,7 @@ Source code for bittensor.core.extrinsics.asyncex.move_stake
amount: Balance,
wait_for_inclusion: bool = True,
wait_for_finalization: bool = False,
+ period: Optional[int] = None,
) -> bool:
"""
Transfers stake from one coldkey to another in the Bittensor network.
@@ -398,6 +403,9 @@ Source code for bittensor.core.extrinsics.asyncex.move_stake
amount (Balance): The amount of stake to transfer as a `Balance` object.
wait_for_inclusion (bool): If True, waits for transaction inclusion in a block. Defaults to `True`.
wait_for_finalization (bool): If True, waits for transaction finalization. Defaults to `False`.
+ 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.
Returns:
bool: True if the transfer was successful, False otherwise.
@@ -415,7 +423,7 @@ Source code for bittensor.core.extrinsics.asyncex.move_stake
# Check sufficient stake
stake_in_origin, stake_in_destination = await _get_stake_in_origin_and_dest(
- subtensor,
+ subtensor=subtensor,
origin_hotkey_ss58=hotkey_ss58,
destination_hotkey_ss58=hotkey_ss58,
origin_coldkey_ss58=wallet.coldkeypub.ss58_address,
@@ -454,6 +462,7 @@ Source code for bittensor.core.extrinsics.asyncex.move_stake
wallet=wallet,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
+ period=period,
)
if success:
@@ -464,7 +473,7 @@ Source code for bittensor.core.extrinsics.asyncex.move_stake
# Get updated stakes
origin_stake, dest_stake = await _get_stake_in_origin_and_dest(
- subtensor,
+ subtensor=subtensor,
origin_hotkey_ss58=hotkey_ss58,
destination_hotkey_ss58=hotkey_ss58,
origin_coldkey_ss58=wallet.coldkeypub.ss58_address,
@@ -501,6 +510,10 @@ Source code for bittensor.core.extrinsics.asyncex.move_stake
amount: Balance,
wait_for_inclusion: bool = True,
wait_for_finalization: bool = False,
+ safe_staking: bool = False,
+ allow_partial_stake: bool = False,
+ rate_tolerance: float = 0.005,
+ period: Optional[int] = None,
) -> bool:
"""
Swaps stake from one subnet to another for a given hotkey in the Bittensor network.
@@ -514,6 +527,12 @@ Source code for bittensor.core.extrinsics.asyncex.move_stake
amount (Balance): The amount of stake to swap as a `Balance` object.
wait_for_inclusion (bool): If True, waits for transaction inclusion in a block. Defaults to True.
wait_for_finalization (bool): If True, waits for transaction finalization. Defaults to False.
+ safe_staking (bool): If true, enables price safety checks to protect against price impact.
+ allow_partial_stake (bool): If true, allows partial stake swaps when the full amount would exceed the price tolerance.
+ rate_tolerance (float): Maximum allowed increase in a price ratio (0.005 = 0.5%).
+ 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.
Returns:
bool: True if the swap was successful, False otherwise.
@@ -530,7 +549,7 @@ Source code for bittensor.core.extrinsics.asyncex.move_stake
# Check sufficient stake
stake_in_origin, stake_in_destination = await _get_stake_in_origin_and_dest(
- subtensor,
+ subtensor=subtensor,
origin_hotkey_ss58=hotkey_ss58,
destination_hotkey_ss58=hotkey_ss58,
origin_coldkey_ss58=wallet.coldkeypub.ss58_address,
@@ -546,20 +565,47 @@ Source code for bittensor.core.extrinsics.asyncex.move_stake
return False
try:
- logging.info(
- f"Swapping stake for hotkey [blue]{hotkey_ss58}[/blue]\n"
- f"Amount: [green]{amount}[/green] from netuid [yellow]{origin_netuid}[/yellow] to netuid "
- f"[yellow]{destination_netuid}[/yellow]"
- )
+ call_params = {
+ "hotkey": hotkey_ss58,
+ "origin_netuid": origin_netuid,
+ "destination_netuid": destination_netuid,
+ "alpha_amount": amount.rao,
+ }
+
+ if safe_staking:
+ origin_pool, destination_pool = await asyncio.gather(
+ subtensor.subnet(netuid=origin_netuid),
+ subtensor.subnet(netuid=destination_netuid),
+ )
+ swap_rate_ratio = origin_pool.price.rao / destination_pool.price.rao
+ swap_rate_ratio_with_tolerance = swap_rate_ratio * (1 + rate_tolerance)
+
+ logging.info(
+ f"Swapping stake with safety for hotkey [blue]{hotkey_ss58}[/blue]\n"
+ f"Amount: [green]{amount}[/green] from netuid [green]{origin_netuid}[/green] to netuid "
+ f"[green]{destination_netuid}[/green]\n"
+ f"Current price ratio: [green]{swap_rate_ratio:.4f}[/green], "
+ f"Ratio with tolerance: [green]{swap_rate_ratio_with_tolerance:.4f}[/green]"
+ )
+ call_params.update(
+ {
+ "limit_price": swap_rate_ratio_with_tolerance,
+ "allow_partial": allow_partial_stake,
+ }
+ )
+ call_function = "swap_stake_limit"
+ else:
+ logging.info(
+ f"Swapping stake for hotkey [blue]{hotkey_ss58}[/blue]\n"
+ f"Amount: [green]{amount}[/green] from netuid [green]{origin_netuid}[/green] to netuid "
+ f"[green]{destination_netuid}[/green]"
+ )
+ call_function = "swap_stake"
+
call = await subtensor.substrate.compose_call(
call_module="SubtensorModule",
- call_function="swap_stake",
- call_params={
- "hotkey": hotkey_ss58,
- "origin_netuid": origin_netuid,
- "destination_netuid": destination_netuid,
- "alpha_amount": amount.rao,
- },
+ call_function=call_function,
+ call_params=call_params,
)
success, err_msg = await subtensor.sign_and_send_extrinsic(
@@ -567,6 +613,7 @@ Source code for bittensor.core.extrinsics.asyncex.move_stake
wallet=wallet,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
+ period=period,
)
if success:
@@ -594,7 +641,12 @@ Source code for bittensor.core.extrinsics.asyncex.move_stake
return True
else:
- logging.error(f":cross_mark: [red]Failed[/red]: {err_msg}")
+ if safe_staking and "Custom error: 8" in err_msg:
+ logging.error(
+ ":cross_mark: [red]Failed[/red]: Price ratio exceeded tolerance limit. Either increase price tolerance or enable partial staking."
+ )
+ else:
+ logging.error(f":cross_mark: [red]Failed[/red]: {err_msg}")
return False
except Exception as e:
@@ -615,6 +667,7 @@ Source code for bittensor.core.extrinsics.asyncex.move_stake
amount: Balance,
wait_for_inclusion: bool = True,
wait_for_finalization: bool = False,
+ period: Optional[int] = None,
) -> bool:
"""
Moves stake from one hotkey to another within subnets in the Bittensor network.
@@ -629,6 +682,9 @@ Source code for bittensor.core.extrinsics.asyncex.move_stake
amount (Balance): The amount of stake to move as a `Balance` object.
wait_for_inclusion (bool): If True, waits for transaction inclusion in a block. Defaults to True.
wait_for_finalization (bool): If True, waits for transaction finalization. Defaults to False.
+ 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.
Returns:
bool: True if the move was successful, False otherwise.
@@ -637,7 +693,7 @@ Source code for bittensor.core.extrinsics.asyncex.move_stake
# Check sufficient stake
stake_in_origin, stake_in_destination = await _get_stake_in_origin_and_dest(
- subtensor,
+ subtensor=subtensor,
origin_hotkey_ss58=origin_hotkey,
destination_hotkey_ss58=destination_hotkey,
origin_coldkey_ss58=wallet.coldkeypub.ss58_address,
@@ -675,6 +731,7 @@ Source code for bittensor.core.extrinsics.asyncex.move_stake
wallet=wallet,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
+ period=period,
)
if success:
@@ -685,7 +742,7 @@ Source code for bittensor.core.extrinsics.asyncex.move_stake
# Get updated stakes
origin_stake, dest_stake = await _get_stake_in_origin_and_dest(
- subtensor,
+ subtensor=subtensor,
origin_hotkey_ss58=origin_hotkey,
destination_hotkey_ss58=destination_hotkey,
origin_coldkey_ss58=wallet.coldkeypub.ss58_address,
diff --git a/static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/registration.html b/static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/registration.html
index 2de198ec38..65198c9336 100644
--- a/static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/registration.html
+++ b/static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/registration.html
@@ -160,25 +160,28 @@
bittensor.core.settings
bittensor.core.stream
bittensor.core.subtensor
-bittensor.core.subtensor_api
bittensor.core.synapse
bittensor.core.tensor
bittensor.core.threadpool
-bittensor.core.timelock
bittensor.core.types
+bittensor.extras
bittensor.utils
- bittensor.utils.axon_utils
- bittensor.utils.balance
- bittensor.utils.btlogging
- bittensor.utils.easy_imports
- bittensor.utils.formatting
-- bittensor.utils.mock
+- bittensor.utils.liquidity
- bittensor.utils.networking
- bittensor.utils.registration
- bittensor.utils.subnets
-- bittensor.utils.substrate_utils
- bittensor.utils.version
- bittensor.utils.weight_utils
@@ -346,7 +349,7 @@ Source code for bittensor.core.extrinsics.asyncex.registration
import asyncio
from typing import Optional, Union, TYPE_CHECKING
-from bittensor.utils import unlock_key, format_error_message
+from bittensor.utils import unlock_key
from bittensor.utils.btlogging import logging
from bittensor.utils.registration import log_no_torch_error, create_pow_async, torch
@@ -362,6 +365,7 @@ Source code for bittensor.core.extrinsics.asyncex.registration
wallet: "Wallet",
wait_for_inclusion: bool = False,
wait_for_finalization: bool = True,
+ period: Optional[int] = None,
) -> tuple[bool, str]:
"""
Performs a burned register extrinsic call to the Subtensor chain.
@@ -374,6 +378,9 @@ Source code for bittensor.core.extrinsics.asyncex.registration
wallet (bittensor_wallet.Wallet): The wallet to be registered.
wait_for_inclusion (bool): Whether to wait for the transaction to be included in a block. Default is False.
wait_for_finalization (bool): Whether to wait for the transaction to be finalized. Default 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.
Returns:
Tuple[bool, Optional[str]]: A tuple containing a boolean indicating success or failure, and an optional error
@@ -394,6 +401,7 @@ Source code for bittensor.core.extrinsics.asyncex.registration
wallet=wallet,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
+ period=period,
)
@@ -405,6 +413,7 @@ Source code for bittensor.core.extrinsics.asyncex.registration
netuid: int,
wait_for_inclusion: bool = False,
wait_for_finalization: bool = True,
+ period: Optional[int] = None,
) -> bool:
"""Registers the wallet to chain by recycling TAO.
@@ -416,6 +425,9 @@ Source code for bittensor.core.extrinsics.asyncex.registration
returns ``False`` if the extrinsic fails to enter the block within the timeout.
wait_for_finalization (bool): If set, waits for the extrinsic to be finalized on the chain before returning
``True``, or returns ``False`` if the extrinsic fails to be finalized within the timeout.
+ 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.
Returns:
success (bool): Flag is ``True`` if extrinsic was finalized or included in the block. If we did not wait for
@@ -436,7 +448,7 @@ Source code for bittensor.core.extrinsics.asyncex.registration
f":satellite: [magenta]Checking Account on subnet[/magenta] [blue]{netuid}[/blue][magenta] ...[/magenta]"
)
- # We could do this as_completed because we don't actually need old_balance and recycle
+ # We could do this as_completed because we don't need old_balance and recycle
# if neuron is null, but the complexity isn't worth it considering the small performance
# gains we'd hypothetically receive in this situation
neuron, old_balance, recycle_amount = await asyncio.gather(
@@ -464,6 +476,7 @@ Source code for bittensor.core.extrinsics.asyncex.registration
wallet=wallet,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
+ period=period,
)
if not success:
@@ -501,6 +514,7 @@ Source code for bittensor.core.extrinsics.asyncex.registration
pow_result: "POWSolution",
wait_for_inclusion: bool = False,
wait_for_finalization: bool = True,
+ period: Optional[int] = None,
) -> tuple[bool, Optional[str]]:
"""Sends a (POW) register extrinsic to the chain.
@@ -511,6 +525,9 @@ Source code for bittensor.core.extrinsics.asyncex.registration
pow_result (POWSolution): The PoW result to register.
wait_for_inclusion (bool): If ``True``, waits for the extrinsic to be included in a block. Default to `False`.
wait_for_finalization (bool): If ``True``, waits for the extrinsic to be finalized. Default to `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.
Returns:
success (bool): ``True`` if the extrinsic was included in a block.
@@ -535,6 +552,7 @@ Source code for bittensor.core.extrinsics.asyncex.registration
wallet=wallet,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
+ period=period,
)
@@ -554,6 +572,7 @@ Source code for bittensor.core.extrinsics.asyncex.registration
num_processes: Optional[int] = None,
update_interval: Optional[int] = None,
log_verbose: bool = False,
+ period: Optional[int] = None,
) -> bool:
"""Registers the wallet to the chain.
@@ -574,6 +593,9 @@ Source code for bittensor.core.extrinsics.asyncex.registration
num_processes: The number of processes to use to register.
update_interval: The number of nonces to solve between updates.
log_verbose: 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.
Returns:
`True` if extrinsic was finalized or included in the block. If we did not wait for finalization/inclusion, the
@@ -662,7 +684,7 @@ Source code for bittensor.core.extrinsics.asyncex.registration
# pow successful, proceed to submit pow to chain for registration
else:
logging.info(":satellite: [magenta]Submitting POW...[/magenta]")
- # check if pow result is still valid
+ # check if a pow result is still valid
while not await pow_result.is_stale_async(subtensor=subtensor):
result: tuple[bool, Optional[str]] = await _do_pow_register(
subtensor=subtensor,
@@ -671,6 +693,7 @@ Source code for bittensor.core.extrinsics.asyncex.registration
pow_result=pow_result,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
+ period=period,
)
success, err_msg = result
@@ -730,6 +753,7 @@ Source code for bittensor.core.extrinsics.asyncex.registration
wallet: "Wallet",
wait_for_inclusion: bool = False,
wait_for_finalization: bool = True,
+ period: Optional[int] = None,
) -> bool:
"""
Registers a new subnetwork on the Bittensor blockchain asynchronously.
@@ -739,6 +763,9 @@ Source code for bittensor.core.extrinsics.asyncex.registration
wallet (Wallet): The wallet to be used for subnet registration.
wait_for_inclusion (bool): If set, waits for the extrinsic to enter a block before returning true.
wait_for_finalization (bool): If set, waits for the extrinsic to be finalized on the chain before returning 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.
Returns:
bool: True if the subnet registration was successful, False otherwise.
@@ -761,29 +788,25 @@ Source code for bittensor.core.extrinsics.asyncex.registration
},
)
- extrinsic = await subtensor.substrate.create_signed_extrinsic(
- call=call, keypair=wallet.coldkey
- )
-
- response = await subtensor.substrate.submit_extrinsic(
- extrinsic,
+ success, message = await subtensor.sign_and_send_extrinsic(
+ call=call,
+ wallet=wallet,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
+ period=period,
)
if not wait_for_finalization and not wait_for_inclusion:
return True
- if not await response.is_success:
- logging.error(
- f"Failed to register subnet: {format_error_message(await response.error_message)}"
+ if success:
+ logging.success(
+ ":white_heavy_check_mark: [green]Successfully registered subnet[/green]"
)
- return False
+ return True
- logging.success(
- ":white_heavy_check_mark: [green]Successfully registered subnet[/green]"
- )
- return True
+ logging.error(f"Failed to register subnet: {message}")
+ return False
@@ -797,11 +820,13 @@ Source code for bittensor.core.extrinsics.asyncex.registration
github_repo: str,
subnet_contact: str,
subnet_url: str,
+ logo_url: str,
discord: str,
description: str,
additional: str,
wait_for_inclusion: bool = False,
wait_for_finalization: bool = True,
+ period: Optional[int] = None,
) -> tuple[bool, str]:
"""
Set the identity information for a given subnet.
@@ -814,11 +839,15 @@ Source code for bittensor.core.extrinsics.asyncex.registration
github_repo (str): URL of the GitHub repository related to the subnet.
subnet_contact (str): Subnet's contact information, e.g., email or contact link.
subnet_url (str): The URL of the subnet's primary web portal.
+ logo_url (str): The URL of the logo's primary web portal.
discord (str): Discord server or contact for the subnet.
description (str): A textual description of the subnet.
additional (str): Any additional metadata or information related to the subnet.
wait_for_inclusion (bool): Whether to wait for the extrinsic inclusion in a block (default: False).
wait_for_finalization (bool): Whether to wait for the extrinsic finalization in a block (default: 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.
Returns:
tuple[bool, str]: A tuple where the first element indicates success or failure (True/False), and the second
@@ -839,33 +868,34 @@ Source code for bittensor.core.extrinsics.asyncex.registration
"github_repo": github_repo,
"subnet_contact": subnet_contact,
"subnet_url": subnet_url,
+ "logo_url": logo_url,
"discord": discord,
"description": description,
"additional": additional,
},
)
- response = await subtensor.substrate.submit_extrinsic(
+ success, message = await subtensor.sign_and_send_extrinsic(
call=call,
wallet=wallet,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
+ period=period,
)
if not wait_for_finalization and not wait_for_inclusion:
- return True, f"Identities for subnet {netuid} are sent to the chain."
+ return True, message
- if await response.is_success:
+ if success:
logging.success(
f":white_heavy_check_mark: [green]Identities for subnet[/green] [blue]{netuid}[/blue] [green]are set.[/green]"
)
return True, f"Identities for subnet {netuid} are set."
- else:
- error_message = await response.error_message
- logging.error(
- f":cross_mark: Failed to set identity for subnet [blue]{netuid}[/blue]: {error_message}"
- )
- return False, f"Failed to set identity for subnet {netuid}: {error_message}"
+
+ logging.error(
+ f":cross_mark: Failed to set identity for subnet [blue]{netuid}[/blue]: {message}"
+ )
+ return False, f"Failed to set identity for subnet {netuid}: {message}"
diff --git a/static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/root.html b/static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/root.html
index 63087eca55..9cc9e60cbf 100644
--- a/static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/root.html
+++ b/static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/root.html
@@ -160,25 +160,28 @@
bittensor.core.settings
bittensor.core.stream
bittensor.core.subtensor
-bittensor.core.subtensor_api
bittensor.core.synapse
bittensor.core.tensor
bittensor.core.threadpool
-bittensor.core.timelock
bittensor.core.types
+bittensor.extras
bittensor.utils
- bittensor.utils.axon_utils
- bittensor.utils.balance
- bittensor.utils.btlogging
- bittensor.utils.easy_imports
- bittensor.utils.formatting
-- bittensor.utils.mock
+- bittensor.utils.liquidity
- bittensor.utils.networking
- bittensor.utils.registration
- bittensor.utils.subnets
-- bittensor.utils.substrate_utils
- bittensor.utils.version
- bittensor.utils.weight_utils
@@ -335,21 +338,23 @@
Source code for bittensor.core.extrinsics.asyncex.root
import asyncio
-from typing import Union, TYPE_CHECKING
+from typing import Optional, Union, TYPE_CHECKING
-from bittensor_wallet import Wallet
import numpy as np
from numpy.typing import NDArray
from bittensor.core.errors import SubstrateRequestException
from bittensor.utils import u16_normalized_float, format_error_message, unlock_key
+from bittensor.utils.balance import Balance
from bittensor.utils.btlogging import logging
from bittensor.utils.weight_utils import (
normalize_max_weight,
convert_weights_and_uids_for_emit,
+ convert_uids_and_weights,
)
if TYPE_CHECKING:
+ from bittensor_wallet import Wallet
from bittensor.core.async_subtensor import AsyncSubtensor
@@ -384,8 +389,9 @@ Source code for bittensor.core.extrinsics.asyncex.root
wallet: "Wallet",
wait_for_inclusion: bool = True,
wait_for_finalization: bool = True,
+ period: Optional[int] = None,
) -> bool:
- """Registers the wallet to root network.
+ """Registers the wallet to the root network.
Arguments:
subtensor (bittensor.core.async_subtensor.AsyncSubtensor): The AsyncSubtensor object
@@ -394,12 +400,42 @@ Source code for bittensor.core.extrinsics.asyncex.root
`False` if the extrinsic fails to enter the block within the timeout.
wait_for_finalization (bool): If set, waits for the extrinsic to be finalized on the chain before returning
`True`, or returns `False` if the extrinsic fails to be finalized within the timeout.
+ 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.
Returns:
`True` if extrinsic was finalized or included in the block. If we did not wait for finalization/inclusion,
the response is `True`.
"""
netuid = 0
+ logging.info(
+ f"Registering on netuid [blue]{netuid}[/blue] on network: [blue]{subtensor.network}[/blue]"
+ )
+
+ logging.info("Fetching recycle amount & balance.")
+ block_hash = await subtensor.get_block_hash()
+ recycle_call, balance = await asyncio.gather(
+ subtensor.get_hyperparameter(
+ param_name="Burn",
+ netuid=netuid,
+ block_hash=block_hash,
+ ),
+ subtensor.get_balance(
+ wallet.coldkeypub.ss58_address,
+ block_hash=block_hash,
+ ),
+ )
+
+ current_recycle = Balance.from_rao(int(recycle_call))
+
+ if balance < current_recycle:
+ logging.error(
+ f"[red]Insufficient balance {balance} to register neuron. "
+ f"Current recycle is {current_recycle} TAO[/red]."
+ )
+ return False
+
if not (unlock := unlock_key(wallet)).success:
logging.error(unlock.message)
return False
@@ -422,15 +458,16 @@ Source code for bittensor.core.extrinsics.asyncex.root
call_function="root_register",
call_params={"hotkey": wallet.hotkey.ss58_address},
)
- success, err_msg = await subtensor.sign_and_send_extrinsic(
- call,
+ success, message = await subtensor.sign_and_send_extrinsic(
+ call=call,
wallet=wallet,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
+ period=period,
)
if not success:
- logging.error(f":cross_mark: [red]Failed error:[/red] {err_msg}")
+ logging.error(f":cross_mark: [red]Failed error:[/red] {message}")
await asyncio.sleep(0.5)
return False
@@ -462,7 +499,7 @@ Source code for bittensor.core.extrinsics.asyncex.root
version_key: int = 0,
wait_for_inclusion: bool = False,
wait_for_finalization: bool = False,
- period: int = 5,
+ period: Optional[int] = 8,
) -> tuple[bool, str]:
"""
Sets the root weights on the Subnet for the given wallet hotkey account.
@@ -482,7 +519,9 @@ Source code for bittensor.core.extrinsics.asyncex.root
False.
wait_for_finalization (bool, optional): If True, waits for the extrinsic to be finalized on the chain. Defaults
to False.
- period (int, optional): The period in seconds to wait for extrinsic inclusion or finalization. Defaults to 5.
+ 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.
Returns:
tuple: Returns a tuple containing a boolean indicating success and a message describing the result of the
@@ -500,34 +539,25 @@ Source code for bittensor.core.extrinsics.asyncex.root
},
)
- next_nonce = await subtensor.substrate.get_account_next_index(
- wallet.hotkey.ss58_address
- )
-
- # Period dictates how long the extrinsic will stay as part of waiting pool
- extrinsic = await subtensor.substrate.create_signed_extrinsic(
+ success, message = await subtensor.sign_and_send_extrinsic(
call=call,
- keypair=wallet.coldkey,
- era={"period": period},
- nonce=next_nonce,
- )
- response = await subtensor.substrate.submit_extrinsic(
- extrinsic=extrinsic,
+ wallet=wallet,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
+ use_nonce=True,
+ period=period,
)
+
# We only wait here if we expect finalization.
if not wait_for_finalization and not wait_for_inclusion:
- return True, "Not waiting for finalization or inclusion."
+ return True, message
- if await response.is_success:
+ if success:
return True, "Successfully set weights."
- return False, format_error_message(await response.error_message)
+ return False, message
-
-[docs]
async def set_root_weights_extrinsic(
subtensor: "AsyncSubtensor",
wallet: "Wallet",
@@ -536,20 +566,24 @@ Source code for bittensor.core.extrinsics.asyncex.root
version_key: int = 0,
wait_for_inclusion: bool = False,
wait_for_finalization: bool = False,
+ period: Optional[int] = None,
) -> bool:
- """Sets the given weights and values on chain for wallet hotkey account.
+ """Sets the given weights and values on a chain for a wallet hotkey account.
Arguments:
subtensor (bittensor.core.async_subtensor.AsyncSubtensor): The AsyncSubtensor object
wallet (bittensor_wallet.Wallet): Bittensor wallet object.
netuids (Union[NDArray[np.int64], list[int]]): The `netuid` of the subnet to set weights for.
- weights (Union[NDArray[np.float32], list[float]]): Weights to set. These must be `float` s and must correspond
+ weights (Union[NDArray[np.float32], list[Float]]): Weights to set. These must be `Float`s and must correspond
to the passed `netuid` s.
version_key (int): The version key of the validator.
wait_for_inclusion (bool): If set, waits for the extrinsic to enter a block before returning `True`, or returns
`False` if the extrinsic fails to enter the block within the timeout.
wait_for_finalization (bool): If set, waits for the extrinsic to be finalized on the chain before returning `
True`, or returns `False` if the extrinsic fails to be finalized within the timeout.
+ 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.
Returns:
`True` if extrinsic was finalized or included in the block. If we did not wait for finalization/inclusion, the
@@ -567,13 +601,10 @@ Source code for bittensor.core.extrinsics.asyncex.root
logging.error(unlock.message)
return False
- # First convert types.
- if isinstance(netuids, list):
- netuids = np.array(netuids, dtype=np.int64)
- if isinstance(weights, list):
- weights = np.array(weights, dtype=np.float32)
+ # Convert types.
+ netuids, weights = convert_uids_and_weights(netuids, weights)
- logging.debug("Fetching weight limits")
+ logging.debug("[magenta]Fetching weight limits ...[/magenta]")
min_allowed_weights, max_weight_limit = await _get_limits(subtensor)
# Get non zero values.
@@ -587,7 +618,7 @@ Source code for bittensor.core.extrinsics.asyncex.root
)
# Normalize the weights to max value.
- logging.info("Normalizing weights")
+ logging.info("[magenta]Normalizing weights ...[/magenta]")
formatted_weights = normalize_max_weight(x=weights, limit=max_weight_limit)
logging.info(
f"Raw weights -> Normalized weights: [blue]{weights}[/blue] -> [green]{formatted_weights}[/green]"
@@ -605,11 +636,9 @@ Source code for bittensor.core.extrinsics.asyncex.root
version_key=version_key,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
+ period=period,
)
- if not wait_for_finalization and not wait_for_inclusion:
- return True
-
if success is True:
logging.info(":white_heavy_check_mark: [green]Finalized[/green]")
return True
@@ -621,8 +650,7 @@ Source code for bittensor.core.extrinsics.asyncex.root
except SubstrateRequestException as e:
fmt_err = format_error_message(e)
logging.error(f":cross_mark: [red]Failed error:[/red] {fmt_err}")
- return False
-
+ return False
diff --git a/static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/serving.html b/static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/serving.html
index 81e33eee7b..cd3e348572 100644
--- a/static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/serving.html
+++ b/static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/serving.html
@@ -160,25 +160,28 @@
bittensor.core.settings
bittensor.core.stream
bittensor.core.subtensor
-bittensor.core.subtensor_api
bittensor.core.synapse
bittensor.core.tensor
bittensor.core.threadpool
-bittensor.core.timelock
bittensor.core.types
+bittensor.extras
bittensor.utils
- bittensor.utils.axon_utils
- bittensor.utils.balance
- bittensor.utils.btlogging
- bittensor.utils.easy_imports
- bittensor.utils.formatting
-- bittensor.utils.mock
+- bittensor.utils.liquidity
- bittensor.utils.networking
- bittensor.utils.registration
- bittensor.utils.subnets
-- bittensor.utils.substrate_utils
- bittensor.utils.version
- bittensor.utils.weight_utils
@@ -335,18 +338,17 @@
Source code for bittensor.core.extrinsics.asyncex.serving
import asyncio
-from typing import Optional, TYPE_CHECKING
+from typing import Optional, Union, TYPE_CHECKING
from bittensor.core.errors import MetadataError
from bittensor.core.settings import version_as_int
+from bittensor.core.types import AxonServeCallParams
from bittensor.utils import (
- format_error_message,
networking as net,
unlock_key,
Certificate,
)
from bittensor.utils.btlogging import logging
-from bittensor.core.types import AxonServeCallParams
if TYPE_CHECKING:
from bittensor.core.axon import Axon
@@ -354,15 +356,14 @@ Source code for bittensor.core.extrinsics.asyncex.serving
from bittensor_wallet import Wallet
-
-[docs]
async def do_serve_axon(
subtensor: "AsyncSubtensor",
wallet: "Wallet",
call_params: "AxonServeCallParams",
wait_for_inclusion: bool = False,
wait_for_finalization: bool = True,
-) -> tuple[bool, Optional[dict]]:
+ period: Optional[int] = None,
+) -> tuple[bool, str]:
"""
Internal method to submit a serve axon transaction to the Bittensor blockchain. This method creates and submits a
transaction, enabling a neuron's ``Axon`` to serve requests on the network.
@@ -373,9 +374,12 @@ Source code for bittensor.core.extrinsics.asyncex.serving
call_params (bittensor.core.types.AxonServeCallParams): Parameters required for the serve axon call.
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.
+ 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.
Returns:
- tuple[bool, Optional[str]]: A tuple containing a success flag and an optional error message.
+ tuple[bool, str]: A tuple containing a success flag and an optional error message.
This function is crucial for initializing and announcing a neuron's ``Axon`` service on the network, enhancing the
decentralized computation capabilities of Bittensor.
@@ -391,22 +395,15 @@ Source code for bittensor.core.extrinsics.asyncex.serving
call_function=call_function,
call_params=call_params.dict(),
)
- extrinsic = await subtensor.substrate.create_signed_extrinsic(
- call=call, keypair=wallet.hotkey
- )
- response = await subtensor.substrate.submit_extrinsic(
- extrinsic=extrinsic,
+ success, message = await subtensor.sign_and_send_extrinsic(
+ call=call,
+ wallet=wallet,
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
+ sign_with="hotkey",
+ period=period,
)
- if wait_for_inclusion or wait_for_finalization:
- if await response.is_success:
- return True, None
-
- return False, await response.error_message
-
- return True, None
-
+ return success, message
@@ -423,6 +420,7 @@ Source code for bittensor.core.extrinsics.asyncex.serving
wait_for_inclusion: bool = False,
wait_for_finalization=True,
certificate: Optional[Certificate] = None,
+ period: Optional[int] = None,
) -> bool:
"""Subscribes a Bittensor endpoint to the subtensor chain.
@@ -441,6 +439,9 @@ Source code for bittensor.core.extrinsics.asyncex.serving
``True``, or returns ``False`` if the extrinsic fails to be finalized within the timeout.
certificate (bittensor.utils.Certificate): Certificate to use for TLS. If ``None``, no TLS will be used.
Defaults to ``None``.
+ 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.
Returns:
success (bool): Flag is ``True`` if extrinsic was finalized or included in the block. If we did not wait for
@@ -473,32 +474,32 @@ Source code for bittensor.core.extrinsics.asyncex.serving
neuron_up_to_date = not neuron.is_null and params == neuron
if neuron_up_to_date:
logging.debug(
- f"Axon already served on: AxonInfo({wallet.hotkey.ss58_address},{ip}:{port}) "
+ f"Axon already served on: [blue]AxonInfo({wallet.hotkey.ss58_address}, {ip}:{port})[/blue]"
)
return True
logging.debug(
- f"Serving axon with: AxonInfo({wallet.hotkey.ss58_address},{ip}:{port}) -> {subtensor.network}:{netuid}"
+ f"Serving axon with: [blue]AxonInfo({wallet.hotkey.ss58_address}, {ip}:{port})[/blue] -> "
+ f"[green]{subtensor.network}:{netuid}[/green]"
)
- success, error_message = await do_serve_axon(
+ success, message = await do_serve_axon(
subtensor=subtensor,
wallet=wallet,
call_params=params,
wait_for_finalization=wait_for_finalization,
wait_for_inclusion=wait_for_inclusion,
+ period=period,
)
- if wait_for_inclusion or wait_for_finalization:
- if success is True:
- logging.debug(
- f"Axon served with: AxonInfo({wallet.hotkey.ss58_address},{ip}:{port}) on {subtensor.network}:{netuid} "
- )
- return True
- else:
- logging.error(f"Failed: {format_error_message(error_message)}")
- return False
- else:
- return True
+ if success:
+ logging.debug(
+ f"Axon served with: [blue]AxonInfo({wallet.hotkey.ss58_address}, {ip}:{port})[/blue] on "
+ f"[green]{subtensor.network}:{netuid}[/green]"
+ )
+ return True
+
+ logging.error(f"Failed: {message}")
+ return False
@@ -511,6 +512,7 @@ Source code for bittensor.core.extrinsics.asyncex.serving
wait_for_inclusion: bool = False,
wait_for_finalization: bool = True,
certificate: Optional[Certificate] = None,
+ period: Optional[int] = None,
) -> bool:
"""Serves the axon to the network.
@@ -524,6 +526,9 @@ Source code for bittensor.core.extrinsics.asyncex.serving
``True``, or returns ``False`` if the extrinsic fails to be finalized within the timeout.
certificate (bittensor.utils.Certificate): Certificate to use for TLS. If ``None``, no TLS will be used.
Defaults to ``None``.
+ 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.
Returns:
success (bool): Flag is ``True`` if extrinsic was finalized or included in the block. If we did not wait for
@@ -561,21 +566,22 @@ Source code for bittensor.core.extrinsics.asyncex.serving
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
certificate=certificate,
+ period=period,
)
return serve_success
-
-[docs]
async def publish_metadata(
subtensor: "AsyncSubtensor",
wallet: "Wallet",
netuid: int,
data_type: str,
- data: bytes,
+ data: Union[bytes, dict],
wait_for_inclusion: bool = False,
wait_for_finalization: bool = True,
+ period: Optional[int] = None,
+ reset_bonds: bool = False,
) -> bool:
"""
Publishes metadata on the Bittensor network using the specified wallet and network identifier.
@@ -587,18 +593,22 @@ Source code for bittensor.core.extrinsics.asyncex.serving
data_type (str): The data type of the information being submitted. It should be one of the following:
``'Sha256'``, ``'Blake256'``, ``'Keccak256'``, or ``'Raw0-128'``. This specifies the format or hashing
algorithm used for the data.
- data (str): The actual metadata content to be published. This should be formatted or hashed according to the
- ``type`` specified. (Note: max ``str`` length is 128 bytes)
+ data (Union[bytes, dict]): The actual metadata content to be published. This should be formatted or hashed
+ according to the ``type`` specified. (Note: max ``str`` length is 128 bytes for ``'Raw0-128'``.)
wait_for_inclusion (bool, optional): If ``True``, the function will wait for the extrinsic to be included in a
block before returning. Defaults to ``False``.
wait_for_finalization (bool, optional): If ``True``, the function will wait for the extrinsic to be finalized
on the chain before returning. Defaults to ``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.
+ reset_bonds (bool): If `True`, the function will reset the bonds for the neuron. Defaults to `False`.
Returns:
bool: ``True`` if the metadata was successfully published (and finalized if specified). ``False`` otherwise.
Raises:
- MetadataError: If there is an error in submitting the extrinsic or if the response from the blockchain indicates
+ MetadataError: If there is an error in submitting the extrinsic, or if the response from the blockchain indicates
failure.
"""
@@ -606,36 +616,34 @@ Source code for bittensor.core.extrinsics.asyncex.serving
logging.error(unlock.message)
return False
+ fields = [{f"{data_type}": data}]
+ if reset_bonds:
+ fields.append({"ResetBondsFlag": b""})
+
async with subtensor.substrate as substrate:
call = await substrate.compose_call(
call_module="Commitments",
call_function="set_commitment",
call_params={
"netuid": netuid,
- "info": {"fields": [[{f"{data_type}": data}]]},
+ "info": {"fields": [fields]},
},
)
- extrinsic = await substrate.create_signed_extrinsic(
- call=call, keypair=wallet.hotkey
- )
- response = await substrate.submit_extrinsic(
- extrinsic=extrinsic,
+ success, message = await subtensor.sign_and_send_extrinsic(
+ call=call,
+ wallet=wallet,
+ sign_with="hotkey",
wait_for_inclusion=wait_for_inclusion,
wait_for_finalization=wait_for_finalization,
+ period=period,
)
- # We only wait here if we expect finalization.
- if not wait_for_finalization and not wait_for_inclusion:
- return True
- if await response.is_success:
+ if success:
return True
- raise MetadataError(format_error_message(await response.error_message))
-
+ raise MetadataError(message)
-
-[docs]
async def get_metadata(
subtensor: "AsyncSubtensor",
netuid: int,
@@ -643,7 +651,7 @@ Source code for bittensor.core.extrinsics.asyncex.serving
block: Optional[int] = None,
block_hash: Optional[str] = None,
reuse_block: bool = False,
-) -> str:
+) -> Union[str, dict]:
"""Fetches metadata from the blockchain for a given hotkey and netuid."""
async with subtensor.substrate:
block_hash = await subtensor.determine_block_hash(
@@ -656,8 +664,26 @@ Source code for bittensor.core.extrinsics.asyncex.serving
block_hash=block_hash,
reuse_block_hash=reuse_block,
)
- return commit_data
+ return commit_data
+
+async def get_last_bonds_reset(
+ subtensor: "AsyncSubtensor",
+ netuid: int,
+ hotkey: str,
+ block: Optional[int] = None,
+ block_hash: Optional[str] = None,
+ reuse_block: bool = False,
+) -> bytes:
+ """Fetches the last bonds reset triggered at commitment from the blockchain for a given hotkey and netuid."""
+ block_hash = await subtensor.determine_block_hash(block, block_hash, reuse_block)
+ block = await subtensor.substrate.query(
+ module="Commitments",
+ storage_function="LastBondsReset",
+ params=[netuid, hotkey],
+ block_hash=block_hash,
+ )
+ return block
diff --git a/static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/staking.html b/static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/staking.html
index 44717818ee..c01111371d 100644
--- a/static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/staking.html
+++ b/static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/staking.html
@@ -160,25 +160,28 @@
bittensor.core.settings
bittensor.core.stream
bittensor.core.subtensor
-bittensor.core.subtensor_api
bittensor.core.synapse
bittensor.core.tensor
bittensor.core.threadpool
-bittensor.core.timelock
bittensor.core.types
+bittensor.extras
bittensor.utils
- bittensor.utils.axon_utils
- bittensor.utils.balance
- bittensor.utils.btlogging
- bittensor.utils.easy_imports
- bittensor.utils.formatting
-- bittensor.utils.mock
+- bittensor.utils.liquidity
- bittensor.utils.networking
- bittensor.utils.registration
- bittensor.utils.subnets
-- bittensor.utils.substrate_utils
- bittensor.utils.version
- bittensor.utils.weight_utils
@@ -337,11 +340,12 @@ Source code for bittensor.core.extrinsics.asyncex.staking
import asyncio
from typing import Optional, Sequence, TYPE_CHECKING
-from bittensor.core.errors import StakeError, NotRegisteredError
-from bittensor.utils import unlock_key
+from async_substrate_interface.errors import SubstrateRequestException
+
+from bittensor.core.extrinsics.utils import get_old_stakes
+from bittensor.utils import unlock_key, format_error_message
from bittensor.utils.balance import Balance
from bittensor.utils.btlogging import logging
-from bittensor.core.extrinsics.utils import get_old_stakes
if TYPE_CHECKING:
from bittensor_wallet import Wallet
@@ -359,25 +363,40 @@ Source code for bittensor.core.extrinsics.asyncex.staking
amount: Optional[Balance] = None,
wait_for_inclusion: bool = True,
wait_for_finalization: bool = False,
+ safe_staking: bool = False,
+ allow_partial_stake: bool = False,
+ rate_tolerance: float = 0.005,
+ period: Optional[int] = None,
) -> bool:
"""
- Adds the specified amount of stake to passed hotkey `uid`.
+ 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.
Arguments:
- subtensor: the initialized SubtensorInterface object to use
+ subtensor: Subtensor instance with the connection to the chain.
wallet: Bittensor wallet object.
old_balance: the balance prior to the staking
- hotkey_ss58: The `ss58` address of the hotkey account to stake to defaults to the wallet's hotkey.
- netuid: The netuid of the stake to be added
- amount: Amount to stake as Bittensor balance, `None` if staking all.
+ hotkey_ss58: The `ss58` address of the hotkey account to stake to default to the wallet's hotkey. If not
+ specified, the wallet's hotkey will be used. Defaults to ``None``.
+ netuid: The unique identifier of the subnet to which the neuron belongs.
+ amount: Amount to stake as Bittensor balance in TAO always, `None` if staking all. Defaults is ``None``.
wait_for_inclusion: If set, waits for the extrinsic to enter a block before returning `True`, or returns
- `False` if the extrinsic fails to enter the block within the timeout.
+ `False` if the extrinsic fails to enter the block within the timeout. Defaults to ``True``.
wait_for_finalization: If set, waits for the extrinsic to be finalized on the chain before returning `True`,
- or returns `False` if the extrinsic fails to be finalized within the timeout.
+ or returns `False` if the extrinsic fails to be finalized within the timeout. Defaults to ``False``.
+ safe_staking: If True, enables price safety checks. Default is ``False``.
+ allow_partial_stake: If True, allows partial unstaking if price tolerance exceeded. Default is ``False``.
+ rate_tolerance: Maximum allowed price increase percentage (0.005 = 0.5%). Default is ``0.005``.
+ 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.
+ You can think of it as an expiration date for the transaction. Defaults to ``None``.
Returns:
success: Flag is `True` if extrinsic was finalized or included in the block. If we did not wait for
finalization/inclusion, the response is `True`.
+
+ Raises:
+ SubstrateRequestException: Raised if the extrinsic fails to be included in the block within the timeout.
"""
# Decrypt keys,
@@ -417,7 +436,6 @@ Source code for bittensor.core.extrinsics.asyncex.staking
)
else:
staking_balance = amount
- staking_balance.set_unit(netuid)
# Leave existential balance to keep key alive.
if staking_balance > old_balance - existential_deposit:
@@ -435,28 +453,61 @@ Source code for bittensor.core.extrinsics.asyncex.staking
return False
try:
- logging.info(
- f":satellite: [magenta]Staking to:[/magenta] "
- f"[blue]netuid: {netuid}, amount: {staking_balance} "
- f"on {subtensor.network}[/blue] [magenta]...[/magenta]"
- )
+ call_params = {
+ "hotkey": hotkey_ss58,
+ "netuid": netuid,
+ "amount_staked": staking_balance.rao,
+ }
+
+ if safe_staking:
+ pool = await subtensor.subnet(netuid=netuid)
+ base_price = pool.price.tao
+
+ if pool.netuid == 0:
+ price_with_tolerance = base_price
+ else:
+ price_with_tolerance = base_price * (1 + rate_tolerance)
+
+ logging.info(
+ f":satellite: [magenta]Safe Staking to:[/magenta] "
+ f"[blue]netuid: [green]{netuid}[/green], amount: [green]{staking_balance}[/green], "
+ f"tolerance percentage: [green]{rate_tolerance * 100}%[/green], "
+ f"price limit: [green]{price_with_tolerance}[/green], "
+ f"original price: [green]{base_price}[/green], "
+ f"with partial stake: [green]{allow_partial_stake}[/green] "
+ f"on [blue]{subtensor.network}[/blue][/magenta]...[/magenta]"
+ )
+
+ limit_price = Balance.from_tao(price_with_tolerance).rao
+ call_params.update(
+ {
+ "limit_price": limit_price,
+ "allow_partial": allow_partial_stake,
+ }
+ )
+ call_function = "add_stake_limit"
+ else:
+ logging.info(
+ f":satellite: [magenta]Staking to:[/magenta] "
+ f"[blue]netuid: [green]{netuid}[/green], amount: [green]{staking_balance}[/green] "
+ f"on [blue]{subtensor.network}[/blue][magenta]...[/magenta]"
+ )
+ call_function = "add_stake"
+
call = await subtensor.substrate.compose_call(
call_module="SubtensorModule",
- call_function="add_stake",
- call_params={
- "hotkey": hotkey_ss58,
- "amount_staked": staking_balance.rao,
- "netuid": netuid,
- },
+ call_function=call_function,
+ call_params=call_params,
)
staking_response, err_msg = await subtensor.sign_and_send_extrinsic(
- call,
- wallet,
- wait_for_inclusion,
- wait_for_finalization,
+ call=call,
+ wallet=wallet,
+ wait_for_inclusion=wait_for_inclusion,
+ wait_for_finalization=wait_for_finalization,
nonce_key="coldkeypub",
sign_with="coldkey",
use_nonce=True,
+ period=period,
)
if staking_response is True: # If we successfully staked.
# We only wait here if we expect finalization.
@@ -466,8 +517,8 @@ Source code for bittensor.core.extrinsics.asyncex.staking
logging.success(":white_heavy_check_mark: [green]Finalized[/green]")
logging.info(
- f":satellite: [magenta]Checking Balance on:[/magenta] [blue]{subtensor.network}[/blue] "
- "[magenta]...[/magenta]"
+ f":satellite: [magenta]Checking Balance on:[/magenta] "
+ f"[blue]{subtensor.network}[/blue] [magenta]...[/magenta]"
)
new_block_hash = await subtensor.substrate.get_chain_head()
new_balance, new_stake = await asyncio.gather(
@@ -490,18 +541,18 @@ Source code for bittensor.core.extrinsics.asyncex.staking
)
return True
else:
- logging.error(f":cross_mark: [red]Failed: {err_msg}.[/red]")
+ if safe_staking and "Custom error: 8" in err_msg:
+ logging.error(
+ ":cross_mark: [red]Failed[/red]: Price exceeded tolerance limit. Either increase price tolerance or enable partial staking."
+ )
+ else:
+ logging.error(f":cross_mark: [red]Failed: {err_msg}.[/red]")
return False
- except NotRegisteredError:
+ except SubstrateRequestException as error:
logging.error(
- ":cross_mark: [red]Hotkey: {} is not registered.[/red]".format(
- wallet.hotkey_str
- )
+ f":cross_mark: [red]Add Stake Error: {format_error_message(error)}[/red]"
)
- return False
- except StakeError as e:
- logging.error(f":cross_mark: [red]Stake Error: {e}[/red]")
return False
@@ -517,8 +568,9 @@ Source code for bittensor.core.extrinsics.asyncex.staking
amounts: Optional[list[Balance]] = None,
wait_for_inclusion: bool = True,
wait_for_finalization: bool = False,
+ period: Optional[int] = None,
) -> bool:
- """Adds stake to each ``hotkey_ss58`` in the list, using each amount, from a common coldkey.
+ """Adds a stake to each ``hotkey_ss58`` in the list, using each amount, from a common coldkey.
Arguments:
subtensor: The initialized SubtensorInterface object.
@@ -531,6 +583,9 @@ Source code for bittensor.core.extrinsics.asyncex.staking
if the extrinsic fails to enter the block within the timeout.
wait_for_finalization: If set, waits for the extrinsic to be finalized on the chain before returning `True`, or
returns `False` if the extrinsic fails to be finalized within the timeout.
+ 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.
+ You can think of it as an expiration date for the transaction.
Returns:
success: `True` if extrinsic was finalized or included in the block. `True` if any wallet was staked. If we did
@@ -642,33 +697,20 @@ Source code for bittensor.core.extrinsics.asyncex.staking
"netuid": netuid,
},
)
- staking_response, err_msg = await subtensor.sign_and_send_extrinsic(
- call,
- wallet,
- wait_for_inclusion,
- wait_for_finalization,
+ success, message = await subtensor.sign_and_send_extrinsic(
+ call=call,
+ wallet=wallet,
+ wait_for_inclusion=wait_for_inclusion,
+ wait_for_finalization=wait_for_finalization,
nonce_key="coldkeypub",
sign_with="coldkey",
use_nonce=True,
+ period=period,
)
- if staking_response is True: # If we successfully staked.
+ if success is True: # If we successfully staked.
# We only wait here if we expect finalization.
- if idx < len(hotkey_ss58s) - 1:
- # Wait for tx rate limit.
- tx_query = await subtensor.substrate.query(
- module="SubtensorModule", storage_function="TxRateLimit"
- )
- tx_rate_limit_blocks: int = getattr(tx_query, "value", 0)
- if tx_rate_limit_blocks > 0:
- logging.error(
- f":hourglass: [yellow]Waiting for tx rate limit: [white]{tx_rate_limit_blocks}[/white] "
- f"blocks[/yellow]"
- )
- # 12 seconds per block
- await asyncio.sleep(tx_rate_limit_blocks * 12)
-
if not wait_for_finalization and not wait_for_inclusion:
old_balance -= staking_balance
successful_stakes += 1
@@ -706,17 +748,14 @@ Source code for bittensor.core.extrinsics.asyncex.staking
break
else:
- logging.error(f":cross_mark: [red]Failed: {err_msg}.[/red]")
+ logging.error(f":cross_mark: [red]Failed: {message}.[/red]")
continue
- except NotRegisteredError:
+ except SubstrateRequestException as error:
logging.error(
- f":cross_mark: [red]Hotkey: {hotkey_ss58} is not registered.[/red]"
+ f":cross_mark: [red]Add Stake Multiple error: {format_error_message(error)}[/red]"
)
continue
- except StakeError as e:
- logging.error(f":cross_mark: [red]Stake Error: {e}[/red]")
- continue
if successful_stakes != 0:
logging.info(
diff --git a/static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/start_call.html b/static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/start_call.html
new file mode 100644
index 0000000000..8a0398b7e0
--- /dev/null
+++ b/static/python-api/html/_modules/bittensor/core/extrinsics/asyncex/start_call.html
@@ -0,0 +1,474 @@
+
+
+
+
+
+
+
+
+
+ bittensor.core.extrinsics.asyncex.start_call — Bittensor SDK Docs documentation
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+