cryptascreen 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cryptascreen/__init__.py +61 -0
- cryptascreen/_util.py +111 -0
- cryptascreen/_version.py +3 -0
- cryptascreen/client.py +231 -0
- cryptascreen/config.py +48 -0
- cryptascreen/errors.py +217 -0
- cryptascreen/helpers.py +47 -0
- cryptascreen/operations.py +131 -0
- cryptascreen/resources/__init__.py +1 -0
- cryptascreen/resources/alerts.py +51 -0
- cryptascreen/resources/auth.py +36 -0
- cryptascreen/resources/capabilities.py +36 -0
- cryptascreen/resources/cases.py +198 -0
- cryptascreen/resources/compliance.py +116 -0
- cryptascreen/resources/graph.py +70 -0
- cryptascreen/resources/intelligence.py +69 -0
- cryptascreen/resources/monitoring.py +142 -0
- cryptascreen/resources/names.py +97 -0
- cryptascreen/resources/sanctions.py +50 -0
- cryptascreen/resources/screening.py +379 -0
- cryptascreen/resources/settings.py +115 -0
- cryptascreen/resources/webhooks.py +55 -0
- cryptascreen/retry.py +176 -0
- cryptascreen/signature.py +118 -0
- cryptascreen/types/__init__.py +313 -0
- cryptascreen/types/_account.py +199 -0
- cryptascreen/types/_models.py +1620 -0
- cryptascreen/types/cases.py +31 -0
- cryptascreen/types/common.py +17 -0
- cryptascreen/types/compliance.py +27 -0
- cryptascreen/types/graph.py +25 -0
- cryptascreen/types/intelligence.py +11 -0
- cryptascreen/types/names.py +39 -0
- cryptascreen/types/sanctions.py +13 -0
- cryptascreen/types/screening.py +73 -0
- cryptascreen/types/wallet.py +85 -0
- cryptascreen/types/webhooks.py +13 -0
- cryptascreen-0.2.0.dist-info/METADATA +305 -0
- cryptascreen-0.2.0.dist-info/RECORD +41 -0
- cryptascreen-0.2.0.dist-info/WHEEL +4 -0
- cryptascreen-0.2.0.dist-info/licenses/LICENSE +21 -0
cryptascreen/__init__.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""CryptaScreen Python SDK - official client for the CryptaScreen API.
|
|
2
|
+
|
|
3
|
+
Usage::
|
|
4
|
+
|
|
5
|
+
from cryptascreen import CryptaScreen
|
|
6
|
+
|
|
7
|
+
client = CryptaScreen(api_key="csk_...")
|
|
8
|
+
result = client.screening.screen_address({"address": "0x...", "chain": "ethereum"})
|
|
9
|
+
|
|
10
|
+
For async usage::
|
|
11
|
+
|
|
12
|
+
from cryptascreen import AsyncCryptaScreen
|
|
13
|
+
|
|
14
|
+
async with AsyncCryptaScreen(api_key="csk_...") as client:
|
|
15
|
+
result = await client.screening.screen_address({"address": "0x...", "chain": "ethereum"})
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from cryptascreen._util import generate_idempotency_key, is_terminal_job_status
|
|
19
|
+
from cryptascreen._version import __version__
|
|
20
|
+
from cryptascreen.client import AsyncCryptaScreen, CryptaScreen, CryptaScreenClient
|
|
21
|
+
from cryptascreen.errors import (
|
|
22
|
+
ApiKeyLimitReachedError,
|
|
23
|
+
AuthenticationError,
|
|
24
|
+
CryptaScreenError,
|
|
25
|
+
NotFoundError,
|
|
26
|
+
PlanLimitError,
|
|
27
|
+
QuotaExceededError,
|
|
28
|
+
RateLimitError,
|
|
29
|
+
SeatLimitReachedError,
|
|
30
|
+
ServicePausedError,
|
|
31
|
+
ValidationError,
|
|
32
|
+
)
|
|
33
|
+
from cryptascreen.signature import (
|
|
34
|
+
WebhookSignatureError,
|
|
35
|
+
compute_webhook_signature,
|
|
36
|
+
construct_webhook_event,
|
|
37
|
+
verify_webhook_signature,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
__all__ = [
|
|
41
|
+
"ApiKeyLimitReachedError",
|
|
42
|
+
"AsyncCryptaScreen",
|
|
43
|
+
"AuthenticationError",
|
|
44
|
+
"CryptaScreen",
|
|
45
|
+
"CryptaScreenClient",
|
|
46
|
+
"CryptaScreenError",
|
|
47
|
+
"NotFoundError",
|
|
48
|
+
"PlanLimitError",
|
|
49
|
+
"QuotaExceededError",
|
|
50
|
+
"RateLimitError",
|
|
51
|
+
"SeatLimitReachedError",
|
|
52
|
+
"ServicePausedError",
|
|
53
|
+
"ValidationError",
|
|
54
|
+
"WebhookSignatureError",
|
|
55
|
+
"__version__",
|
|
56
|
+
"compute_webhook_signature",
|
|
57
|
+
"construct_webhook_event",
|
|
58
|
+
"generate_idempotency_key",
|
|
59
|
+
"is_terminal_job_status",
|
|
60
|
+
"verify_webhook_signature",
|
|
61
|
+
]
|
cryptascreen/_util.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Small internal helpers shared by the resources."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import uuid
|
|
6
|
+
from typing import Any
|
|
7
|
+
from urllib.parse import quote
|
|
8
|
+
|
|
9
|
+
from pydantic import BaseModel
|
|
10
|
+
|
|
11
|
+
from cryptascreen.errors import ValidationError
|
|
12
|
+
from cryptascreen.types._models import ScreeningJobResultsPage
|
|
13
|
+
|
|
14
|
+
TERMINAL_JOB_STATUSES = ("COMPLETED", "PARTIAL", "FAILED", "CANCELLED")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _enc(value: str) -> str:
|
|
18
|
+
"""encodeURIComponent for a path segment."""
|
|
19
|
+
return quote(str(value), safe="-_.!~*'()")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _body(request: BaseModel | dict[str, Any]) -> dict[str, Any]:
|
|
23
|
+
if isinstance(request, BaseModel):
|
|
24
|
+
return request.model_dump(by_alias=True, exclude_none=True, mode="json")
|
|
25
|
+
return dict(request)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
_CHAIN_REQUIRED = "chain is required: an address does not identify its network"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _chain_required(field: str) -> ValidationError:
|
|
32
|
+
return ValidationError(
|
|
33
|
+
_CHAIN_REQUIRED,
|
|
34
|
+
{field: [_CHAIN_REQUIRED]},
|
|
35
|
+
None,
|
|
36
|
+
"CHAIN_REQUIRED",
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _blank(value: Any) -> bool:
|
|
41
|
+
return not isinstance(value, str) or not value.strip()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _require_chain(body: dict[str, Any]) -> dict[str, Any]:
|
|
45
|
+
"""Single screening: ``chain`` must be present and non-blank (no default network)."""
|
|
46
|
+
if _blank(body.get("chain")):
|
|
47
|
+
raise _chain_required("chain")
|
|
48
|
+
return body
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _require_chains(body: dict[str, Any]) -> dict[str, Any]:
|
|
52
|
+
"""Bulk screening: every address row needs a non-blank entry in ``chains``."""
|
|
53
|
+
addresses = body.get("addresses") or []
|
|
54
|
+
chains = body.get("chains")
|
|
55
|
+
if addresses and (not isinstance(chains, list) or not chains or any(map(_blank, chains))):
|
|
56
|
+
raise _chain_required("chains")
|
|
57
|
+
return body
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _query(**params: Any) -> dict[str, Any]:
|
|
61
|
+
"""Drop None, render booleans like axios (true/false); wire names are camelCase."""
|
|
62
|
+
out: dict[str, Any] = {}
|
|
63
|
+
for k, v in params.items():
|
|
64
|
+
if v is None:
|
|
65
|
+
continue
|
|
66
|
+
out[_camel(k)] = ("true" if v else "false") if isinstance(v, bool) else v
|
|
67
|
+
return out
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _camel(name: str) -> str:
|
|
71
|
+
head, *rest = name.split("_")
|
|
72
|
+
return head + "".join(p.capitalize() for p in rest)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def generate_idempotency_key() -> str:
|
|
76
|
+
"""Random idempotency key (RFC 4122 v4)."""
|
|
77
|
+
return str(uuid.uuid4())
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def is_terminal_job_status(status: str | None) -> bool:
|
|
81
|
+
"""Terminal job statuses (polling stops). Unknown future values are NOT terminal."""
|
|
82
|
+
return (status or "") in TERMINAL_JOB_STATUSES
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _normalise_job_results(data: Any, job_id: str, page: int, size: int) -> ScreeningJobResultsPage:
|
|
86
|
+
d = data if isinstance(data, dict) else {}
|
|
87
|
+
items: list[Any] = (
|
|
88
|
+
d["items"]
|
|
89
|
+
if isinstance(d.get("items"), list)
|
|
90
|
+
else d["content"]
|
|
91
|
+
if isinstance(d.get("content"), list)
|
|
92
|
+
else []
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
def num(*vals: Any, default: int) -> int:
|
|
96
|
+
for v in vals:
|
|
97
|
+
if isinstance(v, (int, float)) and not isinstance(v, bool):
|
|
98
|
+
return int(v)
|
|
99
|
+
return default
|
|
100
|
+
|
|
101
|
+
return ScreeningJobResultsPage.model_validate(
|
|
102
|
+
{
|
|
103
|
+
"jobId": d["jobId"] if isinstance(d.get("jobId"), str) else job_id,
|
|
104
|
+
"status": d["status"] if isinstance(d.get("status"), str) else None,
|
|
105
|
+
"items": items,
|
|
106
|
+
"page": num(d.get("page"), d.get("number"), default=page),
|
|
107
|
+
"size": num(d.get("size"), default=size),
|
|
108
|
+
"totalItems": num(d.get("totalItems"), d.get("totalElements"), default=len(items)),
|
|
109
|
+
"totalPages": num(d.get("totalPages"), default=1),
|
|
110
|
+
}
|
|
111
|
+
)
|
cryptascreen/_version.py
ADDED
cryptascreen/client.py
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
"""Main CryptaScreen SDK client - sync and async."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from types import TracebackType
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
from cryptascreen.config import Config, resolve_base_url
|
|
11
|
+
from cryptascreen.resources.alerts import AlertsResource, AsyncAlertsResource
|
|
12
|
+
from cryptascreen.resources.auth import AsyncAuthResource, AuthResource
|
|
13
|
+
from cryptascreen.resources.capabilities import AsyncCapabilitiesResource, CapabilitiesResource
|
|
14
|
+
from cryptascreen.resources.cases import AsyncCasesResource, CasesResource
|
|
15
|
+
from cryptascreen.resources.compliance import AsyncComplianceResource, ComplianceResource
|
|
16
|
+
from cryptascreen.resources.graph import AsyncGraphResource, GraphResource
|
|
17
|
+
from cryptascreen.resources.intelligence import AsyncIntelligenceResource, IntelligenceResource
|
|
18
|
+
from cryptascreen.resources.monitoring import AsyncMonitoringResource, MonitoringResource
|
|
19
|
+
from cryptascreen.resources.names import AsyncNamesResource, NamesResource
|
|
20
|
+
from cryptascreen.resources.sanctions import AsyncSanctionsResource, SanctionsResource
|
|
21
|
+
from cryptascreen.resources.screening import AsyncScreeningResource, ScreeningResource
|
|
22
|
+
from cryptascreen.resources.settings import AsyncSettingsResource, SettingsResource
|
|
23
|
+
from cryptascreen.resources.webhooks import AsyncWebhooksResource, WebhooksResource
|
|
24
|
+
from cryptascreen.retry import async_execute_with_retry, execute_with_retry
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _parse(response: httpx.Response, binary: bool) -> Any:
|
|
28
|
+
if binary:
|
|
29
|
+
return response.content
|
|
30
|
+
if response.status_code == 204 or not response.content:
|
|
31
|
+
return None
|
|
32
|
+
try:
|
|
33
|
+
return response.json()
|
|
34
|
+
except ValueError:
|
|
35
|
+
return response.text
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class HttpClient:
|
|
39
|
+
"""Synchronous HTTP client wrapper: auth headers, JSON, retry policy, error mapping."""
|
|
40
|
+
|
|
41
|
+
def __init__(self, config: Config, transport: httpx.BaseTransport | None = None) -> None:
|
|
42
|
+
self._config = config
|
|
43
|
+
self._client = httpx.Client(
|
|
44
|
+
base_url=config.base_url,
|
|
45
|
+
headers=config.get_headers(),
|
|
46
|
+
timeout=config.timeout,
|
|
47
|
+
transport=transport,
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
def request(
|
|
51
|
+
self,
|
|
52
|
+
method: str,
|
|
53
|
+
path: str,
|
|
54
|
+
*,
|
|
55
|
+
params: dict[str, Any] | None = None,
|
|
56
|
+
json: Any = None,
|
|
57
|
+
headers: dict[str, str] | None = None,
|
|
58
|
+
binary: bool = False,
|
|
59
|
+
) -> Any:
|
|
60
|
+
"""Send a request and return the parsed JSON (``None`` for an empty body, bytes when ``binary``)."""
|
|
61
|
+
|
|
62
|
+
def _send() -> httpx.Response:
|
|
63
|
+
return self._client.request(
|
|
64
|
+
method, path, params=params or None, json=json, headers=headers
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
return _parse(execute_with_retry(self._config, _send), binary)
|
|
68
|
+
|
|
69
|
+
def close(self) -> None:
|
|
70
|
+
"""Close the underlying HTTP client."""
|
|
71
|
+
self._client.close()
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class AsyncHttpClient:
|
|
75
|
+
"""Asynchronous HTTP client wrapper."""
|
|
76
|
+
|
|
77
|
+
def __init__(self, config: Config, transport: httpx.AsyncBaseTransport | None = None) -> None:
|
|
78
|
+
self._config = config
|
|
79
|
+
self._client = httpx.AsyncClient(
|
|
80
|
+
base_url=config.base_url,
|
|
81
|
+
headers=config.get_headers(),
|
|
82
|
+
timeout=config.timeout,
|
|
83
|
+
transport=transport,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
async def request(
|
|
87
|
+
self,
|
|
88
|
+
method: str,
|
|
89
|
+
path: str,
|
|
90
|
+
*,
|
|
91
|
+
params: dict[str, Any] | None = None,
|
|
92
|
+
json: Any = None,
|
|
93
|
+
headers: dict[str, str] | None = None,
|
|
94
|
+
binary: bool = False,
|
|
95
|
+
) -> Any:
|
|
96
|
+
"""Send an async request and return the parsed JSON."""
|
|
97
|
+
|
|
98
|
+
async def _send() -> httpx.Response:
|
|
99
|
+
return await self._client.request(
|
|
100
|
+
method, path, params=params or None, json=json, headers=headers
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
return _parse(await async_execute_with_retry(self._config, _send), binary)
|
|
104
|
+
|
|
105
|
+
async def close(self) -> None:
|
|
106
|
+
"""Close the underlying async HTTP client."""
|
|
107
|
+
await self._client.aclose()
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _config(
|
|
111
|
+
api_key: str,
|
|
112
|
+
base_url: str | None,
|
|
113
|
+
timeout: float,
|
|
114
|
+
max_retries: int,
|
|
115
|
+
retry_base_delay: float,
|
|
116
|
+
) -> Config:
|
|
117
|
+
if not api_key:
|
|
118
|
+
raise ValueError("api_key is required")
|
|
119
|
+
return Config(
|
|
120
|
+
api_key=api_key,
|
|
121
|
+
base_url=resolve_base_url(base_url),
|
|
122
|
+
timeout=timeout,
|
|
123
|
+
max_retries=max_retries,
|
|
124
|
+
retry_base_delay=retry_base_delay,
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class CryptaScreen:
|
|
129
|
+
"""Synchronous CryptaScreen client.
|
|
130
|
+
|
|
131
|
+
Usage::
|
|
132
|
+
|
|
133
|
+
from cryptascreen import CryptaScreen
|
|
134
|
+
|
|
135
|
+
client = CryptaScreen(api_key="csk_...")
|
|
136
|
+
result = client.screening.screen_address({"address": "0x...", "chain": "ethereum"})
|
|
137
|
+
|
|
138
|
+
Args:
|
|
139
|
+
api_key: Your CryptaScreen API key.
|
|
140
|
+
base_url: Base URL override (default: https://api.cryptascreen.com).
|
|
141
|
+
timeout: Request timeout in seconds (default: 30).
|
|
142
|
+
max_retries: Maximum retries on 429 / 5xx (default: 3).
|
|
143
|
+
retry_base_delay: Base backoff delay in seconds (default: 1).
|
|
144
|
+
"""
|
|
145
|
+
|
|
146
|
+
def __init__(
|
|
147
|
+
self,
|
|
148
|
+
api_key: str,
|
|
149
|
+
*,
|
|
150
|
+
base_url: str | None = None,
|
|
151
|
+
timeout: float = 30.0,
|
|
152
|
+
max_retries: int = 3,
|
|
153
|
+
retry_base_delay: float = 1.0,
|
|
154
|
+
) -> None:
|
|
155
|
+
self._config = _config(api_key, base_url, timeout, max_retries, retry_base_delay)
|
|
156
|
+
self._http = HttpClient(self._config)
|
|
157
|
+
self.screening = ScreeningResource(self._http)
|
|
158
|
+
self.sanctions = SanctionsResource(self._http)
|
|
159
|
+
self.names = NamesResource(self._http)
|
|
160
|
+
self.graph = GraphResource(self._http)
|
|
161
|
+
self.cases = CasesResource(self._http)
|
|
162
|
+
self.alerts = AlertsResource(self._http)
|
|
163
|
+
self.compliance = ComplianceResource(self._http)
|
|
164
|
+
self.intelligence = IntelligenceResource(self._http)
|
|
165
|
+
self.webhooks = WebhooksResource(self._http)
|
|
166
|
+
self.auth = AuthResource(self._http)
|
|
167
|
+
self.capabilities = CapabilitiesResource(self._http)
|
|
168
|
+
self.settings = SettingsResource(self._http)
|
|
169
|
+
self.monitoring = MonitoringResource(self._http)
|
|
170
|
+
|
|
171
|
+
def close(self) -> None:
|
|
172
|
+
"""Close the underlying HTTP client and release resources."""
|
|
173
|
+
self._http.close()
|
|
174
|
+
|
|
175
|
+
def __enter__(self) -> CryptaScreen: # noqa: PYI034
|
|
176
|
+
return self
|
|
177
|
+
|
|
178
|
+
def __exit__(
|
|
179
|
+
self,
|
|
180
|
+
exc_type: type[BaseException] | None,
|
|
181
|
+
exc_val: BaseException | None,
|
|
182
|
+
exc_tb: TracebackType | None,
|
|
183
|
+
) -> None:
|
|
184
|
+
self.close()
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
class AsyncCryptaScreen:
|
|
188
|
+
"""Asynchronous CryptaScreen client (``async with AsyncCryptaScreen(api_key=...) as client``)."""
|
|
189
|
+
|
|
190
|
+
def __init__(
|
|
191
|
+
self,
|
|
192
|
+
api_key: str,
|
|
193
|
+
*,
|
|
194
|
+
base_url: str | None = None,
|
|
195
|
+
timeout: float = 30.0,
|
|
196
|
+
max_retries: int = 3,
|
|
197
|
+
retry_base_delay: float = 1.0,
|
|
198
|
+
) -> None:
|
|
199
|
+
self._config = _config(api_key, base_url, timeout, max_retries, retry_base_delay)
|
|
200
|
+
self._http = AsyncHttpClient(self._config)
|
|
201
|
+
self.screening = AsyncScreeningResource(self._http)
|
|
202
|
+
self.sanctions = AsyncSanctionsResource(self._http)
|
|
203
|
+
self.names = AsyncNamesResource(self._http)
|
|
204
|
+
self.graph = AsyncGraphResource(self._http)
|
|
205
|
+
self.cases = AsyncCasesResource(self._http)
|
|
206
|
+
self.alerts = AsyncAlertsResource(self._http)
|
|
207
|
+
self.compliance = AsyncComplianceResource(self._http)
|
|
208
|
+
self.intelligence = AsyncIntelligenceResource(self._http)
|
|
209
|
+
self.webhooks = AsyncWebhooksResource(self._http)
|
|
210
|
+
self.auth = AsyncAuthResource(self._http)
|
|
211
|
+
self.capabilities = AsyncCapabilitiesResource(self._http)
|
|
212
|
+
self.settings = AsyncSettingsResource(self._http)
|
|
213
|
+
self.monitoring = AsyncMonitoringResource(self._http)
|
|
214
|
+
|
|
215
|
+
async def close(self) -> None:
|
|
216
|
+
"""Close the underlying async HTTP client and release resources."""
|
|
217
|
+
await self._http.close()
|
|
218
|
+
|
|
219
|
+
async def __aenter__(self) -> AsyncCryptaScreen: # noqa: PYI034
|
|
220
|
+
return self
|
|
221
|
+
|
|
222
|
+
async def __aexit__(
|
|
223
|
+
self,
|
|
224
|
+
exc_type: type[BaseException] | None,
|
|
225
|
+
exc_val: BaseException | None,
|
|
226
|
+
exc_tb: TracebackType | None,
|
|
227
|
+
) -> None:
|
|
228
|
+
await self.close()
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
CryptaScreenClient = CryptaScreen # name of the TypeScript SDK class
|
cryptascreen/config.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""SDK configuration."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
|
|
7
|
+
from cryptascreen._version import __version__
|
|
8
|
+
|
|
9
|
+
DEFAULT_BASE_URL = "https://api.cryptascreen.com"
|
|
10
|
+
# The one public host. It routes every request to the data region of the API key (csk_us_... / csk_eu_...).
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def resolve_base_url(base_url: str | None) -> str:
|
|
14
|
+
"""Pick the API host: explicit ``base_url`` (local stack, proxy) or the default host."""
|
|
15
|
+
return base_url or DEFAULT_BASE_URL
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class Config:
|
|
20
|
+
"""Configuration for the CryptaScreen SDK client.
|
|
21
|
+
|
|
22
|
+
Attributes:
|
|
23
|
+
api_key: Your CryptaScreen API key (``csk_...``).
|
|
24
|
+
base_url: Base URL for the CryptaScreen API.
|
|
25
|
+
timeout: Request timeout in seconds.
|
|
26
|
+
max_retries: Maximum retries on 429 (not quota) and 5xx.
|
|
27
|
+
retry_base_delay: Base delay in seconds for exponential backoff (1s, 2s, 4s ...).
|
|
28
|
+
retry_max_delay: Maximum delay in seconds between retries.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
api_key: str
|
|
32
|
+
base_url: str = DEFAULT_BASE_URL
|
|
33
|
+
timeout: float = 30.0
|
|
34
|
+
max_retries: int = 3
|
|
35
|
+
retry_base_delay: float = 1.0
|
|
36
|
+
retry_max_delay: float = 30.0
|
|
37
|
+
headers: dict[str, str] = field(default_factory=dict)
|
|
38
|
+
|
|
39
|
+
def get_headers(self) -> dict[str, str]:
|
|
40
|
+
"""Return the full set of headers for API requests."""
|
|
41
|
+
base = {
|
|
42
|
+
"X-API-Key": self.api_key,
|
|
43
|
+
"Content-Type": "application/json",
|
|
44
|
+
"Accept": "application/json",
|
|
45
|
+
"User-Agent": f"cryptascreen-python/{__version__}",
|
|
46
|
+
}
|
|
47
|
+
base.update(self.headers)
|
|
48
|
+
return base
|
cryptascreen/errors.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
"""Typed exceptions for the CryptaScreen SDK (same classes and codes as @cryptascreen/sdk)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
PLAN_LIMIT_CODES = (
|
|
8
|
+
"SEAT_LIMIT_REACHED",
|
|
9
|
+
"API_KEY_LIMIT_REACHED",
|
|
10
|
+
"MONITORED_WALLET_LIMIT_REACHED",
|
|
11
|
+
"BULK_LIMIT_REACHED",
|
|
12
|
+
"feature_not_in_plan",
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class CryptaScreenError(Exception):
|
|
17
|
+
"""Base exception for all CryptaScreen SDK errors.
|
|
18
|
+
|
|
19
|
+
Attributes:
|
|
20
|
+
message: Human-readable error message.
|
|
21
|
+
status: HTTP status code (0 when no response was received).
|
|
22
|
+
code: Machine code, e.g. ``AUTHENTICATION_ERROR``, ``VALIDATION_ERROR``, ``RATE_LIMIT_EXCEEDED``.
|
|
23
|
+
request_id: ``X-Request-Id`` of the response, if any.
|
|
24
|
+
details: Extra structured details.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(
|
|
28
|
+
self,
|
|
29
|
+
message: str,
|
|
30
|
+
status: int = 0,
|
|
31
|
+
code: str = "UNKNOWN_ERROR",
|
|
32
|
+
request_id: str | None = None,
|
|
33
|
+
details: dict[str, Any] | None = None,
|
|
34
|
+
) -> None:
|
|
35
|
+
super().__init__(message)
|
|
36
|
+
self.message = message
|
|
37
|
+
self.status = status
|
|
38
|
+
self.code = code
|
|
39
|
+
self.request_id = request_id
|
|
40
|
+
self.details = details
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def status_code(self) -> int:
|
|
44
|
+
"""Alias of :attr:`status`."""
|
|
45
|
+
return self.status
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class AuthenticationError(CryptaScreenError):
|
|
49
|
+
"""401 - invalid or missing API key."""
|
|
50
|
+
|
|
51
|
+
def __init__(
|
|
52
|
+
self, message: str = "Invalid or missing API key", request_id: str | None = None
|
|
53
|
+
) -> None:
|
|
54
|
+
super().__init__(message, 401, "AUTHENTICATION_ERROR", request_id)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class RateLimitError(CryptaScreenError):
|
|
58
|
+
"""429 rate limit (retried automatically before it is raised).
|
|
59
|
+
|
|
60
|
+
Attributes:
|
|
61
|
+
reset_at: When the limit is expected to reset (now + Retry-After).
|
|
62
|
+
retry_after_ms: Milliseconds to wait (Retry-After seconds, default 60000).
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
def __init__(self, reset_at: Any, retry_after_ms: int, request_id: str | None = None) -> None:
|
|
66
|
+
super().__init__(
|
|
67
|
+
f"Rate limit exceeded. Resets at {reset_at.isoformat()}",
|
|
68
|
+
429,
|
|
69
|
+
"RATE_LIMIT_EXCEEDED",
|
|
70
|
+
request_id,
|
|
71
|
+
)
|
|
72
|
+
self.reset_at = reset_at
|
|
73
|
+
self.retry_after_ms = retry_after_ms
|
|
74
|
+
|
|
75
|
+
@property
|
|
76
|
+
def retry_after(self) -> float:
|
|
77
|
+
"""Seconds to wait before retrying."""
|
|
78
|
+
return self.retry_after_ms / 1000
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class QuotaExceededError(CryptaScreenError):
|
|
82
|
+
"""429 ``quota_exceeded``: the plan's monthly screenings are used up. NOT a rate limit; never retried."""
|
|
83
|
+
|
|
84
|
+
def __init__(
|
|
85
|
+
self,
|
|
86
|
+
message: str,
|
|
87
|
+
request_id: str | None = None,
|
|
88
|
+
resets_at: str | None = None,
|
|
89
|
+
upgrade_url: str | None = None,
|
|
90
|
+
) -> None:
|
|
91
|
+
super().__init__(
|
|
92
|
+
message,
|
|
93
|
+
429,
|
|
94
|
+
"QUOTA_EXCEEDED",
|
|
95
|
+
request_id,
|
|
96
|
+
{"resetsAt": resets_at, "upgradeUrl": upgrade_url},
|
|
97
|
+
)
|
|
98
|
+
self.resets_at = resets_at
|
|
99
|
+
self.upgrade_url = upgrade_url
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class ServicePausedError(CryptaScreenError):
|
|
103
|
+
"""402 ``SERVICE_PAUSED``: a payment is overdue. Not retried."""
|
|
104
|
+
|
|
105
|
+
def __init__(
|
|
106
|
+
self,
|
|
107
|
+
message: str,
|
|
108
|
+
request_id: str | None = None,
|
|
109
|
+
subscription_status: str | None = None,
|
|
110
|
+
billing_url: str | None = None,
|
|
111
|
+
reason: str | None = None,
|
|
112
|
+
) -> None:
|
|
113
|
+
super().__init__(
|
|
114
|
+
message,
|
|
115
|
+
402,
|
|
116
|
+
"SERVICE_PAUSED",
|
|
117
|
+
request_id,
|
|
118
|
+
{
|
|
119
|
+
"subscriptionStatus": subscription_status,
|
|
120
|
+
"billingUrl": billing_url,
|
|
121
|
+
"reason": reason,
|
|
122
|
+
},
|
|
123
|
+
)
|
|
124
|
+
self.subscription_status = subscription_status
|
|
125
|
+
self.billing_url = billing_url
|
|
126
|
+
self.reason = reason
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class PlanLimitError(CryptaScreenError):
|
|
130
|
+
"""403 with a plan-limit code: an addition beyond the plan's entitlement was refused. Not retried."""
|
|
131
|
+
|
|
132
|
+
def __init__(
|
|
133
|
+
self,
|
|
134
|
+
message: str,
|
|
135
|
+
limit_code: str,
|
|
136
|
+
request_id: str | None = None,
|
|
137
|
+
used: int | None = None,
|
|
138
|
+
limit: int | None = None,
|
|
139
|
+
plan: str | None = None,
|
|
140
|
+
) -> None:
|
|
141
|
+
super().__init__(
|
|
142
|
+
message, 403, limit_code, request_id, {"used": used, "limit": limit, "plan": plan}
|
|
143
|
+
)
|
|
144
|
+
self.limit_code = limit_code
|
|
145
|
+
self.used = used
|
|
146
|
+
self.limit = limit
|
|
147
|
+
self.plan = plan
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class SeatLimitReachedError(PlanLimitError):
|
|
151
|
+
"""403 SEAT_LIMIT_REACHED."""
|
|
152
|
+
|
|
153
|
+
def __init__(
|
|
154
|
+
self,
|
|
155
|
+
message: str,
|
|
156
|
+
request_id: str | None = None,
|
|
157
|
+
used: int | None = None,
|
|
158
|
+
limit: int | None = None,
|
|
159
|
+
plan: str | None = None,
|
|
160
|
+
) -> None:
|
|
161
|
+
super().__init__(message, "SEAT_LIMIT_REACHED", request_id, used, limit, plan)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
class ApiKeyLimitReachedError(PlanLimitError):
|
|
165
|
+
"""403 API_KEY_LIMIT_REACHED."""
|
|
166
|
+
|
|
167
|
+
def __init__(
|
|
168
|
+
self,
|
|
169
|
+
message: str,
|
|
170
|
+
request_id: str | None = None,
|
|
171
|
+
used: int | None = None,
|
|
172
|
+
limit: int | None = None,
|
|
173
|
+
plan: str | None = None,
|
|
174
|
+
) -> None:
|
|
175
|
+
super().__init__(message, "API_KEY_LIMIT_REACHED", request_id, used, limit, plan)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
class NotFoundError(CryptaScreenError):
|
|
179
|
+
"""404 Not Found."""
|
|
180
|
+
|
|
181
|
+
def __init__(
|
|
182
|
+
self, resource: str = "Resource", id: str = "", request_id: str | None = None
|
|
183
|
+
) -> None:
|
|
184
|
+
super().__init__(f"{resource} not found: {id}", 404, "NOT_FOUND", request_id)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
class ValidationError(CryptaScreenError):
|
|
188
|
+
"""400 - request validation failed.
|
|
189
|
+
|
|
190
|
+
Attributes:
|
|
191
|
+
field_errors: ``{field: [messages]}``; bulk items appear as ``field[index]``.
|
|
192
|
+
validation_code: e.g. UNKNOWN_CHAIN, INVALID_ADDRESS_FORMAT, INVALID_CHECKSUM, INVALID_BULK_ITEMS.
|
|
193
|
+
items: Bulk: every invalid item (the whole request was rejected).
|
|
194
|
+
"""
|
|
195
|
+
|
|
196
|
+
def __init__(
|
|
197
|
+
self,
|
|
198
|
+
message: str,
|
|
199
|
+
field_errors: dict[str, list[str]] | None = None,
|
|
200
|
+
request_id: str | None = None,
|
|
201
|
+
validation_code: str | None = None,
|
|
202
|
+
items: list[dict[str, Any]] | None = None,
|
|
203
|
+
) -> None:
|
|
204
|
+
self.field_errors = field_errors or {}
|
|
205
|
+
self.validation_code = validation_code
|
|
206
|
+
self.items = items or []
|
|
207
|
+
super().__init__(
|
|
208
|
+
message,
|
|
209
|
+
400,
|
|
210
|
+
"VALIDATION_ERROR",
|
|
211
|
+
request_id,
|
|
212
|
+
{
|
|
213
|
+
"fieldErrors": self.field_errors,
|
|
214
|
+
"validationCode": validation_code,
|
|
215
|
+
"items": self.items,
|
|
216
|
+
},
|
|
217
|
+
)
|