Skip to content
Merged
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
53 changes: 51 additions & 2 deletions src/tusdt_cli/commands/lending.py
Original file line number Diff line number Diff line change
Expand Up @@ -915,13 +915,62 @@ def accrue_market_interest(ctx: click.Context, wallet_name: str | None, network:
@network_option
@click.pass_context
def market_state(ctx: click.Context, market_id: int, network: str | None) -> None:
"""Show market state (supply, debt, rates, reserve)."""
"""Show market state (supply, debt, rates, reserve).

MarketState tracks supply in lToken units, so alongside the raw lToken
count the command shows the face (underlying) supply it represents at
the current exchange rate — raw lTAO counts are never presented as TAO.
"""
state: CLIContext = ctx.obj
state.network = network or state.network
cfg = state.make_config()
kp = get_reader_keypair(cfg)
result = state.run_read(lambda c: c.lending_get_market_state(kp, market_id))
state.output.detail("Market State", {"Result": result})
state.output.detail("Market State", _market_state_details(result, market_id))


def _market_state_details(result: Any, market_id: int) -> dict[str, Any]:
"""Curate a decoded MarketState for display, adding face-scaled supply.

``MarketState.total_supplied`` is denominated in lToken (scaled) units —
the face value owed to suppliers is ``total_supplied × exchange_rate``
(see the contract's MarketState docs). The raw dict passes through
key-for-key except the supply/rate fields, which are re-emitted with
explicit unit labels, and a derived face row is added so a raw lTAO
count is never mistaken for plain TAO.
"""
if not isinstance(result, dict):
# Unexpected payload shape (not a decoded struct) — keep it raw.
return {"Result": result}
if market_id == 0:
asset, ltoken = "TAO", "lTAO"
elif market_id == 1:
asset, ltoken = "TUSDT", "lTUSDT"
else:
asset, ltoken = "underlying", "lToken"
total_supplied = _dict_field(result, "total_supplied", "totalSupplied")
exchange_rate_inner = _dict_field(result, "exchange_rate", "exchangeRate")
has_supply = isinstance(total_supplied, int)
has_rate = isinstance(exchange_rate_inner, int) and exchange_rate_inner > 0

details: dict[str, Any] = {"market": f"{market_id} ({asset})"}
for key, value in result.items():
# The supply/rate fields are re-emitted below with explicit units.
if key.replace("_", "").lower() in ("totalsupplied", "exchangerate"):
continue
details[key] = value
if has_supply:
details[f"total_supplied ({ltoken}, raw)"] = total_supplied
details[f"total_supplied ({ltoken})"] = format_balance(total_supplied)
if has_supply and has_rate:
face = lending_interest.face_from_ltao(total_supplied, exchange_rate_inner)
details[f"total supplied (face {asset})"] = format_balance(face)
details[f"total supplied (face {asset}, raw)"] = face
details["exchange_rate (1e18 inner)"] = exchange_rate_inner
details[f"exchange_rate ({asset} per {ltoken})"] = format_balance(exchange_rate_inner, 18)
elif has_supply:
details[f"total supplied (face {asset})"] = "n/a (no exchange rate in state)"
return details


@lending_group.command("market-deficit")
Expand Down
10 changes: 10 additions & 0 deletions src/tusdt_cli/lending_interest.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,16 @@ def derive_cash(
return max(cash, 0)


def face_from_ltao(ltoken_amount: int, exchange_rate_inner: int) -> int:
"""Face (underlying) value of an lToken balance — ``floor(ltoken × ER / 1e18)``.

The contract redeems ``ltoken_amount`` for exactly this many underlying
rao (its ``compute_redeem_amount`` floors at 1e18), so this is the TAO /
TUSDT a user actually receives when burning ``ltoken_amount`` lTokens.
"""
return ltoken_amount * exchange_rate_inner // RATIO_SCALE


def pow_fixed(base_inner: int, exp: int) -> int:
"""Fixed-point integer power, flooring at ``RATIO_SCALE`` every step.

Expand Down
20 changes: 20 additions & 0 deletions tests/unit/test_lending_interest.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,33 @@
bps_to_ratio_inner,
compute_borrow_rate,
derive_cash,
face_from_ltao,
pow_fixed,
project_debt,
)

# Live pool exchange-rate inner observed on-chain (pinned, not approximate):
# 1 lTAO ≈ 1.002816870398849427 TAO. All math below is exact integer
# arithmetic at 1e18 scale.
ER_INNER = 1_002_816_870_398_849_427

PARAMS = {"base": 0, "slope1": 0, "slope2": 0, "optimal": 8 * 10**17}


class TestFaceFromLtao:
def test_par_rate_face_equals_ltoken(self):
# ER 1.0: supply of 2_000_000_000 rao mints 2_000_000_000 lTAO.
assert face_from_ltao(2_000_000_000, RATIO_SCALE) == 2_000_000_000

def test_live_rate_pin_redeems_999999999(self):
# Real-chain pin: burning 997_191_042 lTAO at the live rate redeems
# 999_999_999 rao (~1.0 TAO) — NOT 997_191_042 rao (0.9972 TAO).
assert face_from_ltao(997_191_042, ER_INNER) == 999_999_999

def test_zero_ltoken(self):
assert face_from_ltao(0, ER_INNER) == 0


class TestBpsToRatioInner:
def test_one_hundred_percent(self):
assert bps_to_ratio_inner(10_000) == RATIO_SCALE
Expand Down
103 changes: 103 additions & 0 deletions tests/unit/test_lending_market_state.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
"""Unit tests for the market-state display helper (lTAO → face TAO scaling).

Pins the real-chain incident: total_supplied 997_191_042 lTAO at exchange
rate 1_002_816_870_398_849_427 must be shown as 999_999_999 rao face
(~1.0 TAO), never as the raw lTAO count.
"""

from __future__ import annotations

from unittest.mock import patch

import pytest
from click.testing import CliRunner

from tusdt_cli.cli import cli
from tusdt_cli.commands.lending import _market_state_details
from tusdt_cli.context import CLIContext

ER_INNER = 1_002_816_870_398_849_427


@pytest.fixture
def runner() -> CliRunner:
return CliRunner()


class TestMarketStateDetails:
def test_live_rate_scales_total_supplied_to_face(self):
details = _market_state_details(
{"total_supplied": 997_191_042, "exchange_rate": ER_INNER, "total_debt": 0},
0,
)
assert details["market"] == "0 (TAO)"
assert details["total_supplied (lTAO, raw)"] == 997_191_042
assert details["total_supplied (lTAO)"] == "0.997191042"
# The fix: face supply is ~1.0 TAO, not 0.9972 TAO (the raw lTAO).
assert details["total supplied (face TAO)"] == "0.999999999"
assert details["total supplied (face TAO, raw)"] == 999_999_999
# Unrelated fields pass through untouched; raw lTAO/rate keys are not
# re-emitted under their bare names.
assert details["total_debt"] == 0
assert "total_supplied" not in details
assert "exchange_rate" not in details
assert details["exchange_rate (1e18 inner)"] == ER_INNER
assert details["exchange_rate (TAO per lTAO)"] == "1.002816870398849427"

def test_tusdt_market_uses_tusdt_labels(self):
details = _market_state_details(
{"total_supplied": 997_191_042, "exchange_rate": ER_INNER},
1,
)
assert details["market"] == "1 (TUSDT)"
assert details["total_supplied (lTUSDT, raw)"] == 997_191_042
assert details["total supplied (face TUSDT)"] == "0.999999999"

def test_par_rate_face_row_equals_raw(self):
details = _market_state_details({"total_supplied": 2_000_000_000, "exchange_rate": 10**18}, 0)
assert details["total supplied (face TAO)"] == "2"
assert details["total supplied (face TAO, raw)"] == 2_000_000_000

def test_missing_exchange_rate_marks_face_unavailable(self):
details = _market_state_details({"total_supplied": 997_191_042}, 0)
assert details["total supplied (face TAO)"] == "n/a (no exchange rate in state)"

def test_unknown_market_id_uses_generic_labels(self):
details = _market_state_details(
{"total_supplied": 997_191_042, "exchange_rate": ER_INNER},
7,
)
assert details["market"] == "7 (underlying)"
assert details["total_supplied (lToken, raw)"] == 997_191_042
assert details["total supplied (face underlying)"] == "0.999999999"

def test_non_dict_payload_passes_through_raw(self):
assert _market_state_details(["not", "a", "dict"], 0) == {"Result": ["not", "a", "dict"]}

def test_camel_case_aliases_are_normalised_away(self):
# _dict_field tolerates camelCase aliases from drifted ABIs.
details = _market_state_details(
{"totalSupplied": 997_191_042, "exchangeRate": ER_INNER, "totalDebt": 0},
0,
)
assert details["total_supplied (lTAO, raw)"] == 997_191_042
assert details["total supplied (face TAO)"] == "0.999999999"
assert "totalSupplied" not in details
assert "exchangeRate" not in details


class TestMarketStateCommand:
@patch.object(CLIContext, "run_read")
@patch("tusdt_cli.context.load_config")
def test_command_renders_face_row(self, mock_load, mock_run_read, runner):
mock_load.return_value = {
"decimals": 9,
"network": "finney",
"rpc": "ws://127.0.0.1:9944",
"lending_address": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY",
}
mock_run_read.return_value = {"total_supplied": 997_191_042, "exchange_rate": ER_INNER}
result = runner.invoke(cli, ["lending", "market-state", "--market-id", "0"])
assert result.exit_code == 0
assert "total supplied (face TAO)" in result.output
assert "0.999999999" in result.output
Loading