Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion bittensor/core/async_subtensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@
get_fees,
price_to_tick,
tick_to_price,
Position,
)

if TYPE_CHECKING:
Expand Down Expand Up @@ -3005,8 +3006,10 @@ async def get_liquidity_list(
current_tick = price_to_tick(sqrt_price**2)

# Fetch positions
positions_values: list[tuple[dict, int, int]] = []
positions_values: list[tuple[Position, int, int]] = []
positions_storage_keys: list[StorageKey] = []
position: Position

async for _, p in positions_response:
position = p.value

Expand Down
26 changes: 12 additions & 14 deletions bittensor/core/subtensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@
get_fees,
price_to_tick,
tick_to_price,
Position,
)

if TYPE_CHECKING:
Expand Down Expand Up @@ -2427,8 +2428,9 @@ def get_liquidity_list(
sqrt_price = fixed_to_float(sqrt_price_query[1])
current_tick = price_to_tick(sqrt_price**2)

positions_values: list[tuple[dict, int, int]] = []
positions_values: list[tuple[Position, int, int]] = []
positions_storage_keys: list[StorageKey] = []
position: Position
for _, p in positions_response:
position = p.value

Expand Down Expand Up @@ -2512,19 +2514,15 @@ def get_liquidity_list(

positions.append(
LiquidityPosition(
**{
"id": position.get("id")[0],
"price_low": Balance.from_tao(
tick_to_price(position.get("tick_low")[0])
),
"price_high": Balance.from_tao(
tick_to_price(position.get("tick_high")[0])
),
"liquidity": Balance.from_rao(position.get("liquidity")),
"fees_tao": fees_tao,
"fees_alpha": fees_alpha,
"netuid": position.get("netuid"),
}
id=position["id"][0],
price_low=Balance.from_tao(tick_to_price(position["tick_low"][0])),
price_high=Balance.from_tao(
tick_to_price(position["tick_high"][0])
),
liquidity=Balance.from_rao(position["liquidity"]),
fees_tao=fees_tao,
fees_alpha=fees_alpha,
netuid=position["netuid"],
)
)

Expand Down
40 changes: 37 additions & 3 deletions bittensor/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,14 @@ def decode_hex_identity_dict(info_dictionary: dict[str, Any]) -> dict[str, Any]:


def ss58_to_vec_u8(ss58_address: str) -> list[int]:
"""Convert an SS58-encoded address to a list of unsigned 8-bit integers.

Args:
ss58_address: The SS58-encoded Substrate address string.

Returns:
A list of integers representing the raw bytes of the decoded address.
"""
ss58_bytes: bytes = ss58_address_to_bytes(ss58_address)
encoded_address: list[int] = [int(byte) for byte in ss58_bytes]
return encoded_address
Expand Down Expand Up @@ -209,10 +217,26 @@ def ss58_address_to_bytes(ss58_address: str) -> bytes:


def u16_normalized_float(x: int) -> float:
"""Normalize an unsigned 16-bit integer to a float in the range [0, 1].

Args:
x: An integer in the range [0, 65535].

Returns:
The normalized float value (x / 65535).
"""
return float(x) / float(U16_MAX)


def u64_normalized_float(x: int) -> float:
"""Normalize an unsigned 64-bit integer to a float in the range [0, 1].

Args:
x: An integer in the range [0, 2^64 - 1].

Returns:
The normalized float value (x / (2^64 - 1)).
"""
return float(x) / float(U64_MAX)


Expand All @@ -228,6 +252,16 @@ def float_to_u64(value: float) -> int:


def get_hash(content, encoding="utf-8"):
"""Compute the SHA-256 hash of the given content.

Args:
content: The input data to hash. Can be bytes or a string.
encoding: The character encoding to use when the content is a string.
Defaults to `"utf-8"`.

Returns:
The hex-encoded SHA-256 digest string.
"""
sha3 = hashlib.sha3_256()

# Update the hash object with the concatenated string
Expand Down Expand Up @@ -461,11 +495,11 @@ def determine_chain_endpoint_and_network(
"""Determines the chain endpoint and network from the passed network or chain_endpoint.

Parameters:
network: The network flag. The choices are: ``finney`` (main network), ``archive`` (archive network +300 blocks),
``local`` (local running network), ``test`` (test network).
network: The network flag. The choices are: `finney` (main network), `archive` (archive network +300 blocks),
`local` (local running network), `test` (test network).

Returns:
The network and chain endpoint flag. If passed, overrides the ``network`` argument.
The network and chain endpoint flag. If passed, overrides the `network` argument.
"""

if network is None:
Expand Down
1 change: 1 addition & 0 deletions bittensor/utils/balance.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from typing import Optional, TypedDict, Union

from async_substrate_interface.types import ScaleObj
from scalecodec import ScaleType
from async_substrate_interface.types import ScaleObj

Expand Down
38 changes: 34 additions & 4 deletions bittensor/utils/liquidity.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@
"""

import math
from typing import Any
from typing import TypedDict
from dataclasses import dataclass

from async_substrate_interface.types import ScaleObj

from bittensor.utils.balance import Balance, fixed_to_float, FixedPoint
from bittensor.utils import ChainFeatureDisabledWarning, deprecated_message
from bittensor.utils.balance import Balance, fixed_to_float

# These three constants are unchangeable at the level of Uniswap math
MIN_TICK = -887272
Expand Down Expand Up @@ -70,6 +72,16 @@ def to_token_amounts(
)


class Position(TypedDict, total=True):
liquidity: int
fees_tao: FixedPoint | ScaleObj
fees_alpha: FixedPoint | ScaleObj
id: tuple[int,]
tick_low: tuple[int,]
tick_high: tuple[int,]
netuid: int


def price_to_tick(price: float) -> int:
"""Converts a float price to the nearest Uniswap V3 tick index."""
deprecated_message(
Expand Down Expand Up @@ -155,7 +167,7 @@ def get_fees_in_range(


def calculate_fees(
position: dict[str, Any],
position: Position,
global_fees_tao: float,
global_fees_alpha: float,
tao_fees_below_low: float,
Expand All @@ -164,7 +176,25 @@ def calculate_fees(
alpha_fees_above_high: float,
netuid: int,
) -> tuple[Balance, Balance]:
"""Calculate fees for a position."""
"""Calculate the accrued TAO and Alpha fees for a liquidity position.

Computes the net fees earned by a position by aggregating global fee
accumulators and subtracting out-of-range portions, then scaling by
the position's liquidity share.

Args:
position: A dictionary describing the liquidity position.
global_fees_tao: The global TAO fee accumulator value.
global_fees_alpha: The global Alpha fee accumulator value.
tao_fees_below_low: TAO fees accumulated below the position's lower tick.
tao_fees_above_high: TAO fees accumulated above the position's upper tick.
alpha_fees_below_low: Alpha fees accumulated below the position's lower tick.
alpha_fees_above_high: Alpha fees accumulated above the position's upper tick.
netuid: The subnet identifier used for Balance unit tagging.

Returns:
A tuple of `(tao_fees, alpha_fees)` as `Balance` instances.
"""
deprecated_message(
message="calculate_fees() is deprecated. The chain has migrated from Uniswap V3 "
"to PalSwap which uses a different fee calculation mechanism.",
Expand Down
1 change: 0 additions & 1 deletion tests/unit_tests/test_async_subtensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -3874,7 +3874,6 @@ async def fake_current_sqrt_prices():
assert result == expected_prices



@pytest.mark.asyncio
async def test_all_subnets(subtensor, mocker):
"""Verify that `all_subnets` calls proper methods and returns the correct value."""
Expand Down
2 changes: 0 additions & 2 deletions tests/unit_tests/test_subtensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -4151,8 +4151,6 @@ def test_get_subnet_prices(subtensor, mocker):
assert result == expected_prices




def test_all_subnets(subtensor, mocker):
"""Verify that `all_subnets` calls proper methods and returns the correct value."""
# Preps
Expand Down
3 changes: 2 additions & 1 deletion tests/unit_tests/utils/test_liquidity_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
get_fees,
get_fees_in_range,
calculate_fees,
Position,
)


Expand Down Expand Up @@ -97,7 +98,7 @@ def test_get_fees_in_range():
def test_calculate_fees():
"""Test calculation of fees for a position."""
# Preps
position = {
position: Position = {
"id": (2,),
"netuid": 2,
"tick_low": (206189,),
Expand Down