polynode 0.10.5__tar.gz → 0.10.7__tar.gz

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.
Files changed (48) hide show
  1. {polynode-0.10.5 → polynode-0.10.7}/PKG-INFO +3 -1
  2. {polynode-0.10.5 → polynode-0.10.7}/README.md +2 -0
  3. polynode-0.10.7/polynode/_version.py +1 -0
  4. {polynode-0.10.5 → polynode-0.10.7}/polynode/orderbook.py +55 -10
  5. {polynode-0.10.5 → polynode-0.10.7}/polynode/subscription.py +13 -0
  6. {polynode-0.10.5 → polynode-0.10.7}/polynode/trading/eip712.py +3 -2
  7. {polynode-0.10.5 → polynode-0.10.7}/polynode/trading/onboarding.py +17 -4
  8. {polynode-0.10.5 → polynode-0.10.7}/polynode/trading/trader.py +22 -2
  9. {polynode-0.10.5 → polynode-0.10.7}/polynode/types/ws.py +1 -0
  10. {polynode-0.10.5 → polynode-0.10.7}/polynode/ws.py +47 -2
  11. {polynode-0.10.5 → polynode-0.10.7}/pyproject.toml +1 -1
  12. {polynode-0.10.5 → polynode-0.10.7}/tests/conftest.py +9 -5
  13. {polynode-0.10.5 → polynode-0.10.7}/tests/test_client.py +7 -3
  14. polynode-0.10.7/tests/test_orderbook_protocol.py +131 -0
  15. {polynode-0.10.5 → polynode-0.10.7}/tests/test_trading.py +121 -0
  16. polynode-0.10.7/tests/test_ws_protocol.py +107 -0
  17. polynode-0.10.5/polynode/_version.py +0 -1
  18. {polynode-0.10.5 → polynode-0.10.7}/.gitignore +0 -0
  19. {polynode-0.10.5 → polynode-0.10.7}/polynode/__init__.py +0 -0
  20. {polynode-0.10.5 → polynode-0.10.7}/polynode/cache/__init__.py +0 -0
  21. {polynode-0.10.5 → polynode-0.10.7}/polynode/client.py +0 -0
  22. {polynode-0.10.5 → polynode-0.10.7}/polynode/engine.py +0 -0
  23. {polynode-0.10.5 → polynode-0.10.7}/polynode/errors.py +0 -0
  24. {polynode-0.10.5 → polynode-0.10.7}/polynode/orderbook_state.py +0 -0
  25. {polynode-0.10.5 → polynode-0.10.7}/polynode/redemption_watcher.py +0 -0
  26. {polynode-0.10.5 → polynode-0.10.7}/polynode/short_form.py +0 -0
  27. {polynode-0.10.5 → polynode-0.10.7}/polynode/testing.py +0 -0
  28. {polynode-0.10.5 → polynode-0.10.7}/polynode/trading/V2_ORDER_FLOW.md +0 -0
  29. {polynode-0.10.5 → polynode-0.10.7}/polynode/trading/__init__.py +0 -0
  30. {polynode-0.10.5 → polynode-0.10.7}/polynode/trading/clob_api.py +0 -0
  31. {polynode-0.10.5 → polynode-0.10.7}/polynode/trading/constants.py +0 -0
  32. {polynode-0.10.5 → polynode-0.10.7}/polynode/trading/cosigner.py +0 -0
  33. {polynode-0.10.5 → polynode-0.10.7}/polynode/trading/escrow.py +0 -0
  34. {polynode-0.10.5 → polynode-0.10.7}/polynode/trading/position_management.py +0 -0
  35. {polynode-0.10.5 → polynode-0.10.7}/polynode/trading/privy.py +0 -0
  36. {polynode-0.10.5 → polynode-0.10.7}/polynode/trading/relayer.py +0 -0
  37. {polynode-0.10.5 → polynode-0.10.7}/polynode/trading/signer.py +0 -0
  38. {polynode-0.10.5 → polynode-0.10.7}/polynode/trading/sqlite_backend.py +0 -0
  39. {polynode-0.10.5 → polynode-0.10.7}/polynode/trading/types.py +0 -0
  40. {polynode-0.10.5 → polynode-0.10.7}/polynode/types/__init__.py +0 -0
  41. {polynode-0.10.5 → polynode-0.10.7}/polynode/types/enums.py +0 -0
  42. {polynode-0.10.5 → polynode-0.10.7}/polynode/types/events.py +0 -0
  43. {polynode-0.10.5 → polynode-0.10.7}/polynode/types/orderbook.py +0 -0
  44. {polynode-0.10.5 → polynode-0.10.7}/polynode/types/rest.py +0 -0
  45. {polynode-0.10.5 → polynode-0.10.7}/polynode/types/short_form.py +0 -0
  46. {polynode-0.10.5 → polynode-0.10.7}/tests/__init__.py +0 -0
  47. {polynode-0.10.5 → polynode-0.10.7}/tests/test_orderbook.py +0 -0
  48. {polynode-0.10.5 → polynode-0.10.7}/tests/test_types.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: polynode
3
- Version: 0.10.5
3
+ Version: 0.10.7
4
4
  Summary: Python SDK for the PolyNode real-time prediction market data platform
5
5
  Project-URL: Homepage, https://polynode.dev
6
6
  Project-URL: Documentation, https://docs.polynode.dev
@@ -35,6 +35,8 @@ Description-Content-Type: text/markdown
35
35
 
36
36
  Python SDK for the [PolyNode](https://polynode.dev) real-time prediction market data platform.
37
37
 
38
+ **New in v0.10.7:** Polymarket V2 deposit-wallet trading fixes. `ensure_ready()` detects deployed `POLY_1271` wallets correctly, V2 type-3 orders use the deposit wallet as both maker and signer, and existing local credentials can be repaired by rerunning `ensure_ready()`.
39
+
38
40
  ## Install
39
41
 
40
42
  ```bash
@@ -2,6 +2,8 @@
2
2
 
3
3
  Python SDK for the [PolyNode](https://polynode.dev) real-time prediction market data platform.
4
4
 
5
+ **New in v0.10.7:** Polymarket V2 deposit-wallet trading fixes. `ensure_ready()` detects deployed `POLY_1271` wallets correctly, V2 type-3 orders use the deposit wallet as both maker and signer, and existing local credentials can be repaired by rerunning `ensure_ready()`.
6
+
5
7
  ## Install
6
8
 
7
9
  ```bash
@@ -0,0 +1 @@
1
+ __version__ = "0.10.7"
@@ -28,7 +28,7 @@ class OrderbookWS:
28
28
 
29
29
  def __init__(self, api_key: str, ob_url: str, *, compress: bool = True, auto_reconnect: bool = True,
30
30
  max_reconnect_attempts: int = 0, reconnect_base_delay: float = 1.0,
31
- reconnect_max_delay: float = 30.0) -> None:
31
+ reconnect_max_delay: float = 30.0, subscribe_timeout: float = 30.0) -> None:
32
32
  self._api_key = api_key
33
33
  self._ob_url = ob_url
34
34
  self._compress = compress
@@ -36,12 +36,14 @@ class OrderbookWS:
36
36
  self._max_reconnect = max_reconnect_attempts
37
37
  self._base_delay = reconnect_base_delay
38
38
  self._max_delay = reconnect_max_delay
39
+ self._subscribe_timeout = subscribe_timeout
39
40
 
40
41
  self._socket: Any = None
41
42
  self._connected = False
42
43
  self._intentional_close = False
43
44
  self._reconnect_attempts = 0
44
45
  self._token_ids: list[str] = []
46
+ self._pending_subscribe: asyncio.Future | None = None
45
47
  self._recv_task: asyncio.Task | None = None
46
48
 
47
49
  self._handlers: dict[str, list[Callable]] = {
@@ -92,14 +94,20 @@ class OrderbookWS:
92
94
  return self
93
95
 
94
96
  async def subscribe(self, token_ids: list[str]) -> None:
95
- self._token_ids = token_ids
97
+ self._token_ids = list(token_ids)
96
98
  await self._ensure_connected()
97
- await self._send(json.dumps({"action": "subscribe", "markets": token_ids}))
98
-
99
- def unsubscribe(self) -> None:
100
- self._token_ids = []
99
+ await self._send_subscribe(self._token_ids)
100
+
101
+ def unsubscribe(self, token_ids: list[str] | None = None) -> None:
102
+ if token_ids is None:
103
+ self._token_ids = []
104
+ msg = {"action": "unsubscribe"}
105
+ else:
106
+ remove = set(token_ids)
107
+ self._token_ids = [token_id for token_id in self._token_ids if token_id not in remove]
108
+ msg = {"action": "unsubscribe", "markets": token_ids}
101
109
  if self._connected and self._socket:
102
- asyncio.ensure_future(self._send(json.dumps({"action": "unsubscribe"})))
110
+ asyncio.ensure_future(self._send(json.dumps(msg)))
103
111
 
104
112
  async def connect(self) -> None:
105
113
  if self._connected and self._socket:
@@ -157,6 +165,9 @@ class OrderbookWS:
157
165
  return
158
166
  finally:
159
167
  self._connected = False
168
+ self._reject_pending_subscribe(
169
+ WsError("WebSocket connection closed before orderbook subscription was acknowledged")
170
+ )
160
171
  reason = "closed" if self._intentional_close else "lost"
161
172
  for h in self._on_disconnect:
162
173
  h(reason)
@@ -167,11 +178,44 @@ class OrderbookWS:
167
178
  if self._socket and self._connected:
168
179
  await self._socket.send(data)
169
180
 
181
+ async def _send_subscribe(self, token_ids: list[str]) -> None:
182
+ if self._pending_subscribe and not self._pending_subscribe.done():
183
+ raise WsError("Subscribe already pending")
184
+
185
+ fut: asyncio.Future[None] = asyncio.get_running_loop().create_future()
186
+ self._pending_subscribe = fut
187
+ await self._send(json.dumps({"action": "subscribe", "markets": token_ids}))
188
+
189
+ try:
190
+ await asyncio.wait_for(fut, timeout=self._subscribe_timeout)
191
+ except asyncio.TimeoutError:
192
+ if self._pending_subscribe is fut:
193
+ self._pending_subscribe = None
194
+ raise WsError(f"Subscribe timed out after {self._subscribe_timeout:g} seconds")
195
+
196
+ def _resolve_pending_subscribe(self) -> None:
197
+ fut = self._pending_subscribe
198
+ self._pending_subscribe = None
199
+ if fut and not fut.done():
200
+ fut.set_result(None)
201
+
202
+ def _reject_pending_subscribe(self, err: WsError) -> None:
203
+ fut = self._pending_subscribe
204
+ self._pending_subscribe = None
205
+ if fut and not fut.done():
206
+ fut.set_exception(err)
207
+
170
208
  def _handle_message(self, text: str) -> None:
171
209
  msg = json.loads(text)
172
210
 
173
- if msg.get("error"):
174
- err_msg = ObErrorMessage.model_validate(msg)
211
+ if msg.get("error") or msg.get("type") == "error":
212
+ err_msg = ObErrorMessage(
213
+ error=str(msg.get("error") or msg.get("code") or "error"),
214
+ message=str(msg.get("message") or msg.get("error") or "Unknown orderbook error"),
215
+ max=msg.get("max"),
216
+ requested=msg.get("requested"),
217
+ )
218
+ self._reject_pending_subscribe(WsError(err_msg.message, err_msg.error))
175
219
  for h in self._handlers["error"]:
176
220
  h(err_msg)
177
221
  return
@@ -180,6 +224,7 @@ class OrderbookWS:
180
224
 
181
225
  if msg_type == "subscribed":
182
226
  sub_msg = SubscribedMessage(markets=msg.get("markets", 0))
227
+ self._resolve_pending_subscribe()
183
228
  for h in self._handlers["subscribed"]:
184
229
  h(sub_msg)
185
230
 
@@ -238,6 +283,6 @@ class OrderbookWS:
238
283
  for h in self._on_reconnect:
239
284
  h(self._reconnect_attempts)
240
285
  if self._token_ids:
241
- await self._send(json.dumps({"action": "subscribe", "markets": self._token_ids}))
286
+ await self._send_subscribe(self._token_ids)
242
287
  except Exception:
243
288
  pass
@@ -12,6 +12,8 @@ from .types.ws import SubscriptionFilters
12
12
  if TYPE_CHECKING:
13
13
  from .ws import PolyNodeWS
14
14
 
15
+ PRE_ACK_REPLAY_LIMIT = 1000
16
+
15
17
 
16
18
  class SubscriptionBuilder:
17
19
  """Fluent builder for WebSocket subscriptions."""
@@ -79,6 +81,7 @@ class Subscription:
79
81
  self._id: str | None = None
80
82
  self._handlers: dict[str, set[Callable]] = {}
81
83
  self._queue: asyncio.Queue[PolyNodeEvent | None] = asyncio.Queue()
84
+ self._pre_ack_replay: list[PolyNodeEvent] = []
82
85
  self._closed = False
83
86
 
84
87
  @property
@@ -92,6 +95,10 @@ class Subscription:
92
95
  if type not in self._handlers:
93
96
  self._handlers[type] = set()
94
97
  self._handlers[type].add(handler)
98
+ for event in self._pre_ack_replay:
99
+ event_type = event.event_type # type: ignore[union-attr]
100
+ if type == "*" or type == event_type:
101
+ handler(event)
95
102
  return self
96
103
 
97
104
  def off(self, type: str, handler: Callable) -> Subscription:
@@ -114,6 +121,12 @@ class Subscription:
114
121
  # Async iterator queue
115
122
  self._queue.put_nowait(event)
116
123
 
124
+ def _emit_pre_ack(self, event: PolyNodeEvent) -> None:
125
+ self._pre_ack_replay.append(event)
126
+ if len(self._pre_ack_replay) > PRE_ACK_REPLAY_LIMIT:
127
+ self._pre_ack_replay = self._pre_ack_replay[-PRE_ACK_REPLAY_LIMIT:]
128
+ self._emit(event)
129
+
117
130
  def unsubscribe(self) -> None:
118
131
  self._closed = True
119
132
  self._queue.put_nowait(None)
@@ -305,10 +305,11 @@ async def create_signed_order_v2(
305
305
  - timestamp is a string in the payload
306
306
  """
307
307
  maker_amount, taker_amount = compute_amounts(price, size, side, tick_size)
308
+ order_signer = funder_address if signature_type == SignatureType.POLY_1271 else signer_address
308
309
 
309
310
  payload = build_order_payload_v2(
310
311
  maker=funder_address,
311
- signer=signer_address,
312
+ signer=order_signer,
312
313
  token_id=token_id,
313
314
  maker_amount=maker_amount,
314
315
  taker_amount=taker_amount,
@@ -388,7 +389,7 @@ async def create_signed_order_v2(
388
389
  return {
389
390
  "salt": payload.message["salt"], # number
390
391
  "maker": funder_address,
391
- "signer": signer_address,
392
+ "signer": order_signer,
392
393
  "taker": "0x0000000000000000000000000000000000000000",
393
394
  "tokenId": token_id,
394
395
  "makerAmount": str(maker_amount),
@@ -124,6 +124,7 @@ async def detect_wallet_type(eoa: str) -> dict:
124
124
  """Auto-detect if a Safe, Proxy, or deposit wallet is deployed for this EOA."""
125
125
  safe_addr = derive_safe_address(eoa)
126
126
  proxy_addr = derive_proxy_address(eoa)
127
+ deposit_wallet_addr = derive_deposit_wallet_address(eoa)
127
128
 
128
129
  async with httpx.AsyncClient(timeout=10.0) as http:
129
130
  # Check Safe first (most common for existing users)
@@ -152,13 +153,13 @@ async def detect_wallet_type(eoa: str) -> dict:
152
153
  except Exception:
153
154
  pass
154
155
 
155
- # Check deposit wallet (newer accounts)
156
+ # Check deposit wallet (newer accounts). Polymarket's relayer defaults
157
+ # /deployed to SAFE, so deposit wallets must be checked with type=WALLET.
156
158
  try:
157
- dw_addr = derive_deposit_wallet_address(eoa)
158
- if await is_safe_deployed(dw_addr):
159
+ if await is_deposit_wallet_deployed(deposit_wallet_addr):
159
160
  return {
160
161
  "signature_type": SignatureType.POLY_1271,
161
- "funder_address": dw_addr,
162
+ "funder_address": deposit_wallet_addr,
162
163
  }
163
164
  except Exception:
164
165
  pass
@@ -182,6 +183,18 @@ async def is_safe_deployed(funder_address: str) -> bool:
182
183
  return False
183
184
 
184
185
 
186
+ async def is_deposit_wallet_deployed(funder_address: str) -> bool:
187
+ """Check if a deposit wallet is deployed at the given address."""
188
+ async with httpx.AsyncClient(timeout=10.0) as http:
189
+ try:
190
+ resp = await http.get(f"{RELAYER_HOST}/deployed?address={funder_address}&type=WALLET")
191
+ if resp.is_success:
192
+ return resp.json().get("deployed", False)
193
+ except Exception:
194
+ pass
195
+ return False
196
+
197
+
185
198
  async def check_approvals(
186
199
  funder_address: str,
187
200
  rpc_url: str,
@@ -33,6 +33,7 @@ from .onboarding import (
33
33
  create_clob_credentials,
34
34
  derive_funder_address,
35
35
  detect_wallet_type,
36
+ is_deposit_wallet_deployed,
36
37
  is_safe_deployed,
37
38
  set_approvals as set_approvals_onchain,
38
39
  )
@@ -103,14 +104,19 @@ class PolyNodeTrader:
103
104
  signer: str | RouterSigner,
104
105
  *,
105
106
  type: SignatureType | None = None,
107
+ funder_address: str | None = None,
106
108
  ) -> ReadyStatus:
107
109
  """One-call onboarding: detect wallet type, deploy Safe, set approvals, create CLOB creds."""
110
+ if funder_address is not None and type is None:
111
+ raise ValueError("funder_address requires type so the wallet identity is unambiguous")
112
+
108
113
  temp = await normalize_signer(signer, type or SignatureType.POLY_GNOSIS_SAFE)
109
114
  actions: list[str] = []
110
115
 
111
116
  if type is not None:
112
117
  sig_type = type
113
- funder = temp.funder_address or await derive_funder_address(temp.address, sig_type)
118
+ funder = funder_address or temp.funder_address or await derive_funder_address(temp.address, sig_type)
119
+ actions.append(f"explicit_type_{int(sig_type)}")
114
120
  else:
115
121
  detected = await detect_wallet_type(temp.address)
116
122
  sig_type = detected["signature_type"]
@@ -135,6 +141,14 @@ class PolyNodeTrader:
135
141
  else:
136
142
  actions.append("safe_deploy_needed")
137
143
 
144
+ if sig_type == SignatureType.POLY_1271 and not safe_deployed:
145
+ deployed = await is_deposit_wallet_deployed(funder)
146
+ if deployed:
147
+ safe_deployed = True
148
+ actions.append("deposit_wallet_already_deployed")
149
+ else:
150
+ actions.append("deposit_wallet_deploy_needed")
151
+
138
152
  # Check approvals
139
153
  if sig_type in (SignatureType.POLY_GNOSIS_SAFE, SignatureType.EOA) and not approvals_set:
140
154
  try:
@@ -165,6 +179,8 @@ class PolyNodeTrader:
165
179
  db.upsert_credentials(stored)
166
180
  actions.append("credentials_created")
167
181
  else:
182
+ stored.funder_address = funder
183
+ stored.signature_type = sig_type
168
184
  stored.safe_deployed = safe_deployed
169
185
  stored.approvals_set = approvals_set
170
186
  stored.updated_at = time.time()
@@ -214,11 +230,15 @@ class PolyNodeTrader:
214
230
  signer: str | RouterSigner,
215
231
  *,
216
232
  type: SignatureType | None = None,
233
+ funder_address: str | None = None,
217
234
  ) -> LinkResult:
218
235
  """Link a wallet manually (derive credentials, store locally)."""
236
+ if funder_address is not None and type is None:
237
+ raise ValueError("funder_address requires type so the wallet identity is unambiguous")
238
+
219
239
  sig_type = type or self._default_sig_type
220
240
  normalized = await normalize_signer(signer, sig_type)
221
- funder = normalized.funder_address or await derive_funder_address(normalized.address, sig_type)
241
+ funder = funder_address or normalized.funder_address or await derive_funder_address(normalized.address, sig_type)
222
242
 
223
243
  db = self._get_db()
224
244
  existing = db.get_credentials(normalized.address)
@@ -36,3 +36,4 @@ class WsOptions:
36
36
  max_reconnect_attempts: int = 0 # 0 = infinite
37
37
  reconnect_base_delay: float = 1.0
38
38
  reconnect_max_delay: float = 30.0
39
+ subscribe_timeout: float = 30.0
@@ -29,6 +29,32 @@ def _parse_event(data: dict) -> PolyNodeEvent | None:
29
29
  return None
30
30
 
31
31
 
32
+ def _subscription_accepts_event(sub_type: SubscriptionType, event_type: str) -> bool:
33
+ if sub_type in ("global", "markets"):
34
+ return True
35
+ if sub_type == "settlements":
36
+ return event_type in {"settlement", "status_update"}
37
+ if sub_type in ("trades", "large_trades"):
38
+ return event_type == "trade"
39
+ if sub_type in ("prices", "chainlink"):
40
+ return event_type == "price_feed"
41
+ if sub_type == "blocks":
42
+ return event_type == "block"
43
+ if sub_type == "wallets":
44
+ return event_type in {
45
+ "settlement",
46
+ "trade",
47
+ "status_update",
48
+ "position_change",
49
+ "deposit",
50
+ "position_split",
51
+ "position_merge",
52
+ }
53
+ if sub_type == "oracle":
54
+ return event_type == "oracle"
55
+ return True
56
+
57
+
32
58
  class PolyNodeWS:
33
59
  """Async WebSocket client with auto-reconnect and subscription management."""
34
60
 
@@ -41,6 +67,7 @@ class PolyNodeWS:
41
67
  self._max_reconnect = opts.max_reconnect_attempts
42
68
  self._base_delay = opts.reconnect_base_delay
43
69
  self._max_delay = opts.reconnect_max_delay
70
+ self._subscribe_timeout = opts.subscribe_timeout
44
71
 
45
72
  self._socket: Any = None
46
73
  self._connected = False
@@ -105,11 +132,11 @@ class PolyNodeWS:
105
132
  await self._send(json.dumps(msg))
106
133
 
107
134
  try:
108
- return await asyncio.wait_for(fut, timeout=10.0)
135
+ return await asyncio.wait_for(fut, timeout=self._subscribe_timeout)
109
136
  except asyncio.TimeoutError:
110
137
  # Remove from pending
111
138
  self._pending = [(s, f) for s, f in self._pending if f is not fut]
112
- raise WsError("Subscribe timed out after 10 seconds")
139
+ raise WsError(f"Subscribe timed out after {self._subscribe_timeout:g} seconds")
113
140
 
114
141
  def _unsubscribe(self, subscription_id: str | None = None) -> None:
115
142
  if subscription_id:
@@ -182,6 +209,8 @@ class PolyNodeWS:
182
209
  return
183
210
  finally:
184
211
  self._connected = False
212
+ if self._pending:
213
+ self._reject_pending(WsError("WebSocket connection closed before subscription was acknowledged"))
185
214
  reason = "closed" if self._intentional_close else "lost"
186
215
  for h in self._on_disconnect:
187
216
  h(reason)
@@ -250,6 +279,22 @@ class PolyNodeWS:
250
279
  def _route_event(self, event: PolyNodeEvent) -> None:
251
280
  for sub in self._subscriptions.values():
252
281
  sub._emit(event)
282
+ self._route_pending_event(event)
283
+
284
+ def _route_pending_event(self, event: PolyNodeEvent) -> None:
285
+ if not self._pending:
286
+ return
287
+ event_type = event.event_type # type: ignore[union-attr]
288
+ for sub, _ in self._pending:
289
+ if _subscription_accepts_event(sub.type, event_type):
290
+ sub._emit_pre_ack(event)
291
+
292
+ def _reject_pending(self, err: WsError) -> None:
293
+ pending = self._pending
294
+ self._pending = []
295
+ for _, fut in pending:
296
+ if not fut.done():
297
+ fut.set_exception(err)
253
298
 
254
299
  async def _schedule_reconnect(self) -> None:
255
300
  if self._max_reconnect and self._reconnect_attempts >= self._max_reconnect:
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "polynode"
7
- version = "0.10.5"
7
+ version = "0.10.7"
8
8
  description = "Python SDK for the PolyNode real-time prediction market data platform"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -1,8 +1,10 @@
1
1
  """Shared test fixtures."""
2
2
 
3
+ import os
4
+
3
5
  import pytest
4
6
 
5
- TEST_KEY = "pn_live_test_session_tracking_51eca107e9b347b589f5b0a04f98eb1d"
7
+ TEST_KEY = os.getenv("POLYNODE_API_KEY")
6
8
  BASE_URL = "https://api.polynode.dev"
7
9
  WS_URL = "wss://ws.polynode.dev/ws"
8
10
  OB_URL = "wss://ob.polynode.dev/ws"
@@ -10,20 +12,22 @@ OB_URL = "wss://ob.polynode.dev/ws"
10
12
 
11
13
  @pytest.fixture
12
14
  def api_key():
15
+ if not TEST_KEY:
16
+ pytest.skip("POLYNODE_API_KEY is not set")
13
17
  return TEST_KEY
14
18
 
15
19
 
16
20
  @pytest.fixture
17
- def client():
21
+ def client(api_key):
18
22
  from polynode import PolyNode
19
- pn = PolyNode(api_key=TEST_KEY)
23
+ pn = PolyNode(api_key=api_key)
20
24
  yield pn
21
25
  pn.close()
22
26
 
23
27
 
24
28
  @pytest.fixture
25
- async def async_client():
29
+ async def async_client(api_key):
26
30
  from polynode import AsyncPolyNode
27
- pn = AsyncPolyNode(api_key=TEST_KEY)
31
+ pn = AsyncPolyNode(api_key=api_key)
28
32
  yield pn
29
33
  await pn.close()
@@ -1,14 +1,18 @@
1
1
  """Tests for the sync REST client."""
2
2
 
3
+ import os
4
+
3
5
  import pytest
4
6
  from polynode import PolyNode
5
7
  from polynode.types.rest import StatusResponse, MarketsResponse, SettlementsResponse
6
8
 
7
- TEST_KEY = "pn_live_test_session_tracking_51eca107e9b347b589f5b0a04f98eb1d"
9
+ TEST_KEY = os.getenv("POLYNODE_API_KEY")
8
10
 
9
11
 
10
12
  @pytest.fixture
11
13
  def pn():
14
+ if not TEST_KEY:
15
+ pytest.skip("POLYNODE_API_KEY is not set")
12
16
  client = PolyNode(api_key=TEST_KEY)
13
17
  yield client
14
18
  client.close()
@@ -46,7 +50,7 @@ def test_search(pn):
46
50
 
47
51
 
48
52
  def test_search_online_builds_expected_path():
49
- client = PolyNode(api_key=TEST_KEY)
53
+ client = PolyNode(api_key=TEST_KEY or "pn_test_local")
50
54
  calls = []
51
55
 
52
56
  def fake_fetch(path, **kwargs):
@@ -80,7 +84,7 @@ def test_search_online_builds_expected_path():
80
84
 
81
85
 
82
86
  def test_sports_methods_build_expected_paths():
83
- client = PolyNode(api_key=TEST_KEY)
87
+ client = PolyNode(api_key=TEST_KEY or "pn_test_local")
84
88
  calls = []
85
89
 
86
90
  def fake_fetch(path, **kwargs):
@@ -0,0 +1,131 @@
1
+ """Protocol-level orderbook WebSocket regression tests."""
2
+
3
+ import asyncio
4
+ import json
5
+
6
+ import pytest
7
+
8
+ from polynode.errors import WsError
9
+ from polynode.orderbook import OrderbookWS
10
+
11
+
12
+ class FakeSocket:
13
+ def __init__(self) -> None:
14
+ self.sent: list[dict] = []
15
+
16
+ async def send(self, data: str) -> None:
17
+ self.sent.append(json.loads(data))
18
+
19
+
20
+ def snapshot(asset_id: str = "token-1") -> dict:
21
+ return {
22
+ "type": "book_snapshot",
23
+ "asset_id": asset_id,
24
+ "market": "condition-1",
25
+ "bids": [{"price": "0.50", "size": "100"}],
26
+ "asks": [{"price": "0.55", "size": "200"}],
27
+ }
28
+
29
+
30
+ def make_ws(timeout: float = 0.2) -> tuple[OrderbookWS, FakeSocket]:
31
+ socket = FakeSocket()
32
+ ws = OrderbookWS("key", "wss://example.test/ws", subscribe_timeout=timeout)
33
+ ws._socket = socket
34
+ ws._connected = True
35
+ return ws, socket
36
+
37
+
38
+ def test_orderbook_subscribe_waits_for_ack_without_dropping_snapshots():
39
+ async def scenario() -> None:
40
+ ws, socket = make_ws()
41
+ snapshots = []
42
+ subscribed = []
43
+ ws.on("snapshot", snapshots.append)
44
+ ws.on("subscribed", subscribed.append)
45
+
46
+ task = asyncio.create_task(ws.subscribe(["token-1"]))
47
+ await asyncio.sleep(0)
48
+
49
+ assert socket.sent == [{"action": "subscribe", "markets": ["token-1"]}]
50
+ assert not task.done()
51
+
52
+ ws._handle_message(json.dumps({"type": "snapshot_batch", "snapshots": [snapshot()]}))
53
+ assert len(snapshots) == 1
54
+ assert not task.done()
55
+
56
+ ws._handle_message(json.dumps({"type": "subscribed", "markets": 1}))
57
+ await asyncio.wait_for(task, timeout=0.1)
58
+
59
+ assert subscribed[0].markets == 1
60
+ assert snapshots[0].asset_id == "token-1"
61
+
62
+ asyncio.run(scenario())
63
+
64
+
65
+ def test_orderbook_subscribe_rejects_server_error_before_ack():
66
+ async def scenario() -> None:
67
+ ws, _ = make_ws()
68
+ errors = []
69
+ ws.on("error", errors.append)
70
+
71
+ task = asyncio.create_task(ws.subscribe(["token-1", "token-2"]))
72
+ await asyncio.sleep(0)
73
+ ws._handle_message(
74
+ json.dumps(
75
+ {
76
+ "error": "too_many_markets",
77
+ "message": "Too many markets",
78
+ "max": 1,
79
+ "requested": 2,
80
+ }
81
+ )
82
+ )
83
+
84
+ with pytest.raises(WsError, match="Too many markets"):
85
+ await task
86
+
87
+ assert errors[0].error == "too_many_markets"
88
+ assert errors[0].max == 1
89
+ assert errors[0].requested == 2
90
+
91
+ asyncio.run(scenario())
92
+
93
+
94
+ def test_orderbook_subscribe_timeout_uses_configured_timeout():
95
+ async def scenario() -> None:
96
+ ws, socket = make_ws(timeout=0.01)
97
+
98
+ with pytest.raises(WsError, match="0.01 seconds"):
99
+ await ws.subscribe(["token-1"])
100
+
101
+ assert socket.sent == [{"action": "subscribe", "markets": ["token-1"]}]
102
+
103
+ asyncio.run(scenario())
104
+
105
+
106
+ def test_orderbook_partial_unsubscribe_is_additive():
107
+ async def scenario() -> None:
108
+ ws, socket = make_ws()
109
+ ws._token_ids = ["token-1", "token-2", "token-3"]
110
+
111
+ ws.unsubscribe(["token-2"])
112
+ await asyncio.sleep(0)
113
+
114
+ assert ws._token_ids == ["token-1", "token-3"]
115
+ assert socket.sent == [{"action": "unsubscribe", "markets": ["token-2"]}]
116
+
117
+ asyncio.run(scenario())
118
+
119
+
120
+ def test_orderbook_type_error_rejects_pending_subscribe():
121
+ async def scenario() -> None:
122
+ ws, _ = make_ws()
123
+ task = asyncio.create_task(ws.subscribe(["token-1"]))
124
+ await asyncio.sleep(0)
125
+
126
+ ws._handle_message(json.dumps({"type": "error", "code": "bad_request", "message": "Invalid token"}))
127
+
128
+ with pytest.raises(WsError, match="Invalid token"):
129
+ await task
130
+
131
+ asyncio.run(scenario())
@@ -1,11 +1,13 @@
1
1
  """Tests for trading module — EIP-712 signing, HMAC headers, V1 and V2."""
2
2
 
3
3
  import base64
4
+ import asyncio
4
5
 
5
6
  from polynode.trading.cosigner import build_l2_headers
6
7
  from polynode.trading.eip712 import (
7
8
  build_order_payload,
8
9
  build_order_payload_v2,
10
+ create_signed_order_v2,
9
11
  compute_amounts,
10
12
  EXCHANGE_DOMAIN,
11
13
  EXCHANGE_DOMAIN_V2,
@@ -76,6 +78,125 @@ def test_safe_address_derivation():
76
78
  pass # Skip if trading deps not installed
77
79
 
78
80
 
81
+ def test_detect_wallet_type_uses_deposit_wallet_check(monkeypatch):
82
+ """Regression: deposit wallets must be checked as WALLET, not SAFE."""
83
+ from polynode.trading import onboarding
84
+
85
+ eoa = "0x7b3099fe73372D900a9F0F62CdcA261755f7EA60"
86
+ deposit_wallet = "0x58b8048C8f09C2FCc4914258587a8E7E0cc21D76"
87
+
88
+ async def safe_not_deployed(_address: str) -> bool:
89
+ return False
90
+
91
+ async def deposit_wallet_deployed(address: str) -> bool:
92
+ return address == deposit_wallet
93
+
94
+ monkeypatch.setattr(onboarding, "is_safe_deployed", safe_not_deployed)
95
+ monkeypatch.setattr(onboarding, "is_deposit_wallet_deployed", deposit_wallet_deployed)
96
+
97
+ detected = asyncio.run(onboarding.detect_wallet_type(eoa))
98
+
99
+ assert detected["signature_type"] == SignatureType.POLY_1271
100
+ assert detected["funder_address"] == deposit_wallet
101
+
102
+
103
+ def test_v2_poly1271_order_uses_deposit_wallet_as_signer():
104
+ """POLY_1271 V2 orders need maker and signer set to the deposit wallet."""
105
+ signer_address = "0x7b3099fe73372D900a9F0F62CdcA261755f7EA60"
106
+ deposit_wallet = "0x58b8048C8f09C2FCc4914258587a8E7E0cc21D76"
107
+ signed_payload = {}
108
+
109
+ async def fake_sign(payload):
110
+ signed_payload.update(payload.message["contents"])
111
+ return "0x" + "11" * 65
112
+
113
+ order = asyncio.run(create_signed_order_v2(
114
+ fake_sign,
115
+ signer_address=signer_address,
116
+ funder_address=deposit_wallet,
117
+ token_id="12345",
118
+ price=0.5,
119
+ size=1,
120
+ side="BUY",
121
+ signature_type=SignatureType.POLY_1271,
122
+ timestamp_ms=1712345678000,
123
+ ))
124
+
125
+ assert signed_payload["maker"] == deposit_wallet
126
+ assert signed_payload["signer"] == deposit_wallet
127
+ assert order["maker"] == deposit_wallet
128
+ assert order["signer"] == deposit_wallet
129
+ assert order["signatureType"] == 3
130
+
131
+
132
+ def test_ensure_ready_allows_explicit_poly1271_funder(monkeypatch, tmp_path):
133
+ """Existing deposit-wallet users can force type 3 plus a known funder."""
134
+ from polynode.trading import trader as trader_mod
135
+ from polynode.trading.trader import PolyNodeTrader
136
+ from polynode.trading.types import ExchangeVersion, TraderConfig
137
+
138
+ private_key = "0x" + "01" * 32
139
+ deposit_wallet = "0x58b8048C8f09C2FCc4914258587a8E7E0cc21D76"
140
+
141
+ async def deposit_wallet_deployed(address: str) -> bool:
142
+ return address == deposit_wallet
143
+
144
+ async def fake_create_clob_credentials(*_args, **_kwargs):
145
+ return {
146
+ "apiKey": "key",
147
+ "apiSecret": base64.b64encode(b"secret").decode(),
148
+ "apiPassphrase": "pass",
149
+ }
150
+
151
+ monkeypatch.setattr(trader_mod, "is_deposit_wallet_deployed", deposit_wallet_deployed)
152
+ monkeypatch.setattr(trader_mod, "create_clob_credentials", fake_create_clob_credentials)
153
+
154
+ trader = PolyNodeTrader(TraderConfig(
155
+ db_path=str(tmp_path / "trading.db"),
156
+ exchange_version=ExchangeVersion.V2,
157
+ ))
158
+
159
+ status = asyncio.run(trader.ensure_ready(
160
+ private_key,
161
+ type=SignatureType.POLY_1271,
162
+ funder_address=deposit_wallet,
163
+ ))
164
+
165
+ assert status.signature_type == SignatureType.POLY_1271
166
+ assert status.funder_address == deposit_wallet
167
+ assert status.safe_deployed is True
168
+ assert "explicit_type_3" in status.actions
169
+ assert "deposit_wallet_already_deployed" in status.actions
170
+
171
+ try:
172
+ from eth_account import Account
173
+ except ImportError:
174
+ return
175
+
176
+ wallet = Account.from_key(private_key).address
177
+ wrong_safe = "0xb8f9248a67962c9FE37E70e7a6E38e100b7613f1"
178
+ trader.link_credentials(
179
+ wallet=wallet,
180
+ api_key="key",
181
+ api_secret=base64.b64encode(b"secret").decode(),
182
+ api_passphrase="pass",
183
+ signature_type=SignatureType.POLY_GNOSIS_SAFE,
184
+ funder_address=wrong_safe,
185
+ )
186
+
187
+ status = asyncio.run(trader.ensure_ready(
188
+ private_key,
189
+ type=SignatureType.POLY_1271,
190
+ funder_address=deposit_wallet,
191
+ ))
192
+ exported = trader.export_wallet(wallet)
193
+
194
+ assert status.signature_type == SignatureType.POLY_1271
195
+ assert exported is not None
196
+ assert exported.signature_type == SignatureType.POLY_1271
197
+ assert exported.funder_address == deposit_wallet
198
+
199
+
79
200
  # ── V2 constants ──
80
201
 
81
202
 
@@ -0,0 +1,107 @@
1
+ """Protocol-level WebSocket regression tests."""
2
+
3
+ import asyncio
4
+ import json
5
+
6
+ import pytest
7
+
8
+ from polynode.errors import WsError
9
+ from polynode.subscription import Subscription
10
+ from polynode.types.ws import SubscriptionFilters, WsOptions
11
+ from polynode.ws import PolyNodeWS
12
+
13
+
14
+ class FakeSocket:
15
+ def __init__(self) -> None:
16
+ self.sent: list[dict] = []
17
+
18
+ async def send(self, data: str) -> None:
19
+ self.sent.append(json.loads(data))
20
+
21
+
22
+ def settlement_payload(tx_hash: str = "0xabc") -> dict:
23
+ return {
24
+ "event_type": "settlement",
25
+ "tx_hash": tx_hash,
26
+ "status": "pending",
27
+ "detected_at": 1234567890.0,
28
+ "taker_wallet": "0x123",
29
+ "taker_token": "0x456",
30
+ "taker_side": "BUY",
31
+ "taker_price": 0.55,
32
+ "taker_size": 100.0,
33
+ "trades": [],
34
+ }
35
+
36
+
37
+ def test_snapshot_before_subscribed_is_replayed_to_late_handler():
38
+ async def scenario() -> None:
39
+ ws = PolyNodeWS("key", "wss://example.test/ws")
40
+ sub = Subscription(ws, "settlements", SubscriptionFilters())
41
+ fut = asyncio.get_running_loop().create_future()
42
+ ws._pending.append((sub, fut))
43
+
44
+ ws._handle_message(json.dumps({"type": "snapshot", "events": [{"data": settlement_payload()}]}))
45
+ assert not fut.done()
46
+
47
+ ws._handle_message(json.dumps({"type": "subscribed", "subscription_id": "sub-1"}))
48
+ returned = await asyncio.wait_for(fut, timeout=0.1)
49
+
50
+ replayed = []
51
+ returned.on("settlement", replayed.append)
52
+
53
+ queued = await asyncio.wait_for(returned.__anext__(), timeout=0.1)
54
+ assert returned.id == "sub-1"
55
+ assert queued.tx_hash == "0xabc"
56
+ assert [event.tx_hash for event in replayed] == ["0xabc"]
57
+
58
+ asyncio.run(scenario())
59
+
60
+
61
+ def test_pre_ack_snapshot_only_routes_to_compatible_pending_subscription():
62
+ async def scenario() -> None:
63
+ ws = PolyNodeWS("key", "wss://example.test/ws")
64
+ sub = Subscription(ws, "trades", SubscriptionFilters())
65
+ fut = asyncio.get_running_loop().create_future()
66
+ ws._pending.append((sub, fut))
67
+
68
+ ws._handle_message(json.dumps({"type": "snapshot", "events": [{"data": settlement_payload()}]}))
69
+ ws._handle_message(json.dumps({"type": "subscribed", "subscription_id": "trade-sub"}))
70
+ await asyncio.wait_for(fut, timeout=0.1)
71
+
72
+ replayed = []
73
+ sub.on("*", replayed.append)
74
+ assert replayed == []
75
+ assert sub._queue.empty()
76
+
77
+ asyncio.run(scenario())
78
+
79
+
80
+ def test_subscribe_timeout_uses_configured_timeout():
81
+ async def scenario() -> None:
82
+ ws = PolyNodeWS("key", "wss://example.test/ws", WsOptions(subscribe_timeout=0.01))
83
+ ws._socket = FakeSocket()
84
+ ws._connected = True
85
+
86
+ with pytest.raises(WsError, match="0.01 seconds"):
87
+ await ws.subscribe("settlements").send()
88
+
89
+ assert ws._socket.sent == [{"action": "subscribe", "type": "settlements"}]
90
+
91
+ asyncio.run(scenario())
92
+
93
+
94
+ def test_disconnect_rejects_pending_subscriptions():
95
+ async def scenario() -> None:
96
+ ws = PolyNodeWS("key", "wss://example.test/ws")
97
+ sub = Subscription(ws, "settlements", SubscriptionFilters())
98
+ fut = asyncio.get_running_loop().create_future()
99
+ ws._pending.append((sub, fut))
100
+
101
+ ws._reject_pending(WsError("closed"))
102
+
103
+ with pytest.raises(WsError, match="closed"):
104
+ await fut
105
+ assert ws._pending == []
106
+
107
+ asyncio.run(scenario())
@@ -1 +0,0 @@
1
- __version__ = "0.10.5"
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes