|
| 1 | +import ast |
1 | 2 | from typing import Optional, TYPE_CHECKING |
2 | 3 |
|
3 | 4 | from async_substrate_interface.errors import ( |
|
58 | 59 | "UnknownSynapseError", |
59 | 60 | "UnstakeError", |
60 | 61 | "SHIELD_VALIDATION_ERRORS", |
| 62 | + "chain_error_from_substrate_exception", |
61 | 63 | "map_shield_error", |
62 | 64 | ] |
63 | 65 |
|
@@ -278,6 +280,57 @@ def __init__( |
278 | 280 | } |
279 | 281 |
|
280 | 282 |
|
| 283 | +_CUSTOM_ERROR_CODE_TO_EXCEPTION: dict[int, type["ChainError"]] = { |
| 284 | + 3: SubnetNotExists, |
| 285 | + 4: HotKeyAccountNotExists, |
| 286 | + 6: TxRateLimitExceeded, |
| 287 | + 25: NonAssociatedColdKey, |
| 288 | +} |
| 289 | + |
| 290 | + |
| 291 | +def _extract_custom_error_code(error: Exception) -> Optional[int]: |
| 292 | + """Walk a SubstrateRequestException's args looking for a transaction-pool |
| 293 | + validity error like ``{'error': {'code': 1010, ..., 'data': 'Custom error: N'}}`` |
| 294 | + and return ``N``. Returns ``None`` if the shape doesn't match.""" |
| 295 | + for arg in getattr(error, "args", ()): |
| 296 | + parsed = arg |
| 297 | + if isinstance(parsed, str): |
| 298 | + try: |
| 299 | + parsed = ast.literal_eval(parsed) |
| 300 | + except (ValueError, SyntaxError, MemoryError, RecursionError, TypeError): |
| 301 | + continue |
| 302 | + if not isinstance(parsed, dict): |
| 303 | + continue |
| 304 | + inner = parsed.get("error", parsed) |
| 305 | + if not isinstance(inner, dict): |
| 306 | + continue |
| 307 | + data = inner.get("data") |
| 308 | + if isinstance(data, str) and data.startswith("Custom error:"): |
| 309 | + try: |
| 310 | + return int(data.split(":", 1)[1].strip()) |
| 311 | + except ValueError: |
| 312 | + continue |
| 313 | + return None |
| 314 | + |
| 315 | + |
| 316 | +def chain_error_from_substrate_exception( |
| 317 | + error: SubstrateRequestException, |
| 318 | +) -> Optional["ChainError"]: |
| 319 | + """Translate a transaction-pool validation error into a typed |
| 320 | + :class:`ChainError`. Returns ``None`` when the exception doesn't carry a |
| 321 | + recognised ``Custom error: N`` code from subtensor's |
| 322 | + ``CustomTransactionError`` enum, so callers can keep the original.""" |
| 323 | + if isinstance(error, ChainError): |
| 324 | + return None |
| 325 | + code = _extract_custom_error_code(error) |
| 326 | + if code is None: |
| 327 | + return None |
| 328 | + exc_cls = _CUSTOM_ERROR_CODE_TO_EXCEPTION.get(code) |
| 329 | + if exc_cls is None: |
| 330 | + return None |
| 331 | + return exc_cls(*error.args) |
| 332 | + |
| 333 | + |
281 | 334 | def map_shield_error(raw_message: str) -> str: |
282 | 335 | """Map a raw shield validation error to a human-readable description. |
283 | 336 |
|
|
0 commit comments