nozk.py 0.1.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.
- nozk/__init__.py +128 -0
- nozk/_codec.py +227 -0
- nozk/_endpoints.py +263 -0
- nozk/_resources.py +163 -0
- nozk/_transport.py +136 -0
- nozk/client.py +295 -0
- nozk/errors.py +95 -0
- nozk/models/__init__.py +100 -0
- nozk/models/_base.py +56 -0
- nozk/models/crypto.py +39 -0
- nozk/models/market.py +130 -0
- nozk/models/me.py +121 -0
- nozk/models/params.py +122 -0
- nozk/py.typed +0 -0
- nozk_py-0.1.0.dist-info/METADATA +181 -0
- nozk_py-0.1.0.dist-info/RECORD +18 -0
- nozk_py-0.1.0.dist-info/WHEEL +4 -0
- nozk_py-0.1.0.dist-info/licenses/LICENSE +21 -0
nozk/__init__.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""Nozk MC Public API Python client (sync & async)."""
|
|
2
|
+
|
|
3
|
+
from nozk.client import AsyncNozkClient, NozkClient
|
|
4
|
+
from nozk.errors import (
|
|
5
|
+
AuthenticationError,
|
|
6
|
+
BadRequestError,
|
|
7
|
+
ErrorCode,
|
|
8
|
+
NotFoundError,
|
|
9
|
+
NozkAPIError,
|
|
10
|
+
NozkConnectionError,
|
|
11
|
+
NozkError,
|
|
12
|
+
NozkResponseError,
|
|
13
|
+
RateLimitError,
|
|
14
|
+
ScopeError,
|
|
15
|
+
UpstreamError,
|
|
16
|
+
)
|
|
17
|
+
from nozk.models import (
|
|
18
|
+
Bond,
|
|
19
|
+
CorpAffiliation,
|
|
20
|
+
CorpRole,
|
|
21
|
+
CryptoCandle,
|
|
22
|
+
CryptoCoin,
|
|
23
|
+
CryptoCoinDetail,
|
|
24
|
+
CryptoState,
|
|
25
|
+
Deposit,
|
|
26
|
+
GameParams,
|
|
27
|
+
IndexPoint,
|
|
28
|
+
ItemDetail,
|
|
29
|
+
Land,
|
|
30
|
+
LandClaim,
|
|
31
|
+
LandClaimStatus,
|
|
32
|
+
LandKindCount,
|
|
33
|
+
LicenseRank,
|
|
34
|
+
LicenseRef,
|
|
35
|
+
MarketItem,
|
|
36
|
+
MarketSummary,
|
|
37
|
+
Me,
|
|
38
|
+
NozkModel,
|
|
39
|
+
ParamBound,
|
|
40
|
+
ParamCategory,
|
|
41
|
+
ParamGroup,
|
|
42
|
+
ParamRow,
|
|
43
|
+
ParamSection,
|
|
44
|
+
ParamTable,
|
|
45
|
+
ParamTableRow,
|
|
46
|
+
ParamValue,
|
|
47
|
+
PriceCandle,
|
|
48
|
+
Property,
|
|
49
|
+
RankingEntry,
|
|
50
|
+
RateLimit,
|
|
51
|
+
ResponseMeta,
|
|
52
|
+
Room,
|
|
53
|
+
TeamAffiliation,
|
|
54
|
+
TeamRole,
|
|
55
|
+
Trade,
|
|
56
|
+
TradeSide,
|
|
57
|
+
TreasuryFlowItem,
|
|
58
|
+
TreasuryFlowRow,
|
|
59
|
+
TreasuryFlows,
|
|
60
|
+
TreasuryPeriod,
|
|
61
|
+
TreasuryPeriodKey,
|
|
62
|
+
Wallet,
|
|
63
|
+
Warehouse,
|
|
64
|
+
WarehouseItem,
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
__all__ = [
|
|
68
|
+
"AsyncNozkClient",
|
|
69
|
+
"AuthenticationError",
|
|
70
|
+
"BadRequestError",
|
|
71
|
+
"Bond",
|
|
72
|
+
"CorpAffiliation",
|
|
73
|
+
"CorpRole",
|
|
74
|
+
"CryptoCandle",
|
|
75
|
+
"CryptoCoin",
|
|
76
|
+
"CryptoCoinDetail",
|
|
77
|
+
"CryptoState",
|
|
78
|
+
"Deposit",
|
|
79
|
+
"ErrorCode",
|
|
80
|
+
"GameParams",
|
|
81
|
+
"IndexPoint",
|
|
82
|
+
"ItemDetail",
|
|
83
|
+
"Land",
|
|
84
|
+
"LandClaim",
|
|
85
|
+
"LandClaimStatus",
|
|
86
|
+
"LandKindCount",
|
|
87
|
+
"LicenseRank",
|
|
88
|
+
"LicenseRef",
|
|
89
|
+
"MarketItem",
|
|
90
|
+
"MarketSummary",
|
|
91
|
+
"Me",
|
|
92
|
+
"NotFoundError",
|
|
93
|
+
"NozkAPIError",
|
|
94
|
+
"NozkClient",
|
|
95
|
+
"NozkConnectionError",
|
|
96
|
+
"NozkError",
|
|
97
|
+
"NozkModel",
|
|
98
|
+
"NozkResponseError",
|
|
99
|
+
"ParamBound",
|
|
100
|
+
"ParamCategory",
|
|
101
|
+
"ParamGroup",
|
|
102
|
+
"ParamRow",
|
|
103
|
+
"ParamSection",
|
|
104
|
+
"ParamTable",
|
|
105
|
+
"ParamTableRow",
|
|
106
|
+
"ParamValue",
|
|
107
|
+
"PriceCandle",
|
|
108
|
+
"Property",
|
|
109
|
+
"RankingEntry",
|
|
110
|
+
"RateLimit",
|
|
111
|
+
"RateLimitError",
|
|
112
|
+
"ResponseMeta",
|
|
113
|
+
"Room",
|
|
114
|
+
"ScopeError",
|
|
115
|
+
"TeamAffiliation",
|
|
116
|
+
"TeamRole",
|
|
117
|
+
"Trade",
|
|
118
|
+
"TradeSide",
|
|
119
|
+
"TreasuryFlowItem",
|
|
120
|
+
"TreasuryFlowRow",
|
|
121
|
+
"TreasuryFlows",
|
|
122
|
+
"TreasuryPeriod",
|
|
123
|
+
"TreasuryPeriodKey",
|
|
124
|
+
"UpstreamError",
|
|
125
|
+
"Wallet",
|
|
126
|
+
"Warehouse",
|
|
127
|
+
"WarehouseItem",
|
|
128
|
+
]
|
nozk/_codec.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
"""Sans-I/O protocol codec: request specs, header parsing, JSON decoding, and error mapping.
|
|
2
|
+
|
|
3
|
+
This module intentionally has zero dependency on `httpx` or any I/O library.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import datetime as dt
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from typing import TYPE_CHECKING, Generic, TypeVar
|
|
11
|
+
|
|
12
|
+
from pydantic import TypeAdapter, ValidationError
|
|
13
|
+
|
|
14
|
+
from nozk.errors import (
|
|
15
|
+
AuthenticationError,
|
|
16
|
+
BadRequestError,
|
|
17
|
+
ErrorCode,
|
|
18
|
+
NotFoundError,
|
|
19
|
+
NozkAPIError,
|
|
20
|
+
NozkResponseError,
|
|
21
|
+
RateLimitError,
|
|
22
|
+
ScopeError,
|
|
23
|
+
UpstreamError,
|
|
24
|
+
)
|
|
25
|
+
from nozk.models._base import NozkModel, RateLimit, ResponseMeta
|
|
26
|
+
|
|
27
|
+
if TYPE_CHECKING:
|
|
28
|
+
from collections.abc import Callable, Mapping
|
|
29
|
+
|
|
30
|
+
T = TypeVar("T")
|
|
31
|
+
|
|
32
|
+
_ERROR_CLASS_BY_CODE: dict[ErrorCode, type[NozkAPIError]] = {
|
|
33
|
+
ErrorCode.UNAUTHORIZED: AuthenticationError,
|
|
34
|
+
ErrorCode.INVALID_API_KEY: AuthenticationError,
|
|
35
|
+
ErrorCode.INSUFFICIENT_SCOPE: ScopeError,
|
|
36
|
+
ErrorCode.ITEM_NOT_FOUND: NotFoundError,
|
|
37
|
+
ErrorCode.COIN_NOT_FOUND: NotFoundError,
|
|
38
|
+
ErrorCode.NOT_FOUND: NotFoundError,
|
|
39
|
+
ErrorCode.VALIDATION: BadRequestError,
|
|
40
|
+
ErrorCode.RANGE_TOO_WIDE: BadRequestError,
|
|
41
|
+
ErrorCode.RANGE_OUT_OF_BOUNDS: BadRequestError,
|
|
42
|
+
ErrorCode.RATE_LIMITED: RateLimitError,
|
|
43
|
+
ErrorCode.UPSTREAM_ERROR: UpstreamError,
|
|
44
|
+
ErrorCode.UPSTREAM_UNAVAILABLE: UpstreamError,
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
_ERROR_CLASS_BY_STATUS: dict[int, type[NozkAPIError]] = {
|
|
48
|
+
400: BadRequestError,
|
|
49
|
+
401: AuthenticationError,
|
|
50
|
+
403: ScopeError,
|
|
51
|
+
404: NotFoundError,
|
|
52
|
+
422: BadRequestError,
|
|
53
|
+
429: RateLimitError,
|
|
54
|
+
502: UpstreamError,
|
|
55
|
+
503: UpstreamError,
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class _RawItemsEnvelope(NozkModel):
|
|
60
|
+
"""Internal envelope matching Nozk list responses (`{"items": [...]}`)."""
|
|
61
|
+
|
|
62
|
+
items: list[object]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class _ErrorBody(NozkModel):
|
|
66
|
+
code: str
|
|
67
|
+
message: str
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class _ErrorEnvelope(NozkModel):
|
|
71
|
+
error: _ErrorBody
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass(frozen=True, slots=True)
|
|
75
|
+
class RequestSpec(Generic[T]):
|
|
76
|
+
"""Immutable Sans-I/O description of a single GET request and its decoder."""
|
|
77
|
+
|
|
78
|
+
path: str
|
|
79
|
+
params: tuple[tuple[str, str], ...]
|
|
80
|
+
decoder: Callable[[bytes], T]
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@dataclass(frozen=True, slots=True)
|
|
84
|
+
class RawResponse:
|
|
85
|
+
"""Immutable Sans-I/O representation of an HTTP response."""
|
|
86
|
+
|
|
87
|
+
path: str
|
|
88
|
+
status_code: int
|
|
89
|
+
headers: Mapping[str, str]
|
|
90
|
+
content: bytes
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def make_model_decoder(model: type[T]) -> Callable[[bytes], T]:
|
|
94
|
+
"""Build a pure bytes-to-model decoder for a single-object endpoint."""
|
|
95
|
+
adapter: TypeAdapter[T] = TypeAdapter(model)
|
|
96
|
+
return adapter.validate_json
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def make_items_decoder(item_model: type[T]) -> Callable[[bytes], list[T]]:
|
|
100
|
+
"""Build a pure bytes-to-list decoder for a `{"items": [...]}` list endpoint."""
|
|
101
|
+
item_adapter: TypeAdapter[T] = TypeAdapter(item_model)
|
|
102
|
+
|
|
103
|
+
def _decode(raw: bytes) -> list[T]:
|
|
104
|
+
envelope = _RawItemsEnvelope.model_validate_json(raw)
|
|
105
|
+
return [item_adapter.validate_python(entry) for entry in envelope.items]
|
|
106
|
+
|
|
107
|
+
return _decode
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def format_timestamp(value: dt.datetime | str) -> str:
|
|
111
|
+
"""Format a datetime (or ISO string) into UTC ISO 8601 with trailing `Z`.
|
|
112
|
+
|
|
113
|
+
Naive datetimes are treated as UTC per the Nozk API contract.
|
|
114
|
+
Microsecond precision is preserved when non-zero (required for trade cursors).
|
|
115
|
+
"""
|
|
116
|
+
if isinstance(value, str):
|
|
117
|
+
cleaned = value.strip()
|
|
118
|
+
if not cleaned:
|
|
119
|
+
raise ValueError("Timestamp string must not be empty.")
|
|
120
|
+
return cleaned
|
|
121
|
+
|
|
122
|
+
aware = value.replace(tzinfo=dt.UTC) if value.tzinfo is None else value.astimezone(dt.UTC)
|
|
123
|
+
return aware.isoformat().replace("+00:00", "Z")
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _lower_headers(headers: Mapping[str, str]) -> dict[str, str]:
|
|
127
|
+
return {k.lower(): v for k, v in headers.items()}
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def parse_rate_limit(headers: Mapping[str, str]) -> RateLimit | None:
|
|
131
|
+
"""Parse `X-RateLimit-*` response headers into a `RateLimit`, or `None` if absent."""
|
|
132
|
+
lowered = _lower_headers(headers)
|
|
133
|
+
required = (
|
|
134
|
+
"x-ratelimit-limit",
|
|
135
|
+
"x-ratelimit-remaining",
|
|
136
|
+
"x-ratelimit-reset",
|
|
137
|
+
"x-ratelimit-limit-day",
|
|
138
|
+
"x-ratelimit-remaining-day",
|
|
139
|
+
)
|
|
140
|
+
if not all(key in lowered for key in required):
|
|
141
|
+
return None
|
|
142
|
+
try:
|
|
143
|
+
reset_unix = int(lowered["x-ratelimit-reset"])
|
|
144
|
+
return RateLimit(
|
|
145
|
+
limit=int(lowered["x-ratelimit-limit"]),
|
|
146
|
+
remaining=int(lowered["x-ratelimit-remaining"]),
|
|
147
|
+
reset=dt.datetime.fromtimestamp(reset_unix, tz=dt.UTC),
|
|
148
|
+
limit_day=int(lowered["x-ratelimit-limit-day"]),
|
|
149
|
+
remaining_day=int(lowered["x-ratelimit-remaining-day"]),
|
|
150
|
+
)
|
|
151
|
+
except (ValueError, OverflowError, OSError):
|
|
152
|
+
return None
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def parse_retry_after(headers: Mapping[str, str]) -> int | None:
|
|
156
|
+
"""Parse integer seconds from `Retry-After`, returning `None` if missing or non-numeric."""
|
|
157
|
+
lowered = _lower_headers(headers)
|
|
158
|
+
raw = lowered.get("retry-after")
|
|
159
|
+
if raw is None:
|
|
160
|
+
return None
|
|
161
|
+
try:
|
|
162
|
+
return int(raw.strip())
|
|
163
|
+
except ValueError:
|
|
164
|
+
return None
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def parse_response_meta(raw: RawResponse) -> ResponseMeta:
|
|
168
|
+
"""Extract per-response metadata (`rate_limit`, `is_stale`) from a `RawResponse`."""
|
|
169
|
+
lowered = _lower_headers(raw.headers)
|
|
170
|
+
is_stale = lowered.get("x-cache", "").strip().lower() == "stale"
|
|
171
|
+
return ResponseMeta(
|
|
172
|
+
path=raw.path,
|
|
173
|
+
status_code=raw.status_code,
|
|
174
|
+
is_stale=is_stale,
|
|
175
|
+
rate_limit=parse_rate_limit(lowered),
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def decode_error(raw: RawResponse, *, rate_limit: RateLimit | None) -> NozkAPIError:
|
|
180
|
+
"""Decode an HTTP >= 400 response into the matching `NozkAPIError` subclass.
|
|
181
|
+
|
|
182
|
+
Raises `NozkResponseError` if the error body is not valid structured JSON.
|
|
183
|
+
"""
|
|
184
|
+
try:
|
|
185
|
+
envelope = _ErrorEnvelope.model_validate_json(raw.content)
|
|
186
|
+
except ValidationError as exc:
|
|
187
|
+
raise NozkResponseError(
|
|
188
|
+
f"Invalid or non-JSON error body for HTTP {raw.status_code} on {raw.path}.",
|
|
189
|
+
status_code=raw.status_code,
|
|
190
|
+
) from exc
|
|
191
|
+
|
|
192
|
+
parsed_code: ErrorCode | str
|
|
193
|
+
try:
|
|
194
|
+
parsed_code = ErrorCode(envelope.error.code)
|
|
195
|
+
except ValueError:
|
|
196
|
+
parsed_code = envelope.error.code
|
|
197
|
+
|
|
198
|
+
exc_cls: type[NozkAPIError]
|
|
199
|
+
if isinstance(parsed_code, ErrorCode) and parsed_code in _ERROR_CLASS_BY_CODE:
|
|
200
|
+
exc_cls = _ERROR_CLASS_BY_CODE[parsed_code]
|
|
201
|
+
else:
|
|
202
|
+
exc_cls = _ERROR_CLASS_BY_STATUS.get(raw.status_code, NozkAPIError)
|
|
203
|
+
|
|
204
|
+
return exc_cls(
|
|
205
|
+
status_code=raw.status_code,
|
|
206
|
+
code=parsed_code,
|
|
207
|
+
message=envelope.error.message,
|
|
208
|
+
retry_after=parse_retry_after(raw.headers),
|
|
209
|
+
rate_limit=rate_limit,
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def decode_response(spec: RequestSpec[T], raw: RawResponse) -> tuple[T, ResponseMeta]:
|
|
214
|
+
"""Decode a `RawResponse` according to `spec`, raising structured errors on failure."""
|
|
215
|
+
meta = parse_response_meta(raw)
|
|
216
|
+
if raw.status_code >= 400:
|
|
217
|
+
raise decode_error(raw, rate_limit=meta.rate_limit)
|
|
218
|
+
|
|
219
|
+
try:
|
|
220
|
+
data = spec.decoder(raw.content)
|
|
221
|
+
except ValidationError as exc:
|
|
222
|
+
raise NozkResponseError(
|
|
223
|
+
f"Failed to parse response for {raw.path}: {exc}",
|
|
224
|
+
status_code=raw.status_code,
|
|
225
|
+
) from exc
|
|
226
|
+
|
|
227
|
+
return data, meta
|
nozk/_endpoints.py
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
"""Sans-I/O single source of truth for all 17 Nozk API endpoints and cursor helpers.
|
|
2
|
+
|
|
3
|
+
This module intentionally has zero dependency on `httpx` or any I/O library.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import TYPE_CHECKING
|
|
10
|
+
from urllib.parse import quote
|
|
11
|
+
|
|
12
|
+
from nozk._codec import (
|
|
13
|
+
RequestSpec,
|
|
14
|
+
format_timestamp,
|
|
15
|
+
make_items_decoder,
|
|
16
|
+
make_model_decoder,
|
|
17
|
+
)
|
|
18
|
+
from nozk.models.crypto import CryptoCandle, CryptoCoin, CryptoCoinDetail
|
|
19
|
+
from nozk.models.market import (
|
|
20
|
+
IndexPoint,
|
|
21
|
+
ItemDetail,
|
|
22
|
+
MarketItem,
|
|
23
|
+
MarketSummary,
|
|
24
|
+
PriceCandle,
|
|
25
|
+
RankingEntry,
|
|
26
|
+
Trade,
|
|
27
|
+
TreasuryFlows,
|
|
28
|
+
TreasuryPeriodKey,
|
|
29
|
+
)
|
|
30
|
+
from nozk.models.me import Me, Property, Wallet, Warehouse
|
|
31
|
+
from nozk.models.params import GameParams
|
|
32
|
+
|
|
33
|
+
if TYPE_CHECKING:
|
|
34
|
+
import datetime as dt
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True, slots=True)
|
|
38
|
+
class EndpointContract:
|
|
39
|
+
"""Declarative metadata for OpenAPI drift contract testing."""
|
|
40
|
+
|
|
41
|
+
path_template: str
|
|
42
|
+
query_params: frozenset[str] = frozenset()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
ENDPOINT_CONTRACTS: tuple[EndpointContract, ...] = (
|
|
46
|
+
EndpointContract("/v1/market"),
|
|
47
|
+
EndpointContract("/v1/items/{item_key}"),
|
|
48
|
+
EndpointContract("/v1/items/{item_key}/history", frozenset({"from", "to"})),
|
|
49
|
+
EndpointContract("/v1/trades", frozenset({"item", "limit", "before", "before_id"})),
|
|
50
|
+
EndpointContract("/v1/indices/history", frozenset({"days"})),
|
|
51
|
+
EndpointContract("/v1/summary"),
|
|
52
|
+
EndpointContract("/v1/rankings"),
|
|
53
|
+
EndpointContract("/v1/treasury/flows", frozenset({"period"})),
|
|
54
|
+
EndpointContract("/v1/params", frozenset({"category"})),
|
|
55
|
+
EndpointContract("/v1/crypto"),
|
|
56
|
+
EndpointContract("/v1/crypto/{code}"),
|
|
57
|
+
EndpointContract("/v1/crypto/{code}/candles", frozenset({"limit"})),
|
|
58
|
+
EndpointContract("/v1/me"),
|
|
59
|
+
EndpointContract("/v1/me/warehouse"),
|
|
60
|
+
EndpointContract("/v1/me/wallet"),
|
|
61
|
+
EndpointContract("/v1/me/trades", frozenset({"limit", "before", "before_id"})),
|
|
62
|
+
EndpointContract("/v1/me/property"),
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
# Pre-built immutable decoders (constructed once at import time).
|
|
66
|
+
_DECODE_MARKET = make_items_decoder(MarketItem)
|
|
67
|
+
_DECODE_ITEM = make_model_decoder(ItemDetail)
|
|
68
|
+
_DECODE_PRICE_CANDLES = make_items_decoder(PriceCandle)
|
|
69
|
+
_DECODE_TRADES = make_items_decoder(Trade)
|
|
70
|
+
_DECODE_INDICES = make_items_decoder(IndexPoint)
|
|
71
|
+
_DECODE_SUMMARY = make_model_decoder(MarketSummary)
|
|
72
|
+
_DECODE_RANKINGS = make_items_decoder(RankingEntry)
|
|
73
|
+
_DECODE_TREASURY = make_model_decoder(TreasuryFlows)
|
|
74
|
+
_DECODE_PARAMS = make_model_decoder(GameParams)
|
|
75
|
+
_DECODE_CRYPTO_LIST = make_items_decoder(CryptoCoin)
|
|
76
|
+
_DECODE_CRYPTO_DETAIL = make_model_decoder(CryptoCoinDetail)
|
|
77
|
+
_DECODE_CRYPTO_CANDLES = make_items_decoder(CryptoCandle)
|
|
78
|
+
_DECODE_ME = make_model_decoder(Me)
|
|
79
|
+
_DECODE_WAREHOUSE = make_model_decoder(Warehouse)
|
|
80
|
+
_DECODE_WALLET = make_model_decoder(Wallet)
|
|
81
|
+
_DECODE_PROPERTY = make_model_decoder(Property)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _normalize_path_key(value: str, *, name: str) -> str:
|
|
85
|
+
cleaned = value.strip()
|
|
86
|
+
if not cleaned:
|
|
87
|
+
raise ValueError(f"{name} must not be empty.")
|
|
88
|
+
return quote(cleaned.upper(), safe="")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _build_trade_query(
|
|
92
|
+
*,
|
|
93
|
+
item: str | None = None,
|
|
94
|
+
limit: int | None = None,
|
|
95
|
+
before: dt.datetime | str | None = None,
|
|
96
|
+
before_id: int | None = None,
|
|
97
|
+
) -> tuple[tuple[str, str], ...]:
|
|
98
|
+
if before_id is not None and before is None:
|
|
99
|
+
raise ValueError("before_id cannot be specified without before.")
|
|
100
|
+
|
|
101
|
+
params: list[tuple[str, str]] = []
|
|
102
|
+
if item is not None:
|
|
103
|
+
cleaned_item = item.strip()
|
|
104
|
+
if not cleaned_item:
|
|
105
|
+
raise ValueError("item must not be empty when specified.")
|
|
106
|
+
params.append(("item", cleaned_item.upper()))
|
|
107
|
+
if limit is not None:
|
|
108
|
+
params.append(("limit", str(limit)))
|
|
109
|
+
if before is not None:
|
|
110
|
+
params.append(("before", format_timestamp(before)))
|
|
111
|
+
if before_id is not None:
|
|
112
|
+
params.append(("before_id", str(before_id)))
|
|
113
|
+
return tuple(params)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
# --- Market & Economy endpoints (9) ---
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def build_market_request() -> RequestSpec[list[MarketItem]]:
|
|
120
|
+
return RequestSpec(path="/v1/market", params=(), decoder=_DECODE_MARKET)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def build_item_request(item_key: str) -> RequestSpec[ItemDetail]:
|
|
124
|
+
key = _normalize_path_key(item_key, name="item_key")
|
|
125
|
+
return RequestSpec(path=f"/v1/items/{key}", params=(), decoder=_DECODE_ITEM)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def build_item_history_request(
|
|
129
|
+
item_key: str,
|
|
130
|
+
*,
|
|
131
|
+
from_: dt.datetime | str | None = None,
|
|
132
|
+
to: dt.datetime | str | None = None,
|
|
133
|
+
) -> RequestSpec[list[PriceCandle]]:
|
|
134
|
+
key = _normalize_path_key(item_key, name="item_key")
|
|
135
|
+
params: list[tuple[str, str]] = []
|
|
136
|
+
if from_ is not None:
|
|
137
|
+
params.append(("from", format_timestamp(from_)))
|
|
138
|
+
if to is not None:
|
|
139
|
+
params.append(("to", format_timestamp(to)))
|
|
140
|
+
return RequestSpec(
|
|
141
|
+
path=f"/v1/items/{key}/history",
|
|
142
|
+
params=tuple(params),
|
|
143
|
+
decoder=_DECODE_PRICE_CANDLES,
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def build_trades_request(
|
|
148
|
+
*,
|
|
149
|
+
item: str | None = None,
|
|
150
|
+
limit: int | None = None,
|
|
151
|
+
before: dt.datetime | str | None = None,
|
|
152
|
+
before_id: int | None = None,
|
|
153
|
+
) -> RequestSpec[list[Trade]]:
|
|
154
|
+
return RequestSpec(
|
|
155
|
+
path="/v1/trades",
|
|
156
|
+
params=_build_trade_query(item=item, limit=limit, before=before, before_id=before_id),
|
|
157
|
+
decoder=_DECODE_TRADES,
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def build_indices_history_request(*, days: int | None = None) -> RequestSpec[list[IndexPoint]]:
|
|
162
|
+
params = (("days", str(days)),) if days is not None else ()
|
|
163
|
+
return RequestSpec(path="/v1/indices/history", params=params, decoder=_DECODE_INDICES)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def build_summary_request() -> RequestSpec[MarketSummary]:
|
|
167
|
+
return RequestSpec(path="/v1/summary", params=(), decoder=_DECODE_SUMMARY)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def build_rankings_request() -> RequestSpec[list[RankingEntry]]:
|
|
171
|
+
return RequestSpec(path="/v1/rankings", params=(), decoder=_DECODE_RANKINGS)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def build_treasury_flows_request(
|
|
175
|
+
*,
|
|
176
|
+
period: TreasuryPeriodKey | str | None = None,
|
|
177
|
+
) -> RequestSpec[TreasuryFlows]:
|
|
178
|
+
params: tuple[tuple[str, str], ...] = ()
|
|
179
|
+
if period is not None:
|
|
180
|
+
cleaned = period.strip()
|
|
181
|
+
if not cleaned:
|
|
182
|
+
raise ValueError("period must not be empty when specified.")
|
|
183
|
+
params = (("period", cleaned),)
|
|
184
|
+
return RequestSpec(path="/v1/treasury/flows", params=params, decoder=_DECODE_TREASURY)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def build_params_request(*, category: str | None = None) -> RequestSpec[GameParams]:
|
|
188
|
+
params: tuple[tuple[str, str], ...] = ()
|
|
189
|
+
if category is not None:
|
|
190
|
+
cleaned = category.strip()
|
|
191
|
+
if not cleaned:
|
|
192
|
+
raise ValueError("category must not be empty when specified.")
|
|
193
|
+
params = (("category", cleaned),)
|
|
194
|
+
return RequestSpec(path="/v1/params", params=params, decoder=_DECODE_PARAMS)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
# --- Crypto endpoints (3) ---
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def build_crypto_list_request() -> RequestSpec[list[CryptoCoin]]:
|
|
201
|
+
return RequestSpec(path="/v1/crypto", params=(), decoder=_DECODE_CRYPTO_LIST)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def build_crypto_detail_request(code: str) -> RequestSpec[CryptoCoinDetail]:
|
|
205
|
+
norm = _normalize_path_key(code, name="code")
|
|
206
|
+
return RequestSpec(path=f"/v1/crypto/{norm}", params=(), decoder=_DECODE_CRYPTO_DETAIL)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def build_crypto_candles_request(
|
|
210
|
+
code: str,
|
|
211
|
+
*,
|
|
212
|
+
limit: int | None = None,
|
|
213
|
+
) -> RequestSpec[list[CryptoCandle]]:
|
|
214
|
+
norm = _normalize_path_key(code, name="code")
|
|
215
|
+
params = (("limit", str(limit)),) if limit is not None else ()
|
|
216
|
+
return RequestSpec(
|
|
217
|
+
path=f"/v1/crypto/{norm}/candles",
|
|
218
|
+
params=params,
|
|
219
|
+
decoder=_DECODE_CRYPTO_CANDLES,
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
# --- Owner (/v1/me) endpoints (5) ---
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def build_me_request() -> RequestSpec[Me]:
|
|
227
|
+
return RequestSpec(path="/v1/me", params=(), decoder=_DECODE_ME)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def build_me_warehouse_request() -> RequestSpec[Warehouse]:
|
|
231
|
+
return RequestSpec(path="/v1/me/warehouse", params=(), decoder=_DECODE_WAREHOUSE)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def build_me_wallet_request() -> RequestSpec[Wallet]:
|
|
235
|
+
return RequestSpec(path="/v1/me/wallet", params=(), decoder=_DECODE_WALLET)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def build_me_trades_request(
|
|
239
|
+
*,
|
|
240
|
+
limit: int | None = None,
|
|
241
|
+
before: dt.datetime | str | None = None,
|
|
242
|
+
before_id: int | None = None,
|
|
243
|
+
) -> RequestSpec[list[Trade]]:
|
|
244
|
+
return RequestSpec(
|
|
245
|
+
path="/v1/me/trades",
|
|
246
|
+
params=_build_trade_query(limit=limit, before=before, before_id=before_id),
|
|
247
|
+
decoder=_DECODE_TRADES,
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def build_me_property_request() -> RequestSpec[Property]:
|
|
252
|
+
return RequestSpec(path="/v1/me/property", params=(), decoder=_DECODE_PROPERTY)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
# --- Pagination helper ---
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def next_trade_cursor(page: list[Trade], *, page_size: int) -> tuple[dt.datetime, int] | None:
|
|
259
|
+
"""Compute the `(before, before_id)` cursor for the next page, or `None` if exhausted."""
|
|
260
|
+
if not page or len(page) < page_size:
|
|
261
|
+
return None
|
|
262
|
+
last = page[-1]
|
|
263
|
+
return (last.time, last.id)
|