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
8 changes: 6 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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 `"<chain> <symbol>: <msg>"` 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.

---

Expand Down Expand Up @@ -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).

---

Expand Down
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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(<sanitized message>)`.
- `get_chain_wallet_balances(chain)` and `get_all_chain_wallet_balances()` drop the
failed entry from `chain_balances` and append `"<chain> <symbol>: <message>"` 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:
Expand Down
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.6.1
0.6.2
2 changes: 1 addition & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
17 changes: 17 additions & 0 deletions docs/python-sdk-error-handling.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
48 changes: 47 additions & 1 deletion docs/python-sdk-remediation-plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -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, "<context>")`. 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.

---

Expand Down
17 changes: 16 additions & 1 deletion docs/python-sdk-user-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
6 changes: 6 additions & 0 deletions docs/sdk-caching.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
2 changes: 1 addition & 1 deletion src/dexalot_sdk/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
secrets_vault_set,
)

__version__ = "0.6.1"
__version__ = "0.6.2"


def get_version() -> str:
Expand Down
16 changes: 12 additions & 4 deletions src/dexalot_sdk/core/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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
Expand All @@ -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},
)

Expand Down
Loading
Loading