diff --git a/CLAUDE.md b/CLAUDE.md index 2077d77..2c7d7b0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -69,7 +69,7 @@ Unit tests in `tests/unit/` have no external dependencies. Integration tests in - **Async test** (`@pytest.mark.asyncio`): use `AsyncMock` for async dependencies; await the coroutine under test. - Pattern used in this repo: `patch.object(manager, "connect")` to block sync entrypoints that internally schedule `_run()`. Alternatively, patch `loop.create_task` with a side effect that calls `coro.close()` before returning a `MagicMock`. -- `VERSION` file at repo root holds the current version (currently 0.4.0) +- `VERSION` file at repo root holds the current version (currently 0.6.2) - `.env` files: never commit; use `env.example` as template - **`env.example` must be updated** whenever a new `DexalotConfig` field or env var is added — it is the canonical reference for operators - The error sanitizer strips file paths, URLs, and stack traces from user-facing errors. Use `log_level="DEBUG"` locally to get full context for debugging. @@ -108,6 +108,9 @@ Unit tests in `tests/unit/` have no external dependencies. Integration tests in - **RFQ swaps execute on `tx.to` / `order.maker`, never on the deployments `MainnetRFQ` address**: mainnet firm quotes are signed by one of several maker contracts (legacy MainnetRFQ 1.2.8 plus DexalotRFQ 2.x instances, each with its own `swapSigner` and EIP-712 domain) sitting behind `DexalotRouter` (`MainnetRFQ.trustedForwarder()`), whose fallback forwards `simpleSwap` calldata to `order.maker` with the sender appended. The deployments endpoint only lists the legacy address, so sending a quote there fails `RF-IS-01` whenever another maker won the quote. `execute_rfq_swap` resolves the target via `_resolve_rfq_execution_target`: `order.maker` must be in `router.getAllowedRFQs()` (discovered by `_get_rfq_targets`: router from the deployments endpoint's `DexalotRouter` entry, loaded best-effort by `_fetch_optional_contract_deployment`, else `MainnetRFQ.trustedForwarder()` on-chain; makers always on-chain since the API does not list them; cached in the static tier, lookup failures degrade to deployment-only and are not cached), `tx.to` must be the router or the maker, and `tx.data`/`tx.value` (when present) must equal the SDK's own encoding. The SDK always encodes `simpleSwap` itself from the embedded `_SIMPLE_SWAP_ABI`. `MainnetRFQ`/`DexalotRouter` deployments are keyed by the connected chain's `chain_config` name (`"Avalanche"` on mainnet, `"Fuji"` on testnet, via `_connected_chain_key`), which is what `_get_rfq_contract` looks up; before this, Fuji RFQ lookups always missed. - **ERC20 RFQ sells need an allowance on `order.maker`**: the maker contract does `transferFrom(taker)` itself, so approving the router or the legacy address does nothing. `execute_rfq_swap` pre-checks `allowance(taker, maker)` and fails with an actionable message; `approve_rfq_maker(quote)` grants exactly `takerAmount` (or `amount_wei`) after validating the maker against the allow-list. Native sells carry the amount as `msg.value` and skip both. - **`replace_order` cannot change order type/TIF/stp**: `cancelReplaceOrder` carries only a new price and quantity, so the replacement inherits the original `type1`/`type2`/`stp`. To change those, cancel and re-place (e.g. `cancel_add_list`). The method intentionally exposes no `time_in_force`/`stp` params. +- **Wallet-balance entries never carry a string sentinel in `balance`**: `balance` is a numeric string on success or `None` on failure, and a failed entry carries an `error` key (built by `TransferClient._balance_error_entry`). `get_chain_wallet_balance` turns any error entry into `Result.fail` via `_balance_entry_result`. The plural methods (`get_chain_wallet_balances`, `get_all_chain_wallet_balances`) route entries through `_collect_balance_entries`, which drops failed entries from `chain_balances` and appends `" : "` to an additive `errors` list; `_balances_result` returns `Result.fail` only when every lookup failed. `_fetch_erc20_balances_list` emits error entries for failed tokens instead of silently dropping them. Before v0.6.2 an RPC 500 produced `Result.ok({"balance": "Error: ..."})`, which was cached for 10 s and made consumers' `Decimal(balance)` raise `ConversionSyntax`. +- **Failed `Result`s are never cached**: `ttl_cached` / `async_ttl_cached` skip `cache.set` when the return value is a `Result` with `success=False` (`_is_cacheable` in `utils/cache.py`), in all four tiers. Stampede waiters still receive the failed Result; the next caller retries. Tests that previously relied on a cached failure being "instant" (e.g. `test_get_deployment_uses_cache`) had to be rewritten to exercise a real success. Clear the relevant tier at the start of a test that asserts on a first-call failure, since a prior test may have cached a success for the same key. +- **`_sanitize_error` takes a `level` keyword**: default `logging.ERROR` with `exc_info` attached (unchanged for all existing call sites). Tolerated failures (per-token balance lookups) pass `level=logging.WARNING`, and below ERROR the traceback is omitted so a transient RPC blip is one WARNING line, not a stack trace. --- @@ -140,7 +143,8 @@ publishing (OIDC, `id-token: write`). The workflow also supports of-`origin/main` and `ref_type == tag` checks, plus `--provenance`). Consider porting those for defense-in-depth on the Python side. - Released versions so far: `v0.5.12` (first public release, - 2026-04-06). + 2026-04-06) through `v0.6.1`; `v0.6.2` (2026-09, balance-lookup + Result semantics + no caching of failed Results). --- diff --git a/README.md b/README.md index c69e07a..b7355ed 100644 --- a/README.md +++ b/README.md @@ -341,6 +341,8 @@ client.invalidate_cache(level="balance") # Options: static, semi_static, balanc **Note:** Write operations (e.g., `add_order()`, `cancel_order()`, `deposit()`, `withdraw()`) are **never cached** to ensure data integrity. +**Note:** A failed `Result` (`success=False`) is **never cached**, in any tier. A transient RPC or API failure is returned to the caller but the next call retries immediately instead of serving the failure for the rest of the TTL. + ### Per-User Caching Balance data is cached per user address. When `address=None`, the SDK uses the connected wallet's address: @@ -351,6 +353,33 @@ balance1 = await client.get_portfolio_balance("USDC") # Uses connected wallet balance2 = await client.get_portfolio_balance("USDC", address="0xOtherUser") # Different cache entry ``` +### Wallet Balance Results + +Chain-wallet balance methods return entries of the shape +`{"chain", "symbol", "balance", "type"}` (ERC20 entries also carry `"address"`). +`balance` is always a numeric string on success. A lookup that fails (RPC error, +chain not connected, unknown token) never puts an error string in `balance`: + +- `get_chain_wallet_balance(chain, token)` returns `Result.fail()`. +- `get_chain_wallet_balances(chain)` and `get_all_chain_wallet_balances()` drop the + failed entry from `chain_balances` and append `" : "` to + an additional `errors` list. The `Result` is still `ok` when at least one lookup + succeeded, and `fail` only when every lookup failed. +- `get_chain_token_balances(chain, address, tokens)` fails the whole `Result` if any + requested token could not be read, so the returned map only ever holds numbers. + +```python +result = await client.get_all_chain_wallet_balances() +if result.success: + for entry in result.data["chain_balances"]: + print(entry["chain"], entry["symbol"], Decimal(entry["balance"])) + for problem in result.data["errors"]: + print("skipped:", problem) # e.g. "Avalanche AVAX: Error fetching native balance: ..." +``` + +Tolerated per-entry failures are logged at `WARNING` without a traceback; use +`log_level="DEBUG"` if you need the full exception locally. + ### Performance Impact Expected reduction in API calls: diff --git a/VERSION b/VERSION index ee6cdce..b616048 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.6.1 +0.6.2 diff --git a/docs/index.md b/docs/index.md index 239f20e..7c018a1 100644 --- a/docs/index.md +++ b/docs/index.md @@ -58,4 +58,4 @@ pip install dexalot-sdk ## Version -Current release: **0.4.0** — Python ≥ 3.12 +Current release: **0.6.2** — Python ≥ 3.12 diff --git a/docs/python-sdk-error-handling.md b/docs/python-sdk-error-handling.md index 089cbd3..c48ad65 100644 --- a/docs/python-sdk-error-handling.md +++ b/docs/python-sdk-error-handling.md @@ -95,6 +95,23 @@ result = await client.deposit(token="USDC", amount=99999.0, source_chain="Avalan # result.error == "insufficient balance" (decoded revert reason) ``` +### 4. Wallet balance lookups + +A chain-wallet balance that cannot be read (RPC error, chain not connected, unknown token) is never reported as a success with an error string in the `balance` field. The single-token method fails the `Result`; the plural methods keep the entries that succeeded and list the failures separately. + +```python +result = await client.get_chain_wallet_balance("Avalanche", "AVAX") +# result.success == False +# result.error == "Error fetching native balance: HTTP 500 ..." (sanitized) + +result = await client.get_all_chain_wallet_balances() +# result.success == True (at least one lookup succeeded) +# result.data["chain_balances"] -> only entries with a numeric "balance" +# result.data["errors"] -> ["Avalanche AVAX: Error fetching native balance: ..."] +``` + +Failed `Result`s are not cached, so the next call retries immediately. These tolerated failures are logged at `WARNING` without a traceback. + --- ## Revert reasons diff --git a/docs/python-sdk-remediation-plan.md b/docs/python-sdk-remediation-plan.md index 19e414c..848c5fa 100644 --- a/docs/python-sdk-remediation-plan.md +++ b/docs/python-sdk-remediation-plan.md @@ -263,7 +263,53 @@ except Exception as e: **Resolution:** Replaced `f"Error: {e}"` / `f"Error: {str(e)}"` in `_get_l1_native_balance` and `_get_native_balance` with `self._sanitize_error(e, "")`. Two unit tests added in `tests/unit/core/test_transfer.py` (`test_get_l1_native_balance_sanitizes_error`, -`test_get_native_balance_sanitizes_error`). +`test_get_native_balance_sanitizes_error`). Superseded in v0.6.2 by H-6, which removed the +`"Error: ..."` string from `balance` altogether. + +--- + +### H-6: Balance lookup failures returned as success with a string sentinel + +**Status:** ✅ Resolved — v0.6.2 + +**Finding:** +`_get_native_balance`, `_get_erc20_balance` and `_get_l1_native_balance` swallowed RPC +exceptions and wrote `"Error: ..."` (or `"Not connected"`) into the entry's `balance` field. +`_get_chain_wallet_balance_cached` then returned `Result.ok(entry)`, so callers saw +`success=True` with a non-numeric balance; the ERC20 `"error" in balance` guard only caught +pre-RPC token-lookup failures. `async_ttl_cached` stored the poisoned `Result` for the 10 s +balance TTL (and any failed `Result` for up to 1 h in the static tier). Observed in +TradeBots on 2026-09-19: an Avalanche RPC HTTP 500 on `eth_getBalance` produced +`decimal.ConversionSyntax` in the sufficient-balance gate, plus a full ERROR traceback per +transient blip. + +**Affected files:** +- [src/dexalot_sdk/core/transfer.py](../src/dexalot_sdk/core/transfer.py) — `_get_l1_native_balance`, `_get_native_balance`, `_get_erc20_balance`, `_fetch_erc20_balances_list`, `_get_chain_wallet_balance_cached`, `_get_chain_wallet_balances_cached`, `_get_all_chain_wallet_balances_cached` +- [src/dexalot_sdk/utils/cache.py](../src/dexalot_sdk/utils/cache.py) — `ttl_cached`, `async_ttl_cached` +- [src/dexalot_sdk/core/base.py](../src/dexalot_sdk/core/base.py) — `_sanitize_error` + +**Implementation plan:** +- Failed entries carry `balance=None` and an `error` key; no string sentinel in `balance`. +- Single-token path returns `Result.fail(entry["error"])` for any error entry. +- Plural paths drop failed entries from `chain_balances`, report them in an additive + `errors: list[str]`, and return `Result.fail` only when every lookup failed. +- Cache decorators skip storing a `Result` whose `success` is `False`, in all tiers. +- `_sanitize_error(level=...)`: balance helpers log at WARNING without traceback. + +**Acceptance criteria:** +- `get_chain_wallet_balance` on an RPC exception returns `success=False`; the next call + (RPC healthy) succeeds without clearing the cache. +- Plural results contain only numeric `balance` values; failures appear in `errors`. +- `get_chain_token_balances` returns `Result.fail` if any requested token cannot be read. +- No `"Error:"` / `"Not connected"` string appears in any `balance` field. + +**Resolution:** Implemented as planned (PR: mng/balance-result-semantics, v0.6.2). New helpers +`_balance_error_entry`, `_balance_entry_result`, `_collect_balance_entries`, `_balances_result` +in `transfer.py`; `_is_cacheable` in `utils/cache.py`. Tests added across +`tests/unit/core/test_transfer.py`, `tests/unit/utils/test_cache.py`, +`tests/unit/core/test_base.py`, `tests/unit/test_caching.py` +(`test_get_deployment_failure_is_not_cached`). Same contract shipped in the TypeScript SDK +v0.6.2. --- diff --git a/docs/python-sdk-user-guide.md b/docs/python-sdk-user-guide.md index 0a60563..d024ff0 100644 --- a/docs/python-sdk-user-guide.md +++ b/docs/python-sdk-user-guide.md @@ -401,11 +401,26 @@ result = await client.get_portfolio_balance(token="USDC") ```python result = await client.get_all_chain_wallet_balances() +if result.success: + for entry in result.data["chain_balances"]: + # entry["balance"] is always a numeric string here + print(entry["chain"], entry["symbol"], entry["balance"]) + for problem in result.data["errors"]: + # Lookups that failed (RPC error, chain not connected) are listed + # here instead of appearing in chain_balances. + print("skipped:", problem) ``` +`get_chain_wallet_balances(chain)` has the same shape. Both return +`Result.fail` only when *every* lookup failed. The single-token +`get_chain_wallet_balance(chain, token)` returns `Result.fail` on any +failure, so `result.data["balance"]` is safe to convert with `Decimal` +whenever `result.success` is true. + For a known subset of tokens, `get_chain_token_balances` returns a flat `{symbol: balance}` map and errors if any of the requested tokens isn't -available on the chain (rather than silently skipping it): +available on the chain or could not be read (rather than silently skipping +it): ```python result = await client.get_chain_token_balances( diff --git a/docs/sdk-caching.md b/docs/sdk-caching.md index 785227f..2c82b9c 100644 --- a/docs/sdk-caching.md +++ b/docs/sdk-caching.md @@ -74,6 +74,12 @@ const client = new DexalotClient(createConfig({ **Important:** Balance data is cached **per user address** to ensure data privacy and accuracy. +**Failed lookups are never cached.** In every tier, a `Result` with `success=False` +(RPC 500, API timeout, chain not connected) is returned to the caller but not stored, +so the next call retries immediately rather than serving the failure for the rest of +the TTL. Concurrent callers coalesced by stampede protection all receive the same +failed `Result`. + **When to customize:** - Set higher TTL (e.g., 30-60 seconds) for read-heavy applications - Set lower TTL (e.g., 1-5 seconds) for applications requiring near-real-time balances diff --git a/pyproject.toml b/pyproject.toml index 7aaa5ab..1be7955 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,7 +8,7 @@ license = "MIT" license-files = [ "LICENSE.txt" ] -version = "0.6.1" +version = "0.6.2" description = "Dexalot Python SDK - Core library for Dexalot interaction" readme = "README.md" requires-python = ">=3.12,<3.15" diff --git a/src/dexalot_sdk/__init__.py b/src/dexalot_sdk/__init__.py index 03e4809..112c35a 100644 --- a/src/dexalot_sdk/__init__.py +++ b/src/dexalot_sdk/__init__.py @@ -12,7 +12,7 @@ secrets_vault_set, ) -__version__ = "0.6.1" +__version__ = "0.6.2" def get_version() -> str: diff --git a/src/dexalot_sdk/core/base.py b/src/dexalot_sdk/core/base.py index ba20d81..e7d9d14 100644 --- a/src/dexalot_sdk/core/base.py +++ b/src/dexalot_sdk/core/base.py @@ -767,7 +767,9 @@ def _parse_revert_reason(self, error_msg): return f"{code}: {description}" return error_str - def _sanitize_error(self, error: Exception, context: str = "") -> str: + def _sanitize_error( + self, error: Exception, context: str = "", *, level: int = logging.ERROR + ) -> str: """Sanitize an error to prevent leaking sensitive information. This method: @@ -778,6 +780,11 @@ def _sanitize_error(self, error: Exception, context: str = "") -> str: Args: error: The exception to sanitize context: Optional context string describing the operation + level: Logging level for the internal log record. Defaults to + ``logging.ERROR`` with the full traceback attached. Callers + that tolerate the failure (e.g. per-token balance lookups that + degrade gracefully) pass ``logging.WARNING``; below ERROR the + traceback is omitted so transient RPC blips do not spam logs. Returns: A sanitized, user-safe error message @@ -794,10 +801,11 @@ def _sanitize_error(self, error: Exception, context: str = "") -> str: # Full sanitization for non-contract errors sanitized = sanitize_error_message(error, context) - # Log full error details internally (with stack trace) - self.logger.error( + # Log full error details internally (stack trace only at ERROR and above) + self.logger.log( + level, f"Error in {context or 'operation'}", - exc_info=error, + exc_info=error if level >= logging.ERROR else None, extra={"error_type": type(error).__name__, "sanitized_message": sanitized}, ) diff --git a/src/dexalot_sdk/core/transfer.py b/src/dexalot_sdk/core/transfer.py index 54791e2..a969616 100644 --- a/src/dexalot_sdk/core/transfer.py +++ b/src/dexalot_sdk/core/transfer.py @@ -1,4 +1,5 @@ import asyncio +import logging import math from dataclasses import dataclass from datetime import UTC, datetime @@ -302,7 +303,7 @@ async def _get_chain_wallet_balance_cached( f"Token {token} not available on Dexalot L1. Only ALOT (native) exists." ) balance = await self._get_l1_native_balance(query_address) - return Result.ok(balance) + return self._balance_entry_result(balance) # Check connected chain w3_provider = await self._get_provider_for_chain(chain) @@ -319,16 +320,62 @@ async def _get_chain_wallet_balance_cached( balance = await self._get_native_balance( chain, w3_provider, query_address, native_symbol ) - return Result.ok(balance) + return self._balance_entry_result(balance) # ERC20 token check if not chain_id: return Result.fail(f"Chain ID not configured for {chain}") balance = await self._get_erc20_balance(chain, chain_id, w3_provider, query_address, token) - if isinstance(balance, dict) and "error" in balance: - return Result.fail(balance["error"]) - return Result.ok(balance) + return self._balance_entry_result(balance) + + @staticmethod + def _balance_entry_result(entry: dict) -> Result[dict]: + """Turn a single balance entry into a ``Result``. + + An entry carrying an ``error`` key (RPC failure, chain not connected, + unknown token) becomes ``Result.fail`` so callers never see + ``success=True`` with a non-numeric ``balance``. + """ + if entry.get("error"): + return Result.fail(str(entry["error"])) + return Result.ok(entry) + + @staticmethod + def _collect_balance_entries(info: dict[str, Any], entries: list[Any]) -> None: + """Split balance entries into ``info["chain_balances"]`` and ``info["errors"]``. + + ``entries`` may contain single entry dicts or lists of entry dicts (as + returned by ``_fetch_erc20_balances_list``). Entries with an ``error`` + key are reported as ``" : "`` strings and are + never appended to ``chain_balances``, so every ``balance`` in the + result is numeric. + """ + flat: list[dict] = [] + for res in entries: + if isinstance(res, list): + flat.extend(res) + else: + flat.append(res) + for entry in flat: + if entry.get("error"): + label = " ".join(str(v) for v in (entry.get("chain"), entry.get("symbol")) if v) + info["errors"].append( + f"{label}: {entry['error']}" if label else str(entry["error"]) + ) + else: + info["chain_balances"].append(entry) + + @staticmethod + def _balances_result(info: dict[str, Any]) -> Result[dict]: + """``Result.fail`` only when every lookup failed; otherwise ``Result.ok``. + + Partial failures are surfaced through ``info["errors"]`` while the + successful entries remain available in ``info["chain_balances"]``. + """ + if not info["chain_balances"] and info["errors"]: + return Result.fail("; ".join(info["errors"])) + return Result.ok(info) @track_method("transfer") async def get_chain_wallet_balances( @@ -381,14 +428,14 @@ async def _get_chain_wallet_balances_cached( "address": query_address, "chain": chain, "chain_balances": [], + "errors": [], } # Check Dexalot L1 if chain == "Dexalot L1": l1_entry = await self._get_l1_native_balance(query_address) - if "error" not in l1_entry: - info["chain_balances"].append(l1_entry) - return Result.ok(info) + self._collect_balance_entries(info, [l1_entry]) + return self._balances_result(info) # Check connected chain w3_provider = await self._get_provider_for_chain(chain) @@ -407,13 +454,8 @@ async def _get_chain_wallet_balances_cached( ) results = await asyncio.gather(*tasks) - for res in results: - if isinstance(res, list): - info["chain_balances"].extend(res) - elif isinstance(res, dict) and "error" not in res: - info["chain_balances"].append(res) - - return Result.ok(info) + self._collect_balance_entries(info, list(results)) + return self._balances_result(info) @track_method("transfer") async def get_chain_token_balances( @@ -566,6 +608,7 @@ async def _get_all_chain_wallet_balances_cached( info: dict[str, Any] = { "address": query_address, "chain_balances": [], + "errors": [], } tasks = [self._get_l1_native_balance(query_address)] @@ -590,50 +633,75 @@ async def _get_all_chain_wallet_balances_cached( ) results = await asyncio.gather(*tasks) + self._collect_balance_entries(info, list(results)) + return self._balances_result(info) - for res in results: - if isinstance(res, list): - info["chain_balances"].extend(res) - elif isinstance(res, dict) and "error" not in res: - info["chain_balances"].append(res) - - return Result.ok(info) + def _balance_error_entry( + self, + chain: str, + symbol: str, + kind: str, + failure: Exception | str, + context: str, + **extra: Any, + ) -> dict[str, Any]: + """Build a balance entry describing a failed lookup. + + ``balance`` is always ``None`` on failure; the reason lives in + ``error``. Exceptions are sanitized and logged at WARNING without a + traceback (a per-token RPC blip is tolerated, not fatal). A plain + string is used verbatim for non-exception conditions such as + "not connected". + """ + if isinstance(failure, Exception): + message = self._sanitize_error(failure, context, level=logging.WARNING) + else: + message = failure + return { + "chain": chain, + "symbol": symbol, + "balance": None, + **extra, + "type": kind, + "error": message, + } - async def _get_l1_native_balance(self, address: str): + async def _get_l1_native_balance(self, address: str) -> dict[str, Any]: """Get ALOT balance on Dexalot L1.""" - entry = { + if not self.w3_l1: + return self._balance_error_entry( + "Dexalot L1", "ALOT", "Native", "Dexalot L1 not connected", "" + ) + try: + l1_balance = await self.w3_l1.eth.get_balance(cast(Any, address)) + except Exception as e: + return self._balance_error_entry( + "Dexalot L1", "ALOT", "Native", e, "fetching L1 native balance" + ) + return { "chain": "Dexalot L1", "symbol": "ALOT", - "balance": "0", + "balance": str(self.w3_l1.from_wei(l1_balance, "ether")), "type": "Native", } - if self.w3_l1: - try: - l1_balance = await self.w3_l1.eth.get_balance(cast(Any, address)) - entry["balance"] = str(self.w3_l1.from_wei(l1_balance, "ether")) - except Exception as e: - entry["balance"] = f"Error: {self._sanitize_error(e, 'fetching L1 native balance')}" - else: - entry["balance"] = "Not connected" - return entry async def _get_native_balance( self, chain_name: str, w3_provider, address: str, native_symbol: str - ): + ) -> dict[str, Any]: """Get native token balance on a connected chain.""" - entry = { - "chain": chain_name, - "symbol": native_symbol, - "balance": "Error", - "type": "Native", - } try: balance_wei = await w3_provider.eth.get_balance(address) balance_eth = w3_provider.from_wei(balance_wei, "ether") - entry["balance"] = str(balance_eth) except Exception as e: - entry["balance"] = f"Error: {self._sanitize_error(e, 'fetching native balance')}" - return entry + return self._balance_error_entry( + chain_name, native_symbol, "Native", e, "fetching native balance" + ) + return { + "chain": chain_name, + "symbol": native_symbol, + "balance": str(balance_eth), + "type": "Native", + } async def _get_erc20_balance( self, chain_name: str, chain_id: int, w3_provider, address: str, token: str @@ -669,24 +737,23 @@ async def _get_erc20_balance( if token_address == "0x0000000000000000000000000000000000000000": return {"error": f"Token {token} has zero address on chain {chain_name}."} - entry = { - "chain": chain_name, - "symbol": token, - "balance": "Error", - "address": token_address, - "type": "ERC20", - } - try: contract = w3_provider.eth.contract(address=token_address, abi=erc20_abi) balance_wei = await contract.functions.balanceOf(address).call() decimals = token_info.get("evmdecimals", 18) balance_fmt = Utils.unit_conversion(balance_wei, decimals, to_base=False) - entry["balance"] = str(balance_fmt) except Exception as e: - entry["balance"] = f"Error: {self._sanitize_error(e, 'fetching ERC20 balance')}" + return self._balance_error_entry( + chain_name, token, "ERC20", e, "fetching ERC20 balance", address=token_address + ) - return entry + return { + "chain": chain_name, + "symbol": token, + "balance": str(balance_fmt), + "address": token_address, + "type": "ERC20", + } async def _fetch_erc20_balances_list(self, chain_id, chain_name, w3_provider, address: str): erc20_abi = [ @@ -738,6 +805,16 @@ async def _guarded(coro): token_symbols, results, strict=False ): if isinstance(balance_wei, Exception): + balances.append( + self._balance_error_entry( + chain_name, + symbol, + "ERC20", + balance_wei, + "fetching ERC20 balance", + address=token_address, + ) + ) continue balance_fmt = Utils.unit_conversion(balance_wei, decimals, to_base=False) diff --git a/src/dexalot_sdk/utils/cache.py b/src/dexalot_sdk/utils/cache.py index e0e795e..7b8a257 100644 --- a/src/dexalot_sdk/utils/cache.py +++ b/src/dexalot_sdk/utils/cache.py @@ -1,3 +1,11 @@ +"""TTL caches and caching decorators. + +Both ``ttl_cached`` and ``async_ttl_cached`` skip storing a returned +``Result`` whose ``success`` is ``False``: a transient failure (RPC 500, +API timeout) must not be pinned for the tier's TTL. Non-``Result`` values +and successful ``Result`` values are cached as before. +""" + import asyncio import inspect import time @@ -5,6 +13,13 @@ from functools import wraps from typing import Any +from .result import Result + + +def _is_cacheable(value: Any) -> bool: + """Return ``False`` for a failed ``Result``; ``True`` for everything else.""" + return not (isinstance(value, Result) and not value.success) + class MemoryCache: _CLEANUP_INTERVAL = 50 # run cleanup every N writes @@ -95,7 +110,8 @@ def wrapper(*args, **kwargs): if cached is not None: return cached result = func(*args, **kwargs) - cache.set(key, result) + if _is_cacheable(result): + cache.set(key, result) return result return wrapper @@ -112,6 +128,9 @@ def async_ttl_cached(cache: MemoryCache): Stampede protection: concurrent callers for the same uncached key are coalesced — the underlying function is called exactly once and all waiters receive the same result. + + Failed ``Result`` values are handed to every waiter but are *not* + stored, so the next caller after the in-flight fetch retries. """ def decorator(func: Callable): @@ -162,7 +181,8 @@ async def wrapper(*args, **kwargs): try: result = await func(*args, **kwargs) - cache.set(key, result) + if _is_cacheable(result): + cache.set(key, result) fut.set_result(result) return result except Exception as e: diff --git a/tests/unit/core/test_base.py b/tests/unit/core/test_base.py index 25ee379..c74fd95 100644 --- a/tests/unit/core/test_base.py +++ b/tests/unit/core/test_base.py @@ -2298,6 +2298,36 @@ async def test_sanitize_error_with_parsed_reason(self, client): assert "E001" in call_args[0] or "Some Error Description" in call_args[0] assert result == "Sanitized error" + async def test_sanitize_error_default_level_logs_error_with_traceback(self, client): + """Without an explicit level the sanitizer logs at ERROR and attaches exc_info.""" + import logging + + client.logger = MagicMock() + error = ValueError("plain failure") + + client._sanitize_error(error, "doing thing") + + client.logger.log.assert_called_once() + level = client.logger.log.call_args[0][0] + assert level == logging.ERROR + assert client.logger.log.call_args.kwargs["exc_info"] is error + assert client.logger.log.call_args.kwargs["extra"]["error_type"] == "ValueError" + + async def test_sanitize_error_warning_level_omits_traceback(self, client): + """Callers that tolerate the failure can log at WARNING without a stack trace.""" + import logging + + client.logger = MagicMock() + + sanitized = client._sanitize_error( + ValueError("tolerated"), "fetching balance", level=logging.WARNING + ) + + assert sanitized + level = client.logger.log.call_args[0][0] + assert level == logging.WARNING + assert client.logger.log.call_args.kwargs["exc_info"] is None + @patch("dexalot_sdk.core.base.aiohttp.TCPConnector") @patch("dexalot_sdk.core.base.aiohttp.ClientSession") async def test_make_http_request_python_lt_314(self, mock_session, mock_connector, client): diff --git a/tests/unit/core/test_transfer.py b/tests/unit/core/test_transfer.py index 9192efe..53b8cba 100644 --- a/tests/unit/core/test_transfer.py +++ b/tests/unit/core/test_transfer.py @@ -1,4 +1,5 @@ import asyncio +import logging import os from decimal import Decimal from unittest.mock import AsyncMock, MagicMock, patch @@ -321,7 +322,8 @@ async def test_get_chain_wallet_balance_erc20_contract_error(self, client): } } info = await client.get_chain_wallet_balance("Avalanche", "ERR") - assert not info.success or "Error" in str(info.data.get("balance", "")) + assert not info.success + assert "fetching ERC20 balance" in info.error async def test_get_chain_wallet_balance_no_chain_id(self, client): # Chain ID not configured @@ -568,23 +570,38 @@ async def test_get_all_chain_wallet_balances(self, client): ) assert avax_entry["balance"] == "5.0" - # Test error handling - L1 balance error + assert info.data["errors"] == [] + + # Partial failure: L1 lookup fails but Avalanche still succeeds. from dexalot_sdk.core.base import _BALANCE_CACHE _BALANCE_CACHE.clear() client.w3_l1.eth.get_balance.side_effect = Exception("L1 Error") info = await client.get_all_chain_wallet_balances() assert info.success - l1_entry = next(b for b in info.data["chain_balances"] if b["chain"] == "Dexalot L1") - # The error should be in the balance field - assert "Error" in str(l1_entry["balance"]) + assert not any(b["chain"] == "Dexalot L1" for b in info.data["chain_balances"]) + assert all(b["balance"] is not None for b in info.data["chain_balances"]) + assert len(info.data["errors"]) == 1 + assert info.data["errors"][0].startswith("Dexalot L1 ALOT: ") async def test_get_all_chain_wallet_balances_not_connected(self, client): + """A missing L1 provider is reported in ``errors`` and never as a balance string.""" client.w3_l1 = None info = await client.get_all_chain_wallet_balances() assert info.success - l1_entry = next(b for b in info.data["chain_balances"] if b["chain"] == "Dexalot L1") - assert l1_entry["balance"] == "Not connected" + assert not any(b["chain"] == "Dexalot L1" for b in info.data["chain_balances"]) + assert info.data["errors"] == ["Dexalot L1 ALOT: Dexalot L1 not connected"] + + async def test_get_all_chain_wallet_balances_all_failed_returns_fail(self, client): + """When every lookup fails the plural call returns Result.fail, not an empty success.""" + client.w3_l1 = None + avax = client.connected_chain_providers["Avalanche"] + avax.eth.get_balance = AsyncMock(side_effect=Exception("RPC 500")) + avax.eth.contract.side_effect = Exception("no contract") + info = await client.get_all_chain_wallet_balances() + assert not info.success + assert "Dexalot L1 ALOT: Dexalot L1 not connected" in info.error + assert "Avalanche AVAX: " in info.error async def test_get_portfolio_balance(self, client): client.portfolio_sub_contract.functions.getBalance.return_value.call = AsyncMock( @@ -1290,8 +1307,8 @@ async def test_transfer_missing_coverage(self, client): client.w3_l1.eth.get_balance.side_effect = Exception("Err") info = await client.get_all_chain_wallet_balances() assert info.success - l1_entry = next(b for b in info.data["chain_balances"] if b["chain"] == "Dexalot L1") - assert "Error" in l1_entry["balance"] + assert not any(b["chain"] == "Dexalot L1" for b in info.data["chain_balances"]) + assert any(e.startswith("Dexalot L1 ALOT: ") for e in info.data["errors"]) from dexalot_sdk.core.base import _BALANCE_CACHE @@ -1306,8 +1323,12 @@ async def test_transfer_missing_coverage(self, client): info = await client.get_all_chain_wallet_balances() assert info.success - avax_entry = next(b for b in info.data["chain_balances"] if b["chain"] == "Avalanche") - assert "Error" in str(avax_entry["balance"]) + # Avalanche native failed: no Native entry, ERC20 entries still numeric, one error. + assert not any( + b["chain"] == "Avalanche" and b["type"] == "Native" for b in info.data["chain_balances"] + ) + assert all(b["balance"] is not None for b in info.data["chain_balances"]) + assert any(e.startswith("Avalanche AVAX: ") for e in info.data["errors"]) client.portfolio_sub_contract = MagicMock() client.portfolio_sub_contract.functions.getBalance.side_effect = Exception("Err") @@ -1661,7 +1682,12 @@ async def raise_exception(): 43114, "Avalanche", mock_provider, VALID_ADDRESS ) assert isinstance(result, list) - assert len(result) == 0 + # Failed tokens are reported as error entries so plural callers can surface them. + assert len(result) == 2 + assert {e["symbol"] for e in result} == {"TOKEN1", "TOKEN2"} + assert all(e["balance"] is None for e in result) + assert all(e["error"] for e in result) + assert all(e["type"] == "ERC20" for e in result) assert mock_provider.eth.contract.called async def test_fetch_erc20_balances_list_concurrency_limit(self, client): @@ -2210,10 +2236,11 @@ async def test_get_l1_native_balance_sanitizes_error(self, client): entry = await client._get_l1_native_balance(VALID_ADDRESS) - assert secret_url not in entry["balance"], ( - "Raw exception with secret URL must not appear in balance output" + assert entry["balance"] is None + assert secret_url not in entry["error"], ( + "Raw exception with secret URL must not appear in error output" ) - assert entry["balance"].startswith("Error:") + assert entry["error"] async def test_get_native_balance_sanitizes_error(self, client): """H-5: _get_native_balance must not leak raw exception text (e.g. URLs) to callers.""" @@ -2223,10 +2250,169 @@ async def test_get_native_balance_sanitizes_error(self, client): entry = await client._get_native_balance("Avalanche", w3, VALID_ADDRESS, "AVAX") - assert secret_url not in entry["balance"], ( - "Raw exception with secret URL must not appear in balance output" + assert entry["balance"] is None + assert secret_url not in entry["error"], ( + "Raw exception with secret URL must not appear in error output" + ) + assert entry["error"] + + async def test_get_erc20_balance_rpc_failure_returns_error_entry(self, client): + """A failing balanceOf yields balance=None plus a sanitized error, keeping the address.""" + w3 = self.create_w3() + mock_contract = MagicMock() + mock_contract.functions.balanceOf.return_value.call = AsyncMock( + side_effect=Exception("failed: https://rpc.example.com/secret-key") + ) + w3.eth.contract.side_effect = None + w3.eth.contract.return_value = mock_contract + + entry = await client._get_erc20_balance("Avalanche", 43114, w3, VALID_ADDRESS, "USDC") + + assert entry["balance"] is None + assert entry["address"] == "0xUSDC" + assert entry["type"] == "ERC20" + assert "secret-key" not in entry["error"] + assert entry["error"] + + async def test_balance_error_entry_logs_warning_without_traceback(self, client): + """Tolerated balance failures log at WARNING and omit exc_info.""" + client.logger = MagicMock() + entry = client._balance_error_entry( + "Avalanche", "AVAX", "Native", Exception("boom"), "fetching native balance" + ) + assert entry["balance"] is None + assert entry["error"] + client.logger.log.assert_called_once() + level = client.logger.log.call_args[0][0] + assert level == logging.WARNING + assert client.logger.log.call_args.kwargs["exc_info"] is None + + async def test_balance_error_entry_with_plain_message_does_not_log(self, client): + """A non-exception reason (e.g. not connected) is used verbatim and is not logged.""" + client.logger = MagicMock() + entry = client._balance_error_entry("Dexalot L1", "ALOT", "Native", "not connected", "") + assert entry == { + "chain": "Dexalot L1", + "symbol": "ALOT", + "balance": None, + "type": "Native", + "error": "not connected", + } + client.logger.log.assert_not_called() + + def test_collect_balance_entries_error_without_chain_label(self, client): + """An error entry lacking chain/symbol is reported verbatim.""" + info = {"chain_balances": [], "errors": []} + client._collect_balance_entries( + info, [{"error": "Token X not found"}, [{"chain": "A", "symbol": "B", "balance": "1"}]] ) - assert entry["balance"].startswith("Error:") + assert info["errors"] == ["Token X not found"] + assert info["chain_balances"] == [{"chain": "A", "symbol": "B", "balance": "1"}] + + def test_balances_result_empty_without_errors_is_ok(self, client): + """No entries and no errors (nothing to look up) is still a success.""" + info = {"chain_balances": [], "errors": []} + res = client._balances_result(info) + assert res.success + assert res.data is info + + async def test_get_chain_wallet_balance_native_rpc_failure_fails(self, client): + """An RPC failure on the native lookup is a failed Result, never success with a string.""" + avax = client.connected_chain_providers["Avalanche"] + avax.eth.get_balance = AsyncMock(side_effect=Exception("500 Internal Server Error")) + + info = await client.get_chain_wallet_balance("Avalanche", "AVAX") + + assert not info.success + assert info.data is None + assert "fetching native balance" in info.error + + async def test_get_chain_wallet_balance_l1_rpc_failure_fails(self, client): + client.w3_l1.eth.get_balance = AsyncMock(side_effect=Exception("L1 down")) + + info = await client.get_chain_wallet_balance("Dexalot L1", "ALOT") + + assert not info.success + assert "fetching L1 native balance" in info.error + + async def test_get_chain_wallet_balance_l1_not_connected_fails(self, client): + client.w3_l1 = None + + info = await client.get_chain_wallet_balance("Dexalot L1", "ALOT") + + assert not info.success + assert info.error == "Dexalot L1 not connected" + + async def test_get_chain_wallet_balance_erc20_rpc_failure_fails(self, client): + avax = client.connected_chain_providers["Avalanche"] + mock_contract = MagicMock() + mock_contract.functions.balanceOf.return_value.call = AsyncMock( + side_effect=Exception("balanceOf reverted") + ) + avax.eth.contract.side_effect = None + avax.eth.contract.return_value = mock_contract + + info = await client.get_chain_wallet_balance("Avalanche", "USDC") + + assert not info.success + assert "fetching ERC20 balance" in info.error + + async def test_get_chain_wallet_balance_failure_is_not_cached(self, client): + """A failed lookup is not pinned in the balance cache; the next call retries.""" + avax = client.connected_chain_providers["Avalanche"] + avax.eth.get_balance = AsyncMock(side_effect=Exception("500 Internal Server Error")) + + first = await client.get_chain_wallet_balance("Avalanche", "AVAX") + assert not first.success + + avax.eth.get_balance = AsyncMock(return_value=3 * 10**18) + second = await client.get_chain_wallet_balance("Avalanche", "AVAX") + + assert second.success + assert second.data["balance"] == "3.0" + + async def test_get_chain_wallet_balances_partial_failure_reports_errors(self, client): + """Native failure with successful ERC20s: ok Result, numeric balances, one error.""" + avax = client.connected_chain_providers["Avalanche"] + avax.eth.get_balance = AsyncMock(side_effect=Exception("500 Internal Server Error")) + + info = await client.get_chain_wallet_balances("Avalanche") + + assert info.success + assert info.data["chain_balances"] + assert all(b["balance"] is not None for b in info.data["chain_balances"]) + assert all(b["type"] == "ERC20" for b in info.data["chain_balances"]) + assert len(info.data["errors"]) == 1 + assert info.data["errors"][0].startswith("Avalanche AVAX: ") + + async def test_get_chain_wallet_balances_all_failed_returns_fail(self, client): + avax = client.connected_chain_providers["Avalanche"] + avax.eth.get_balance = AsyncMock(side_effect=Exception("500 Internal Server Error")) + avax.eth.contract.side_effect = Exception("no contract") + + info = await client.get_chain_wallet_balances("Avalanche") + + assert not info.success + assert info.error.startswith("Avalanche AVAX: ") + + async def test_get_chain_wallet_balances_l1_failure_returns_fail(self, client): + client.w3_l1.eth.get_balance = AsyncMock(side_effect=Exception("L1 down")) + + info = await client.get_chain_wallet_balances("Dexalot L1") + + assert not info.success + assert info.error.startswith("Dexalot L1 ALOT: ") + + async def test_get_chain_token_balances_rpc_failure_fails(self, client): + """The flat symbol map never carries an error string; the Result fails instead.""" + avax = client.connected_chain_providers["Avalanche"] + avax.eth.get_balance = AsyncMock(side_effect=Exception("500 Internal Server Error")) + + result = await client.get_chain_token_balances("Avalanche", VALID_ADDRESS, ["AVAX"]) + + assert not result.success + assert result.error.startswith("AVAX: ") + assert "fetching native balance" in result.error async def test_get_all_portfolio_balances_rpc_exception(self, client): """When asyncio.gather returns a BaseException in its results, the method re-raises it immediately.""" diff --git a/tests/unit/test_caching.py b/tests/unit/test_caching.py index 5334381..7c793a5 100644 --- a/tests/unit/test_caching.py +++ b/tests/unit/test_caching.py @@ -119,23 +119,69 @@ async def test_get_chains_uses_cache(self, mock_env_setup): assert elapsed < 0.01 # Should be near-instant (cached) async def test_get_deployment_uses_cache(self, mock_env_setup): - """Verify get_deployment() uses cache.""" + """Verify a successful get_deployment() is served from cache on the second call.""" with patch("dexalot_sdk.core.base.aiohttp.ClientSession"): + mock_resp = AsyncMock() + mock_resp.status = 200 + mock_resp.json = AsyncMock( + return_value=[ + {"contract_name": "TradePairs", "address": "0x123", "abi": {"abi": []}} + ] + ) + mock_resp.text = AsyncMock(return_value="") + mock_resp.raise_for_status = MagicMock() + mock_cm = AsyncMock() + mock_cm.__aenter__.return_value = mock_resp + mock_cm.__aexit__.return_value = None + with patch.dict(os.environ, {"PRIVATE_KEY": "0x" + "a" * 64}, clear=False): with patch("dexalot_sdk.core.config.load_dotenv"): client = DexalotClient() - client.deployments = {"TradePairs": {"address": "0x123"}} + client._mock_session = MagicMock() + client._session = client._mock_session + client._mock_session.get.return_value = mock_cm - # First call result1 = await client.get_deployment() + assert result1.success + call_count_1 = client._mock_session.get.call_count - # Second call - should be cached - start = time.time() result2 = await client.get_deployment() - elapsed = time.time() - start + assert result2.success + call_count_2 = client._mock_session.get.call_count - assert result1 == result2 - assert elapsed < 0.01 # Should be near-instant (cached) + assert result1.data == result2.data + assert call_count_2 == call_count_1 + + async def test_get_deployment_failure_is_not_cached(self, mock_env_setup): + """A failed get_deployment() must not be pinned in the 1-hour static tier.""" + from dexalot_sdk.core.base import _STATIC_CACHE + + _STATIC_CACHE.clear() + with patch("dexalot_sdk.core.base.aiohttp.ClientSession"): + with patch.dict(os.environ, {"PRIVATE_KEY": "0x" + "a" * 64}, clear=False): + with patch("dexalot_sdk.core.config.load_dotenv"): + client = DexalotClient() + + attempts = {"n": 0} + + async def flaky(*_args, **_kwargs): + attempts["n"] += 1 + if attempts["n"] == 1: + raise RuntimeError("HTTP 500") + return [{"contract_name": "TradePairs", "address": "0x123"}] + + client._api_call = flaky + + first = await client.get_deployment() + assert not first.success + + second = await client.get_deployment() + assert second.success + assert attempts["n"] == 2 + + third = await client.get_deployment() + assert third.success + assert attempts["n"] == 2 class TestSemiStaticDataCaching: diff --git a/tests/unit/utils/test_cache.py b/tests/unit/utils/test_cache.py index 181180f..90d2f65 100644 --- a/tests/unit/utils/test_cache.py +++ b/tests/unit/utils/test_cache.py @@ -6,6 +6,101 @@ import pytest from dexalot_sdk.utils.cache import MemoryCache, async_ttl_cached, ttl_cached +from dexalot_sdk.utils.result import Result + + +def test_ttl_cached_does_not_store_failed_result(): + """A failed Result is returned but not stored; the next call re-invokes.""" + cache = MemoryCache(ttl_seconds=60) + calls = 0 + + @ttl_cached(cache) + def lookup(x): + nonlocal calls + calls += 1 + return Result.fail("boom") if calls == 1 else Result.ok(x) + + first = lookup(1) + assert not first.success + second = lookup(1) + assert second.success + assert second.data == 1 + assert calls == 2 + # The successful Result is now cached. + assert lookup(1) is second + assert calls == 2 + + +@pytest.mark.asyncio +async def test_async_ttl_cached_does_not_store_failed_result(): + """A failed Result is handed back but never pinned for the TTL.""" + cache = MemoryCache(ttl_seconds=60) + calls = 0 + + @async_ttl_cached(cache) + async def lookup(x): + nonlocal calls + calls += 1 + return Result.fail("rpc 500") if calls == 1 else Result.ok(x * 2) + + first = await lookup(4) + assert not first.success + assert first.error == "rpc 500" + + second = await lookup(4) + assert second.success + assert second.data == 8 + assert calls == 2 + + # Successful Result is cached from here on. + assert await lookup(4) is second + assert calls == 2 + + +@pytest.mark.asyncio +async def test_async_ttl_cached_stores_successful_result_and_plain_values(): + cache = MemoryCache(ttl_seconds=60) + calls = 0 + + @async_ttl_cached(cache) + async def ok_lookup(x): + nonlocal calls + calls += 1 + return Result.ok(x) + + @async_ttl_cached(cache) + async def plain_lookup(x): + nonlocal calls + calls += 1 + return x + + assert (await ok_lookup(1)).success + assert (await ok_lookup(1)).success + assert await plain_lookup(2) == 2 + assert await plain_lookup(2) == 2 + assert calls == 2 + + +@pytest.mark.asyncio +async def test_async_ttl_cached_stampede_waiters_receive_failed_result(): + """Coalesced waiters all get the same failed Result, and nothing is cached.""" + cache = MemoryCache(ttl_seconds=60) + calls = 0 + + @async_ttl_cached(cache) + async def failing(x): + nonlocal calls + calls += 1 + await asyncio.sleep(0.01) + return Result.fail("transient") + + results = await asyncio.gather(*[failing(9) for _ in range(4)]) + + assert calls == 1 + assert all(not r.success and r.error == "transient" for r in results) + # Next caller after the in-flight fetch retries instead of hitting a cached failure. + await failing(9) + assert calls == 2 def test_memory_cache_set_get(): diff --git a/tests/unit/utils/test_error_sanitizer.py b/tests/unit/utils/test_error_sanitizer.py index cbc37a0..dee364d 100644 --- a/tests/unit/utils/test_error_sanitizer.py +++ b/tests/unit/utils/test_error_sanitizer.py @@ -19,6 +19,13 @@ def test_sanitize_exception(self): assert "test context" in result assert "Invalid input parameter" in result + def test_sanitize_attribute_error(self): + """AttributeError maps to the generic 'Invalid operation' message.""" + error = AttributeError("'NoneType' object has no attribute 'get'") + result = sanitize_error_message(error, "test context") + assert "Invalid operation" in result + assert "NoneType" not in result + def test_remove_file_paths(self): """Test that file paths are removed.""" # The regex pattern matches paths starting with /Users, /home, etc. diff --git a/uv.lock b/uv.lock index 2d3c1ee..7627ef0 100644 --- a/uv.lock +++ b/uv.lock @@ -785,7 +785,7 @@ wheels = [ [[package]] name = "dexalot-sdk" -version = "0.6.1" +version = "0.6.2" source = { editable = "." } dependencies = [ { name = "aiohttp" },