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
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,16 @@ All notable changes to `citrate-labs-sdk` are documented here. This project adhe

## [Unreleased]

### Changed

- `TreasuryManager.get_credit_price_usd` fails closed on a stale or unset oracle price (X21, oracle
v2 ADR fed#745 consumer C9). `BulkComputeGateway.currentCreditPriceUsd()` has no staleness
check, so the manager first reads the gateway's `oracle()`, its `lastComputeUpdateBlock()` and
that block's timestamp, and raises the new `PriceUnavailableError` (no price read) when the
compute price was never set by a committee round, is more than `oracle_staleness_seconds` old
(new keyword, default `DEFAULT_ORACLE_STALENESS_SECONDS` = 900; a time bound, not a block
count), or its freshness cannot be read. A 0 or negative bound is refused at construction.

## [0.9.0] - 2026-11-12: the r1007 network

Breaking (0.x minor): the vendored address book and the genesis check move from r1006 to r1007
Expand Down
8 changes: 7 additions & 1 deletion citrate_sdk/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,12 @@
# COMPUTE-4: Compute marketplace manager
from .compute import ComputeManager
from .crypto import EncryptionConfig, KeyManager
from .errors import CitrateError, InsufficientFundsError, ModelNotFoundError
from .errors import (
CitrateError,
InsufficientFundsError,
ModelNotFoundError,
PriceUnavailableError,
)
from .farming import FarmingManager

# LC.5.3: Learning / Staking / Classroom managers
Expand Down Expand Up @@ -84,6 +89,7 @@
"CitrateError",
"ModelNotFoundError",
"InsufficientFundsError",
"PriceUnavailableError",
# LC.5.3: Learning managers
"LearningManager",
"StakingManager",
Expand Down
7 changes: 7 additions & 0 deletions citrate_sdk/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,13 @@ class TimeoutError(CitrateError):
pass


class PriceUnavailableError(CitrateError):
"""An oracle price is stale, was never set, or its freshness cannot be read.

No price is returned; show "price unavailable", never a cached price (X21).
"""


class ConfigurationError(CitrateError):
"""SDK configuration error"""
pass
Expand Down
75 changes: 74 additions & 1 deletion citrate_sdk/treasury.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

from __future__ import annotations

import time
from typing import Any, cast

from ._chain_guard import (
Expand All @@ -28,7 +29,7 @@
resolve_expected_genesis,
)
from .abi import AbiInterface
from .errors import ConfigurationError
from .errors import ConfigurationError, PriceUnavailableError

# ============================================================================
# Contract ABIs (minimal -- only the methods we call)
Expand Down Expand Up @@ -56,8 +57,18 @@
"function totalCreditsSpent() view returns (uint256)",
"function purchaseCount() view returns (uint256)",
"function currentCreditPriceUsd() view returns (uint256 priceUsd6)",
"function oracle() view returns (address)",
]

# X21: the v1 ComputePricingOracle views the credit price freshness check reads.
COMPUTE_PRICING_ORACLE_ABI = [
"function lastComputeUpdateBlock() view returns (uint256)",
]

# X21 / oracle v2 ADR (fed#745) section 5: the staleness bound every oracle
# consumer uses, in seconds (owner, 2026-11-30). A time bound, not a block count.
DEFAULT_ORACLE_STALENESS_SECONDS = 900


# ============================================================================
# TreasuryManager
Expand All @@ -81,7 +92,18 @@ def __init__(
*,
chain_id: int | None = None,
expected_genesis_hash: Any = UNSET,
oracle_staleness_seconds: int = DEFAULT_ORACLE_STALENESS_SECONDS,
) -> None:
if (
isinstance(oracle_staleness_seconds, bool)
or not isinstance(oracle_staleness_seconds, int)
or oracle_staleness_seconds <= 0
):
raise ConfigurationError(
"oracle_staleness_seconds must be a positive integer number of seconds, "
f"got {oracle_staleness_seconds!r}"
)
self._oracle_staleness_seconds = oracle_staleness_seconds
self._rpc_call = rpc_call
# PBA-L6b-042: writes assert eth_chainId against this before sending.
self._expected_chain_id = expected_chain_id(chain_id)
Expand All @@ -98,6 +120,7 @@ def __init__(

self._treasury_iface = AbiInterface(STABLECOIN_TREASURY_ABI)
self._gateway_iface = AbiInterface(BULK_COMPUTE_GATEWAY_ABI)
self._oracle_iface = AbiInterface(COMPUTE_PRICING_ORACLE_ABI)

# --- Internal helpers ---

Expand All @@ -119,6 +142,46 @@ def _eth_call(self, to: str, data: str) -> str:
result = self._rpc_call("eth_call", [{"to": to, "data": data}, "latest"])
return cast(str, result)

def _require_fresh_compute_price(self, gateway: str) -> None:
"""X21: refuse unless the compute price the gateway reads is fresh.

Data source: ``BulkComputeGateway.oracle()``, then
``ComputePricingOracle.lastComputeUpdateBlock()`` via eth_call, then that
block's timestamp via ``eth_getBlockByNumber``. The compute track only
(``currentCreditPriceUsd`` reads ``computePriceUsdCents``), never the
shared ``lastUpdateBlock``, and in seconds on this machine's clock, never
v1's block-counted ``isPriceStale()``.
"""

def unavailable(why: str) -> PriceUnavailableError:
return PriceUnavailableError(f"oracle price unavailable: {why}")

try:
data = self._gateway_iface.encode_function_data("oracle")
(oracle,) = self._gateway_iface.decode_function_result(
"oracle", self._eth_call(gateway, data)
)
data = self._oracle_iface.encode_function_data("lastComputeUpdateBlock")
(block,) = self._oracle_iface.decode_function_result(
"lastComputeUpdateBlock", self._eth_call(str(oracle), data)
)
except Exception as exc: # any read failure fails closed
raise unavailable(f"cannot read the oracle update block ({exc})") from exc
if int(block) == 0:
raise unavailable("the compute price was never set by a committee round")
try:
header = self._rpc_call("eth_getBlockByNumber", [hex(int(block)), False])
updated_at = int(header["timestamp"], 16)
except Exception as exc:
raise unavailable(f"cannot read the timestamp of block {int(block)} ({exc})") from exc
now = int(time.time())
bound = self._oracle_staleness_seconds
if updated_at > now + bound:
raise unavailable(f"update time {updated_at} is more than {bound}s ahead of this clock")
age = max(0, now - updated_at)
if age > bound:
raise unavailable(f"last update {age}s ago exceeds the {bound}s bound")

def _send_transaction(self, to: str, data: str, value: str = "0x0") -> str:
if not self._default_account:
raise ConfigurationError("defaultAccount not configured; required for write operations.")
Expand Down Expand Up @@ -321,10 +384,20 @@ def get_credit_price_usd(self) -> int:

Data source: BulkComputeGateway.currentCreditPriceUsd() via eth_call.

X21: that view does not check staleness, so this method first checks the
compute track of the gateway's oracle (see ``_require_fresh_compute_price``)
and returns no price when it is stale or unset.

Returns:
Price in 6-decimal USD (e.g., 130_000 = $0.13).

Raises:
PriceUnavailableError: the oracle's compute price was never set, was
last updated more than ``oracle_staleness_seconds`` ago, or its
freshness cannot be read.
"""
addr = self._require_gateway_address()
self._require_fresh_compute_price(addr)
data = self._gateway_iface.encode_function_data("currentCreditPriceUsd")
result = self._eth_call(addr, data)
(price,) = self._gateway_iface.decode_function_result("currentCreditPriceUsd", result)
Expand Down
14 changes: 13 additions & 1 deletion tests/test_treasury.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
- Raises ConfigurationError when contract addresses are missing
"""

import time
from unittest.mock import MagicMock

import pytest
Expand Down Expand Up @@ -269,10 +270,21 @@ def test_get_total_distributed_decode(self):
def test_get_credit_price_usd_decode(self):
"""get_credit_price_usd properly decodes uint256 result."""
# 13 cents = 130_000 in 6 decimals
rpc = MagicMock(return_value=_encode_uint256(130_000))
# X21: every eth_call answers the same word, so the oracle's compute
# track was last updated at block 130_000; that block is mined now.
now = int(time.time())

def rpc_answer(method, params):
if method == "eth_getBlockByNumber":
return {"number": params[0], "timestamp": hex(now)}
return _encode_uint256(130_000)

rpc = MagicMock(side_effect=rpc_answer)
mgr = self._make_manager(rpc)
price = mgr.get_credit_price_usd()
assert price == 130_000
# The price read comes last, after the freshness reads.
assert rpc.call_args_list[-1].args[1][0]["data"][2:10] == keccak256(b"currentCreditPriceUsd()")[:4].hex()


# ---------------------------------------------------------------------------
Expand Down
119 changes: 119 additions & 0 deletions tests/test_treasury_stale_price.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
"""X21 / oracle v2 ADR (fed#745) section 5, consumer C9: the credit price read
fails closed on a stale or unset oracle price.

``BulkComputeGateway.currentCreditPriceUsd()`` returns
``oracle.computePriceUsdCents() * 10_000`` with no staleness check (ADR
section 5 v1 finding, consumer C5). ``get_credit_price_usd`` must therefore
check the compute track of the gateway's oracle itself: refuse when no
committee round ever set it (``lastComputeUpdateBlock() == 0``) and when its
block is older than the staleness bound (default 900 s, owner 2026-11-30; a
time bound, never v1's block-counted ``isPriceStale()``).
"""

from __future__ import annotations

import time
from typing import Any

import pytest

from citrate_sdk.abi import keccak256
from citrate_sdk.errors import CitrateError, PriceUnavailableError
from citrate_sdk.treasury import TreasuryManager

GATEWAY = "0x" + "bb" * 20
ORACLE = "0x" + "dd" * 20
UPDATE_BLOCK = 1_000
PRICE_USD6 = 130_000


def _sel(sig: str) -> str:
return keccak256(sig.encode())[:4].hex()


def _word(v: int) -> str:
return "0x" + v.to_bytes(32, "big").hex()


class FakeChain:
"""Answers the gateway, oracle and block reads; counts price reads."""

def __init__(
self,
age: int | None = 30,
update_block: int | None = UPDATE_BLOCK,
) -> None:
self.update_block = update_block # None: the view reverts
self.timestamp = None if age is None else int(time.time()) - age
self.price_reads = 0

def __call__(self, method: str, params: list[Any]) -> Any:
if method == "eth_call":
to = params[0]["to"].lower()
sel = params[0]["data"][2:10]
if to == GATEWAY and sel == _sel("oracle()"):
return "0x" + "00" * 12 + ORACLE[2:]
if to == GATEWAY and sel == _sel("currentCreditPriceUsd()"):
self.price_reads += 1
return _word(PRICE_USD6)
if to == ORACLE and sel == _sel("lastComputeUpdateBlock()"):
if self.update_block is None:
raise RuntimeError("execution reverted")
return _word(self.update_block)
raise RuntimeError(f"unexpected eth_call {to} {sel}")
if method == "eth_getBlockByNumber":
if self.timestamp is None or int(params[0], 16) != UPDATE_BLOCK:
return None
return {"number": params[0], "timestamp": hex(self.timestamp)}
raise RuntimeError(f"unexpected rpc {method}")


def _mgr(chain: FakeChain, **kw: Any) -> TreasuryManager:
return TreasuryManager(
rpc_call=chain,
contract_addresses={"bulkComputeGateway": GATEWAY},
**kw,
)


def _refused(chain: FakeChain, **kw: Any) -> None:
with pytest.raises(CitrateError, match="price unavailable"):
_mgr(chain, **kw).get_credit_price_usd()
assert chain.price_reads == 0, "the price must not be read"


def test_refusal_is_a_price_unavailable_error() -> None:
chain = FakeChain(age=2_000)
with pytest.raises(PriceUnavailableError):
_mgr(chain).get_credit_price_usd()


def test_fresh_price_is_returned() -> None:
chain = FakeChain(age=60)
assert _mgr(chain).get_credit_price_usd() == PRICE_USD6
assert chain.price_reads == 1


def test_stale_compute_track_refuses() -> None:
_refused(FakeChain(age=2_000))


def test_unset_compute_track_refuses() -> None:
_refused(FakeChain(update_block=0))


def test_unreadable_freshness_refuses() -> None:
_refused(FakeChain(update_block=None))
_refused(FakeChain(age=None))


def test_default_bound_is_900_and_configured_bound_is_used() -> None:
_refused(FakeChain(age=1_000))
assert _mgr(FakeChain(age=1_000), oracle_staleness_seconds=1_200).get_credit_price_usd() == PRICE_USD6
_refused(FakeChain(age=200), oracle_staleness_seconds=120)


@pytest.mark.parametrize("bad", [0, -5])
def test_non_positive_bound_is_refused(bad: int) -> None:
with pytest.raises(CitrateError, match="oracle_staleness_seconds"):
_mgr(FakeChain(), oracle_staleness_seconds=bad)
Loading