opinion-clob-sdk 0.1.4__py3-none-any.whl → 0.1.5__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.

Potentially problematic release.


This version of opinion-clob-sdk might be problematic. Click here for more details.

Files changed (55) hide show
  1. opinion_clob_sdk/__init__.py +1 -1
  2. opinion_clob_sdk/opinion_clob_sdk/__init__.py +1 -1
  3. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/__init__.py +1 -1
  4. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/__init__.py +1 -1
  5. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/__init__.py +26 -0
  6. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/__init__.py +0 -0
  7. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/contract_caller.py +390 -0
  8. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/contracts/__init__.py +0 -0
  9. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/contracts/conditional_tokens.py +707 -0
  10. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/contracts/erc20.py +111 -0
  11. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/exception.py +11 -0
  12. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/py_order_utils/__init__.py +0 -0
  13. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/py_order_utils/builders/__init__.py +0 -0
  14. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/py_order_utils/builders/base_builder.py +41 -0
  15. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/py_order_utils/builders/exception.py +2 -0
  16. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/py_order_utils/builders/order_builder.py +90 -0
  17. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/py_order_utils/builders/order_builder_test.py +40 -0
  18. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/py_order_utils/constants.py +2 -0
  19. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/py_order_utils/model/__init__.py +0 -0
  20. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/py_order_utils/model/order.py +254 -0
  21. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/py_order_utils/model/order_type.py +9 -0
  22. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/py_order_utils/model/sides.py +8 -0
  23. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/py_order_utils/model/signatures.py +8 -0
  24. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/py_order_utils/signer.py +20 -0
  25. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/py_order_utils/utils.py +109 -0
  26. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/safe/__init__.py +0 -0
  27. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/safe/constants.py +19 -0
  28. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/safe/eip712/__init__.py +176 -0
  29. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/safe/enums.py +6 -0
  30. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/safe/exceptions.py +94 -0
  31. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/safe/multisend.py +347 -0
  32. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/safe/safe.py +141 -0
  33. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/safe/safe_contracts/__init__.py +0 -0
  34. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/safe/safe_contracts/compatibility_fallback_handler_v1_3_0.py +327 -0
  35. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/safe/safe_contracts/multisend_v1_3_0.py +22 -0
  36. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/safe/safe_contracts/safe_v1_3_0.py +1035 -0
  37. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/safe/safe_contracts/utils.py +26 -0
  38. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/safe/safe_signature.py +364 -0
  39. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/safe/safe_test.py +37 -0
  40. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/safe/safe_tx.py +437 -0
  41. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/safe/signatures.py +63 -0
  42. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/safe/typing.py +17 -0
  43. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/chain/safe/utils.py +218 -0
  44. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/config.py +4 -0
  45. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/model.py +19 -0
  46. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/sdk.py +947 -0
  47. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/sdk.py +2 -2
  48. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/sdk.py +2 -2
  49. opinion_clob_sdk/opinion_clob_sdk/opinion_clob_sdk/verify_api_calls.py +135 -0
  50. opinion_clob_sdk/opinion_clob_sdk/sdk.py +2 -2
  51. opinion_clob_sdk/sdk.py +2 -2
  52. {opinion_clob_sdk-0.1.4.dist-info → opinion_clob_sdk-0.1.5.dist-info}/METADATA +1 -1
  53. {opinion_clob_sdk-0.1.4.dist-info → opinion_clob_sdk-0.1.5.dist-info}/RECORD +55 -12
  54. {opinion_clob_sdk-0.1.4.dist-info → opinion_clob_sdk-0.1.5.dist-info}/WHEEL +0 -0
  55. {opinion_clob_sdk-0.1.4.dist-info → opinion_clob_sdk-0.1.5.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,947 @@
1
+ from typing import List, Optional, Dict, Any, Tuple
2
+ import logging
3
+ import math
4
+ from time import time
5
+ from decimal import Decimal
6
+
7
+ from eth_typing import ChecksumAddress, HexStr
8
+ from opinion_api.api.prediction_market_api import PredictionMarketApi
9
+ from opinion_api.api.user_api import UserApi
10
+ from opinion_api.api_client import ApiClient
11
+ from opinion_api.configuration import Configuration
12
+ from opinion_clob_sdk.chain.safe.utils import fast_to_checksum_address
13
+ from .chain.contract_caller import ContractCaller
14
+ from .chain.py_order_utils.builders.order_builder import OrderBuilder
15
+ from .chain.py_order_utils.model.order import OrderDataInput, OrderData, PlaceOrderDataInput
16
+ from .chain.py_order_utils.constants import ZERO_ADDRESS, ZX
17
+ from .chain.py_order_utils.model.signatures import POLY_GNOSIS_SAFE
18
+ from .chain.py_order_utils.model.sides import BUY, SELL, OrderSide
19
+ from .chain.py_order_utils.model.order_type import LIMIT_ORDER, MARKET_ORDER
20
+ from .model import TopicStatus, TopicStatusFilter, TopicType
21
+ from .chain.py_order_utils.utils import calculate_order_amounts
22
+
23
+ API_INTERNAL_ERROR_MSG = "Unable to process your request. Please contact technical support."
24
+ MISSING_MARKET_ID_MSG = "market_id is required."
25
+ MISSING_TOKEN_ID_MSG = "token_id is required."
26
+ MAX_DECIMALS = 18 # Standard maximum for ERC20 tokens (ETH, DAI, etc.)
27
+
28
+ # Supported blockchain chain IDs
29
+ CHAIN_ID_BASE_MAINNET = 8453 # Base mainnet
30
+ SUPPORTED_CHAIN_IDS = [CHAIN_ID_BASE_MAINNET]
31
+
32
+ class InvalidParamError(Exception):
33
+ pass
34
+
35
+ class OpenApiError(Exception):
36
+ pass
37
+
38
+ def safe_amount_to_wei(amount: float, decimals: int) -> int:
39
+ """
40
+ Safely convert human-readable amount to wei units without precision loss.
41
+
42
+ Args:
43
+ amount: Human-readable amount (e.g., 1.5 for 1.5 tokens)
44
+ decimals: Token decimals (e.g., 6 for USDC, 18 for ETH)
45
+
46
+ Returns:
47
+ Integer amount in wei units
48
+
49
+ Raises:
50
+ InvalidParamError: If amount or decimals are invalid
51
+ """
52
+ if amount <= 0:
53
+ raise InvalidParamError(f"Amount must be positive, got: {amount}")
54
+
55
+ if decimals < 0 or decimals > MAX_DECIMALS:
56
+ raise InvalidParamError(f"Decimals must be between 0 and {MAX_DECIMALS}, got: {decimals}")
57
+
58
+ # Use Decimal for exact calculation
59
+ amount_decimal = Decimal(str(amount))
60
+ multiplier = Decimal(10) ** decimals
61
+
62
+ result_decimal = amount_decimal * multiplier
63
+
64
+ # Convert to int
65
+ result = int(result_decimal)
66
+
67
+ # Validate result fits in uint256
68
+ if result >= 2**256:
69
+ raise InvalidParamError(f"Amount too large for uint256: {result}")
70
+
71
+ if result <= 0:
72
+ raise InvalidParamError(f"Calculated amount is zero or negative: {result}")
73
+
74
+ return result
75
+
76
+ class Client:
77
+ def __init__(
78
+ self,
79
+ host: str = '',
80
+ apikey: str = '',
81
+ chain_id: Optional[int] = None,
82
+ rpc_url: str = '',
83
+ private_key: HexStr = HexStr(''),
84
+ multi_sig_addr: str = '',
85
+ conditional_tokens_addr: ChecksumAddress = ChecksumAddress(''),
86
+ multisend_addr: ChecksumAddress = ChecksumAddress(''),
87
+ enable_trading_check_interval: int = 3600,
88
+ quote_tokens_cache_ttl: int = 3600,
89
+ market_cache_ttl: int = 300
90
+ ) -> None:
91
+ """
92
+ Initialize the Opinion CLOB SDK client.
93
+
94
+ Args:
95
+ host: API host URL
96
+ apikey: API authentication key
97
+ chain_id: Blockchain chain ID (8453 for Base mainnet)
98
+ rpc_url: RPC endpoint URL
99
+ private_key: Private key for signing transactions
100
+ multi_sig_addr: Multi-signature wallet address
101
+ conditional_tokens_addr: Conditional tokens contract address
102
+ multisend_addr: Multisend contract address
103
+ enable_trading_check_interval: Time interval (in seconds) to cache enable_trading checks.
104
+ Default is 3600 (1 hour). Set to 0 to check every time.
105
+ This significantly improves performance for frequent operations.
106
+ quote_tokens_cache_ttl: Time interval (in seconds) to cache quote tokens data.
107
+ Default is 3600 (1 hour). Set to 0 to disable caching.
108
+ market_cache_ttl: Time interval (in seconds) to cache market data.
109
+ Default is 300 (5 minutes). Set to 0 to disable caching.
110
+ """
111
+ self.conf = Configuration(host=host)
112
+ self.conf.api_key['ApiKeyAuth'] = apikey
113
+ self.api_key = apikey
114
+ multi_sig_addr = fast_to_checksum_address(multi_sig_addr)
115
+ self.contract_caller = ContractCaller(rpc_url=rpc_url, private_key=private_key, multi_sig_addr=multi_sig_addr,
116
+ conditional_tokens_addr=conditional_tokens_addr,
117
+ multisend_addr=multisend_addr,
118
+ enable_trading_check_interval=enable_trading_check_interval)
119
+ self.api_client = ApiClient(self.conf)
120
+ self.market_api = PredictionMarketApi(self.api_client)
121
+ self.user_api = UserApi(self.api_client)
122
+ # Validate and set chain_id
123
+ if chain_id not in SUPPORTED_CHAIN_IDS:
124
+ raise InvalidParamError(f'chain_id must be one of {SUPPORTED_CHAIN_IDS}')
125
+ self.chain_id = chain_id
126
+
127
+ # Cache configuration
128
+ self.quote_tokens_cache_ttl = quote_tokens_cache_ttl
129
+ self.market_cache_ttl = market_cache_ttl
130
+ self._quote_tokens_cache: Optional[Any] = None
131
+ self._quote_tokens_cache_time: float = 0
132
+ self._market_cache: Dict[int, Tuple[Any, float]] = {} # market_id -> (data, timestamp)
133
+
134
+ def _validate_market_response(self, response: Any, operation_name: str = "operation") -> Any:
135
+ """Validate and extract market data from API response"""
136
+ if hasattr(response, 'errno') and response.errno != 0:
137
+ raise OpenApiError(f"Failed to {operation_name}: {response}")
138
+
139
+ if not hasattr(response, 'result') or not hasattr(response.result, 'data'):
140
+ raise OpenApiError(f"Invalid response format for {operation_name}")
141
+
142
+ return response.result.data
143
+
144
+ def _parse_list_response(self, response: Any, operation_name: str = "operation") -> List[Any]:
145
+ """Parse response that contains a list"""
146
+ if hasattr(response, 'errno') and response.errno != 0:
147
+ raise OpenApiError(f"Failed to {operation_name}: {response}")
148
+
149
+ if not hasattr(response, 'result') or not hasattr(response.result, 'list'):
150
+ raise OpenApiError(f"Invalid list response format for {operation_name}")
151
+
152
+ return response.result.list
153
+
154
+ def enable_trading(self) -> Tuple[Any, Any, Any]:
155
+ quote_token_list_response = self.get_quote_tokens()
156
+ quote_token_list = self._parse_list_response(quote_token_list_response, "get quote tokens")
157
+
158
+ supported_quote_tokens: dict = {}
159
+
160
+ # for each quote token, check if the chain_id is the same as the chain_id in the contract_caller
161
+ for quote_token in quote_token_list:
162
+ quote_token_address = fast_to_checksum_address(quote_token.quote_token_address)
163
+ ctf_exchange_address = fast_to_checksum_address(quote_token.ctf_exchange_address)
164
+ supported_quote_tokens[quote_token_address] = ctf_exchange_address
165
+
166
+ logging.info(f'Supported quote tokens: {supported_quote_tokens}')
167
+ if len(supported_quote_tokens) == 0:
168
+ raise OpenApiError('No supported quote tokens found')
169
+ return self.contract_caller.enable_trading(supported_quote_tokens)
170
+
171
+ def split(self, market_id: int, amount: int, check_approval: bool = True) -> Tuple[Any, Any, Any]:
172
+ """Split collateral into outcome tokens for a market.
173
+
174
+ Args:
175
+ market_id: The market ID to split tokens for (required)
176
+ amount: Amount of collateral to split in wei (required)
177
+ check_approval: Whether to check and enable trading approvals first
178
+ """
179
+ if not market_id or market_id <= 0:
180
+ raise InvalidParamError("market_id must be a positive integer")
181
+ if not amount or amount <= 0:
182
+ raise InvalidParamError("amount must be a positive integer")
183
+
184
+ # Enable trading first for all trade operations.
185
+ if check_approval:
186
+ self.enable_trading()
187
+
188
+ topic_detail = self.get_market(market_id)
189
+ market_data = self._validate_market_response(topic_detail, "get market for split")
190
+
191
+ if int(market_data.chain_id) != self.chain_id:
192
+ raise OpenApiError('Cannot split on different chain')
193
+
194
+ status = market_data.status
195
+ if not (status == TopicStatus.ACTIVATED.value or status == TopicStatus.RESOLVED.value or status == TopicStatus.RESOLVING.value):
196
+ raise OpenApiError('Cannot split on non-activated/resolving/resolved market')
197
+ collateral = fast_to_checksum_address(market_data.quote_token)
198
+ condition_id = market_data.condition_id
199
+
200
+ return self.contract_caller.split(collateral_token=collateral, condition_id=bytes.fromhex(condition_id), amount=amount)
201
+
202
+ def merge(self, market_id: int, amount: int, check_approval: bool = True) -> Tuple[Any, Any, Any]:
203
+ """Merge outcome tokens back into collateral for a market.
204
+
205
+ Args:
206
+ market_id: The market ID to merge tokens for (required)
207
+ amount: Amount of outcome tokens to merge in wei (required)
208
+ check_approval: Whether to check and enable trading approvals first
209
+ """
210
+ if not market_id or market_id <= 0:
211
+ raise InvalidParamError("market_id must be a positive integer")
212
+ if not amount or amount <= 0:
213
+ raise InvalidParamError("amount must be a positive integer")
214
+
215
+ # Enable trading first for all trade operations.
216
+ if check_approval:
217
+ self.enable_trading()
218
+
219
+ topic_detail = self.get_market(market_id)
220
+ market_data = self._validate_market_response(topic_detail, "get market for merge")
221
+
222
+ if int(market_data.chain_id) != self.chain_id:
223
+ raise OpenApiError('Cannot merge on different chain')
224
+
225
+ status = market_data.status
226
+ if not (status == TopicStatus.ACTIVATED.value or status == TopicStatus.RESOLVED.value or status == TopicStatus.RESOLVING.value):
227
+ raise OpenApiError('Cannot merge on non-activated/resolving/resolved market')
228
+ collateral = fast_to_checksum_address(market_data.quote_token)
229
+ condition_id = market_data.condition_id
230
+
231
+ return self.contract_caller.merge(collateral_token=collateral, condition_id=bytes.fromhex(condition_id),
232
+ amount=amount)
233
+
234
+ def redeem(self, market_id: int, check_approval: bool = True) -> Tuple[Any, Any, Any]:
235
+ """Redeem winning outcome tokens for collateral after market resolution.
236
+
237
+ Args:
238
+ market_id: The market ID to redeem tokens for (required)
239
+ check_approval: Whether to check and enable trading approvals first
240
+ """
241
+ if not market_id or market_id <= 0:
242
+ raise InvalidParamError("market_id must be a positive integer")
243
+
244
+ # Enable trading first for all trade operations.
245
+ if check_approval:
246
+ self.enable_trading()
247
+
248
+ topic_detail = self.get_market(market_id)
249
+ market_data = self._validate_market_response(topic_detail, "get market for redeem")
250
+
251
+ if int(market_data.chain_id) != self.chain_id:
252
+ raise OpenApiError('Cannot redeem on different chain')
253
+
254
+ status = market_data.status
255
+ if not status == TopicStatus.RESOLVED.value:
256
+ raise OpenApiError('Cannot redeem on non-resolved market')
257
+ collateral = market_data.quote_token
258
+ condition_id = market_data.condition_id
259
+ logging.info(f'Redeem: collateral={collateral}, condition_id={condition_id}')
260
+ return self.contract_caller.redeem(collateral_token=collateral, condition_id=bytes.fromhex(condition_id))
261
+
262
+ def get_quote_tokens(self, use_cache: bool = True) -> Any:
263
+ """Get list of supported quote tokens
264
+
265
+ Args:
266
+ use_cache: Whether to use cached data if available (default True).
267
+ Set to False to force a fresh API call.
268
+ """
269
+ current_time = time()
270
+
271
+ # Check cache if enabled
272
+ if use_cache and self.quote_tokens_cache_ttl > 0:
273
+ if self._quote_tokens_cache is not None:
274
+ cache_age = current_time - self._quote_tokens_cache_time
275
+ if cache_age < self.quote_tokens_cache_ttl:
276
+ logging.debug(f"Using cached quote tokens (age: {cache_age:.1f}s)")
277
+ return self._quote_tokens_cache
278
+
279
+ # Fetch fresh data
280
+ logging.debug("Fetching fresh quote tokens from API")
281
+ result = self.market_api.openapi_quote_token_get(apikey=self.api_key, chain_id=str(self.chain_id))
282
+
283
+ # Update cache
284
+ if self.quote_tokens_cache_ttl > 0:
285
+ self._quote_tokens_cache = result
286
+ self._quote_tokens_cache_time = current_time
287
+
288
+ return result
289
+
290
+ # Deprecated: use get_quote_tokens() instead
291
+ def get_currencies(self) -> Any:
292
+ """Deprecated: Use get_quote_tokens() instead"""
293
+ return self.get_quote_tokens()
294
+
295
+ def get_markets(
296
+ self,
297
+ topic_type: Optional[TopicType] = None,
298
+ page: int = 1,
299
+ limit: int = 20,
300
+ status: Optional[TopicStatusFilter] = None
301
+ ) -> Any:
302
+ """Get markets with pagination support.
303
+
304
+ Args:
305
+ topic_type: Optional filter by topic type
306
+ page: Page number (>= 1)
307
+ limit: Number of items per page (1-20)
308
+ status: Optional filter by status
309
+ """
310
+ if page < 1:
311
+ raise InvalidParamError("page must be >= 1")
312
+ if not 1 <= limit <= 20:
313
+ raise InvalidParamError("limit must be between 1 and 20")
314
+
315
+ result = self.market_api.openapi_market_get(
316
+ apikey=self.api_key,
317
+ topic_type=topic_type.value if topic_type else None,
318
+ page=page,
319
+ limit=limit,
320
+ chain_id=str(self.chain_id),
321
+ status=status.value if status else None
322
+ )
323
+ return result
324
+
325
+ def get_market(self, market_id, use_cache: bool = True):
326
+ """Get detailed information about a specific market
327
+
328
+ Args:
329
+ market_id: The market ID to query
330
+ use_cache: Whether to use cached data if available (default True).
331
+ Set to False to force a fresh API call.
332
+ """
333
+ try:
334
+ if not market_id:
335
+ raise InvalidParamError(MISSING_MARKET_ID_MSG)
336
+
337
+ current_time = time()
338
+
339
+ # Check cache if enabled
340
+ if use_cache and self.market_cache_ttl > 0:
341
+ if market_id in self._market_cache:
342
+ cached_data, cache_time = self._market_cache[market_id]
343
+ cache_age = current_time - cache_time
344
+ if cache_age < self.market_cache_ttl:
345
+ logging.debug(f"Using cached market {market_id} (age: {cache_age:.1f}s)")
346
+ return cached_data
347
+
348
+ # Fetch fresh data
349
+ logging.debug(f"Fetching fresh market {market_id} from API")
350
+ result = self.market_api.openapi_market_market_id_get(apikey=self.api_key, market_id=market_id)
351
+
352
+ # Update cache
353
+ if self.market_cache_ttl > 0:
354
+ self._market_cache[market_id] = (result, current_time)
355
+
356
+ return result
357
+ except InvalidParamError as e:
358
+ logging.error(f"Validation error: {e}")
359
+ raise
360
+ except Exception as e:
361
+ logging.error(f"API error: {e}")
362
+ raise OpenApiError(f"Failed to get market: {e}")
363
+
364
+ def get_categorical_market(self, market_id):
365
+ """Get detailed information about a categorical market"""
366
+ try:
367
+ if not market_id:
368
+ raise InvalidParamError(MISSING_MARKET_ID_MSG)
369
+
370
+ result = self.market_api.openapi_market_categorical_market_id_get(apikey=self.api_key, market_id=market_id)
371
+ return result
372
+ except InvalidParamError as e:
373
+ logging.error(f"Validation error: {e}")
374
+ raise
375
+ except Exception as e:
376
+ logging.error(f"API error: {e}")
377
+ raise OpenApiError(f"Failed to get categorical market: {e}")
378
+
379
+ def get_price_history(self, token_id, interval="1hour", start_time=int(time()), bars=60):
380
+ """Get price history/candlestick data for a token"""
381
+ try:
382
+ if not token_id:
383
+ raise InvalidParamError(MISSING_TOKEN_ID_MSG)
384
+
385
+ if not interval:
386
+ raise InvalidParamError('interval is required')
387
+
388
+ result = self.market_api.openapi_token_price_history_get(
389
+ apikey=self.api_key,
390
+ token_id=token_id,
391
+ interval=interval,
392
+ start_time=start_time,
393
+ bars=bars
394
+ )
395
+ return result
396
+ except InvalidParamError as e:
397
+ logging.error(f"Validation error: {e}")
398
+ raise
399
+ except Exception as e:
400
+ logging.error(f"API error: {e}")
401
+ raise OpenApiError(f"Failed to get price history: {e}")
402
+
403
+ def get_orderbook(self, token_id):
404
+ """Get orderbook for a specific token"""
405
+ try:
406
+ if not token_id:
407
+ raise InvalidParamError(MISSING_TOKEN_ID_MSG)
408
+
409
+ result = self.market_api.openapi_token_orderbook_get(apikey=self.api_key, token_id=token_id)
410
+ return result
411
+ except InvalidParamError as e:
412
+ logging.error(f"Validation error: {e}")
413
+ raise
414
+ except Exception as e:
415
+ logging.error(f"API error: {e}")
416
+ raise OpenApiError(f"Failed to get orderbook: {e}")
417
+
418
+ def get_latest_price(self, token_id):
419
+ """Get latest price for a token"""
420
+ try:
421
+ if not token_id:
422
+ raise InvalidParamError(MISSING_TOKEN_ID_MSG)
423
+
424
+ result = self.market_api.openapi_token_latest_price_get(apikey=self.api_key, token_id=token_id)
425
+ return result
426
+ except InvalidParamError as e:
427
+ logging.error(f"Validation error: {e}")
428
+ raise
429
+ except Exception as e:
430
+ logging.error(f"API error: {e}")
431
+ raise OpenApiError(f"Failed to get latest price: {e}")
432
+
433
+ def get_fee_rates(self, token_id):
434
+ """Get fee rates for a token"""
435
+ try:
436
+ if not token_id:
437
+ raise InvalidParamError(MISSING_TOKEN_ID_MSG)
438
+
439
+ result = self.market_api.openapi_token_fee_rates_get(apikey=self.api_key, token_id=token_id)
440
+ return result
441
+ except InvalidParamError as e:
442
+ logging.error(f"Validation error: {e}")
443
+ raise
444
+ except Exception as e:
445
+ logging.error(f"API error: {e}")
446
+ raise OpenApiError(f"Failed to get fee rates: {e}")
447
+
448
+ def _place_order(self, data: OrderDataInput, exchange_addr='', chain_id=0, currency_addr='', currency_decimal=0, check_approval=False):
449
+ if check_approval:
450
+ self.enable_trading()
451
+ try:
452
+ if not exchange_addr:
453
+ raise InvalidParamError('exchange_addr is required')
454
+
455
+ # Validate currency_decimal to prevent overflow
456
+ if currency_decimal < 0:
457
+ raise InvalidParamError(f'currency_decimal must be non-negative, got: {currency_decimal}')
458
+ if currency_decimal > MAX_DECIMALS:
459
+ raise InvalidParamError(f'currency_decimal too large (max {MAX_DECIMALS}): {currency_decimal}')
460
+
461
+ chain_id = self.chain_id
462
+
463
+ builder = OrderBuilder(exchange_addr, chain_id, self.contract_caller.signer)
464
+ takerAmount = 0
465
+
466
+ if data.orderType == MARKET_ORDER:
467
+ takerAmount = 0
468
+ data.price = "0"
469
+ # Use safe conversion to avoid precision loss
470
+ recalculated_maker_amount = safe_amount_to_wei(data.makerAmount, currency_decimal)
471
+ if data.orderType == LIMIT_ORDER:
472
+ # Use safe conversion to avoid precision loss
473
+ maker_amount_wei = safe_amount_to_wei(data.makerAmount, currency_decimal)
474
+ recalculated_maker_amount, takerAmount = calculate_order_amounts(
475
+ price=float(data.price),
476
+ maker_amount=maker_amount_wei,
477
+ side=data.side,
478
+ decimals=currency_decimal
479
+ )
480
+
481
+ order_data = OrderData(
482
+ maker=self.contract_caller.multi_sig_addr,
483
+ taker=ZERO_ADDRESS,
484
+ tokenId=data.tokenId,
485
+ makerAmount=recalculated_maker_amount,
486
+ takerAmount=takerAmount,
487
+ feeRateBps='0',
488
+ side=data.side,
489
+ signatureType=POLY_GNOSIS_SAFE,
490
+ signer=self.contract_caller.signer.address()
491
+ )
492
+ signerOrder = builder.build_signed_order(order_data)
493
+
494
+ order_dict = signerOrder.order.dict()
495
+
496
+ # Create V2AddOrderReq object for opinion_api
497
+ from opinion_api.models.v2_add_order_req import V2AddOrderReq
498
+
499
+ v2_add_order_req = V2AddOrderReq(
500
+ salt=str(order_dict['salt']),
501
+ topic_id=data.marketId,
502
+ maker=order_dict['maker'],
503
+ signer=order_dict['signer'],
504
+ taker=order_dict['taker'],
505
+ token_id=str(order_dict['tokenId']),
506
+ maker_amount=str(order_dict['makerAmount']),
507
+ taker_amount=str(order_dict['takerAmount']),
508
+ expiration=str(order_dict['expiration']),
509
+ nonce=str(order_dict['nonce']),
510
+ fee_rate_bps=str(order_dict['feeRateBps']),
511
+ side=str(order_dict['side']),
512
+ signature_type=str(order_dict['signatureType']),
513
+ signature=signerOrder.signature,
514
+ sign=signerOrder.signature,
515
+ contract_address="",
516
+ currency_address=currency_addr,
517
+ price=data.price,
518
+ trading_method=int(data.orderType),
519
+ timestamp=int(time()),
520
+ safe_rate='0',
521
+ order_exp_time='0'
522
+ )
523
+
524
+ result = self.market_api.openapi_order_post(apikey=self.api_key, add_order_req=v2_add_order_req)
525
+ return result
526
+ except InvalidParamError as e:
527
+ logging.error(f"Validation error: {e}")
528
+ raise
529
+ except Exception as e:
530
+ logging.error(f"API error: {e}")
531
+ raise OpenApiError(f"Failed to place order: {e}")
532
+
533
+ def place_order(self, data: PlaceOrderDataInput, check_approval=False):
534
+ """Place an order on the market"""
535
+ quote_token_list_response = self.get_quote_tokens()
536
+ quote_token_list = self._parse_list_response(quote_token_list_response, "get quote tokens")
537
+
538
+ market_response = self.get_market(data.marketId)
539
+ market = self._validate_market_response(market_response, "get market for place order")
540
+
541
+ if int(market.chain_id) != self.chain_id:
542
+ raise OpenApiError('Cannot place order on different chain')
543
+
544
+ quote_token_addr = market.quote_token
545
+
546
+ # find quote token from quote_token_list by quote_token_address
547
+ quote_token = next((item for item in quote_token_list if str.lower(item.quote_token_address) == str.lower(quote_token_addr)), None)
548
+ if not quote_token:
549
+ raise OpenApiError('Quote token not found for this market')
550
+
551
+ exchange_addr = quote_token.ctf_exchange_address
552
+ chain_id = quote_token.chain_id
553
+
554
+ makerAmount = 0
555
+ minimal_maker_amount = 1
556
+
557
+ # reject if market buy and makerAmountInBaseToken is provided
558
+ if(data.side == OrderSide.BUY and data.orderType == MARKET_ORDER and data.makerAmountInBaseToken):
559
+ raise InvalidParamError('makerAmountInBaseToken is not allowed for market buy')
560
+
561
+ # reject if market sell and makerAmountInQuoteToken is provided
562
+ if(data.side == OrderSide.SELL and data.orderType == MARKET_ORDER and data.makerAmountInQuoteToken):
563
+ raise InvalidParamError('makerAmountInQuoteToken is not allowed for market sell')
564
+
565
+ # Validate price for limit orders (prevent division by zero)
566
+ if data.orderType == LIMIT_ORDER:
567
+ try:
568
+ price_decimal = Decimal(str(data.price))
569
+ if price_decimal <= 0:
570
+ raise InvalidParamError(f'Price must be positive for limit orders, got: {data.price}')
571
+ except (ValueError, TypeError, InvalidParamError):
572
+ raise
573
+ except Exception as e:
574
+ raise InvalidParamError(f'Invalid price format: {data.price}') from e
575
+
576
+ # need amount to be in quote token
577
+ if(data.side == OrderSide.BUY):
578
+ # e.g. yes/no
579
+ if(data.makerAmountInBaseToken):
580
+ # Use Decimal for precise calculation to avoid floating point errors
581
+ base_amount = Decimal(str(data.makerAmountInBaseToken))
582
+ price_decimal = Decimal(str(data.price))
583
+ makerAmount = float(base_amount * price_decimal)
584
+ # makerAmountInBaseToken should be at least 1 otherwise throw error
585
+ if(float(data.makerAmountInBaseToken) < minimal_maker_amount):
586
+ raise InvalidParamError("makerAmountInBaseToken must be at least 1")
587
+ # e.g. usdc
588
+ elif(data.makerAmountInQuoteToken):
589
+ makerAmount = float(data.makerAmountInQuoteToken)
590
+ # makerAmountInQuoteToken should be at least 1 otherwise throw error
591
+ if(float(data.makerAmountInQuoteToken) < minimal_maker_amount):
592
+ raise InvalidParamError("makerAmountInQuoteToken must be at least 1")
593
+ else:
594
+ raise InvalidParamError("Either makerAmountInBaseToken or makerAmountInQuoteToken must be provided for BUY orders")
595
+
596
+ elif(data.side == OrderSide.SELL):
597
+ # e.g. yes/no
598
+ if(data.makerAmountInBaseToken):
599
+ makerAmount = float(data.makerAmountInBaseToken)
600
+ # makerAmountInBaseToken should be at least 1 otherwise throw error
601
+ if(float(data.makerAmountInBaseToken) < minimal_maker_amount):
602
+ raise InvalidParamError("makerAmountInBaseToken must be at least 1")
603
+ # e.g. usdc
604
+ elif(data.makerAmountInQuoteToken):
605
+ # Use Decimal for precise division to avoid floating point errors
606
+ quote_amount = Decimal(str(data.makerAmountInQuoteToken))
607
+ price_decimal = Decimal(str(data.price))
608
+ if price_decimal == 0:
609
+ raise InvalidParamError("Price cannot be zero for SELL orders with makerAmountInQuoteToken")
610
+ makerAmount = float(quote_amount / price_decimal)
611
+ # makerAmountInQuoteToken should be at least 1 otherwise throw error
612
+ if(float(data.makerAmountInQuoteToken) < minimal_maker_amount):
613
+ raise InvalidParamError("makerAmountInQuoteToken must be at least 1")
614
+ else:
615
+ raise InvalidParamError("Either makerAmountInBaseToken or makerAmountInQuoteToken must be provided for SELL orders")
616
+
617
+ # Final validation: ensure makerAmount was properly calculated
618
+ if makerAmount <= 0:
619
+ raise InvalidParamError(f"Calculated makerAmount must be positive, got: {makerAmount}")
620
+
621
+
622
+ input = OrderDataInput(
623
+ marketId=data.marketId,
624
+ tokenId=data.tokenId,
625
+ makerAmount=makerAmount,
626
+ price=data.price,
627
+ orderType=data.orderType,
628
+ side=data.side
629
+ )
630
+
631
+ return self._place_order(input, exchange_addr, chain_id, quote_token_addr, int(quote_token.decimal), check_approval)
632
+
633
+ def cancel_order(self, order_id):
634
+ """
635
+ Cancel an existing order.
636
+
637
+ Args:
638
+ order_id: Order ID to cancel (str)
639
+
640
+ Returns:
641
+ API response for order cancellation
642
+ """
643
+ if not order_id or not isinstance(order_id, str):
644
+ raise InvalidParamError('order_id must be a non-empty string')
645
+
646
+ from opinion_api.models.openapi_cancel_order_request_open_api import OpenapiCancelOrderRequestOpenAPI
647
+
648
+ # Internally use trans_no for API compatibility
649
+ request_body = OpenapiCancelOrderRequestOpenAPI(trans_no=order_id)
650
+ result = self.market_api.openapi_order_cancel_post(apikey=self.api_key, cancel_order_req=request_body)
651
+ return result
652
+
653
+ def place_orders_batch(self, orders: List[PlaceOrderDataInput], check_approval: bool = False) -> List[Any]:
654
+ """
655
+ Place multiple orders in batch to reduce API calls.
656
+
657
+ Args:
658
+ orders: List of PlaceOrderDataInput objects
659
+ check_approval: Whether to check and enable trading approvals first (done once for all orders)
660
+
661
+ Returns:
662
+ List of order placement results
663
+
664
+ Raises:
665
+ InvalidParamError: If orders list is empty or invalid
666
+ """
667
+ if not orders or not isinstance(orders, list):
668
+ raise InvalidParamError('orders must be a non-empty list')
669
+
670
+ if len(orders) == 0:
671
+ raise InvalidParamError('orders list cannot be empty')
672
+
673
+ # Enable trading once for all orders if needed
674
+ if check_approval:
675
+ self.enable_trading()
676
+
677
+ results = []
678
+ errors = []
679
+
680
+ for i, order in enumerate(orders):
681
+ try:
682
+ # Place each order without checking approval again
683
+ result = self.place_order(order, check_approval=False)
684
+ results.append({
685
+ 'index': i,
686
+ 'success': True,
687
+ 'result': result,
688
+ 'order': order
689
+ })
690
+ except Exception as e:
691
+ logging.error(f"Failed to place order at index {i}: {e}")
692
+ errors.append({
693
+ 'index': i,
694
+ 'success': False,
695
+ 'error': str(e),
696
+ 'order': order
697
+ })
698
+ results.append({
699
+ 'index': i,
700
+ 'success': False,
701
+ 'error': str(e),
702
+ 'order': order
703
+ })
704
+
705
+ if errors:
706
+ logging.warning(f"Batch order placement completed with {len(errors)} errors out of {len(orders)} orders")
707
+
708
+ return results
709
+
710
+ def cancel_orders_batch(self, order_ids: List[str]) -> List[Any]:
711
+ """
712
+ Cancel multiple orders in batch.
713
+
714
+ Args:
715
+ order_ids: List of order IDs to cancel
716
+
717
+ Returns:
718
+ List of cancellation results
719
+
720
+ Raises:
721
+ InvalidParamError: If order_ids list is empty or invalid
722
+ """
723
+ if not order_ids or not isinstance(order_ids, list):
724
+ raise InvalidParamError('order_ids must be a non-empty list')
725
+
726
+ if len(order_ids) == 0:
727
+ raise InvalidParamError('order_ids list cannot be empty')
728
+
729
+ results = []
730
+ errors = []
731
+
732
+ for i, order_id in enumerate(order_ids):
733
+ try:
734
+ result = self.cancel_order(order_id)
735
+ results.append({
736
+ 'index': i,
737
+ 'success': True,
738
+ 'result': result,
739
+ 'order_id': order_id
740
+ })
741
+ except Exception as e:
742
+ logging.error(f"Failed to cancel order {order_id}: {e}")
743
+ errors.append({
744
+ 'index': i,
745
+ 'success': False,
746
+ 'error': str(e),
747
+ 'order_id': order_id
748
+ })
749
+ results.append({
750
+ 'index': i,
751
+ 'success': False,
752
+ 'error': str(e),
753
+ 'order_id': order_id
754
+ })
755
+
756
+ if errors:
757
+ logging.warning(f"Batch order cancellation completed with {len(errors)} errors out of {len(order_ids)} orders")
758
+
759
+ return results
760
+
761
+ def cancel_all_orders(self, market_id: Optional[int] = None, side: Optional[OrderSide] = None) -> dict:
762
+ """
763
+ Cancel all open orders, optionally filtered by market and/or side.
764
+
765
+ Args:
766
+ market_id: Optional filter - only cancel orders for this market
767
+ side: Optional filter - only cancel BUY or SELL orders
768
+
769
+ Returns:
770
+ Dictionary with cancellation summary: {
771
+ 'total_orders': int,
772
+ 'cancelled': int,
773
+ 'failed': int,
774
+ 'results': List[dict]
775
+ }
776
+ """
777
+ # Get all open orders
778
+ all_orders = self.get_my_orders(
779
+ market_id=market_id if market_id else 0,
780
+ status='open',
781
+ limit=100, # Get up to 100 orders per page
782
+ page=1
783
+ )
784
+
785
+ # Parse response to get order list
786
+ orders_list = self._parse_list_response(all_orders, "get open orders for cancellation")
787
+
788
+ if not orders_list or len(orders_list) == 0:
789
+ logging.info("No open orders to cancel")
790
+ return {
791
+ 'total_orders': 0,
792
+ 'cancelled': 0,
793
+ 'failed': 0,
794
+ 'results': []
795
+ }
796
+
797
+ # Filter by side if specified
798
+ if side:
799
+ orders_list = [order for order in orders_list if int(order.side) == int(side.value)]
800
+
801
+ # Extract order IDs (internally stored as trans_no)
802
+ order_ids = [order.trans_no for order in orders_list if hasattr(order, 'trans_no')]
803
+
804
+ if not order_ids:
805
+ logging.info("No orders match the filter criteria")
806
+ return {
807
+ 'total_orders': 0,
808
+ 'cancelled': 0,
809
+ 'failed': 0,
810
+ 'results': []
811
+ }
812
+
813
+ # Cancel all orders in batch
814
+ results = self.cancel_orders_batch(order_ids)
815
+
816
+ # Count successes and failures
817
+ cancelled = sum(1 for r in results if r.get('success'))
818
+ failed = sum(1 for r in results if not r.get('success'))
819
+
820
+ logging.info(f"Cancelled {cancelled} orders, {failed} failed out of {len(order_ids)} total")
821
+
822
+ return {
823
+ 'total_orders': len(order_ids),
824
+ 'cancelled': cancelled,
825
+ 'failed': failed,
826
+ 'results': results
827
+ }
828
+
829
+ def get_my_orders(self, market_id=0, status="", limit=10, page=1):
830
+ """Get user's orders with optional filters"""
831
+ try:
832
+ if not isinstance(market_id, int):
833
+ raise InvalidParamError('market_id must be an integer')
834
+
835
+ result = self.market_api.openapi_order_get(
836
+ apikey=self.api_key,
837
+ topic_id=market_id if market_id > 0 else None,
838
+ status=status if status else None,
839
+ limit=limit,
840
+ page=page,
841
+ chain_id=str(self.chain_id)
842
+ )
843
+ return result
844
+ except InvalidParamError as e:
845
+ logging.error(f"Validation error: {e}")
846
+ raise
847
+ except Exception as e:
848
+ logging.error(f"API error: {e}")
849
+ raise OpenApiError(f"Failed to get orders: {e}")
850
+
851
+ def get_order_by_id(self, order_id):
852
+ """Get detailed information about a specific order"""
853
+ try:
854
+ if not order_id or not isinstance(order_id, str):
855
+ raise InvalidParamError('order_id must be a non-empty string')
856
+
857
+ result = self.market_api.openapi_order_order_id_get(apikey=self.api_key, order_id=order_id)
858
+ return result
859
+ except InvalidParamError as e:
860
+ logging.error(f"Validation error: {e}")
861
+ raise
862
+ except Exception as e:
863
+ logging.error(f"API error: {e}")
864
+ raise OpenApiError(f"Failed to get order by id: {e}")
865
+
866
+ def get_my_positions(
867
+ self,
868
+ market_id: int = 0,
869
+ page: int = 1,
870
+ limit: int = 10
871
+ ) -> Any:
872
+ """Get user's positions with optional filters
873
+
874
+ Args:
875
+ market_id: Optional filter by market ID (0 for all markets)
876
+ page: Page number (default 1)
877
+ limit: Number of items per page (default 10)
878
+ """
879
+ try:
880
+ if not isinstance(market_id, int):
881
+ raise InvalidParamError('market_id must be an integer')
882
+
883
+ if not isinstance(page, int):
884
+ raise InvalidParamError('page must be an integer')
885
+
886
+ if not isinstance(limit, int):
887
+ raise InvalidParamError('limit must be an integer')
888
+
889
+ result = self.market_api.openapi_positions_get(
890
+ apikey=self.api_key,
891
+ topic_id=market_id if market_id > 0 else None,
892
+ page=page,
893
+ limit=limit,
894
+ chain_id=str(self.chain_id)
895
+ )
896
+ return result
897
+ except InvalidParamError as e:
898
+ logging.error(f"Validation error: {e}")
899
+ raise
900
+ except Exception as e:
901
+ logging.error(f"API error: {e}")
902
+ raise OpenApiError(f"Failed to get positions: {e}")
903
+
904
+ def get_my_balances(self, wallet_address=None):
905
+ """Get user's balances"""
906
+ try:
907
+ if not wallet_address:
908
+ wallet_address = self.contract_caller.signer.address()
909
+
910
+ result = self.market_api.openapi_user_balance_get(
911
+ apikey=self.api_key,
912
+ wallet_address=wallet_address,
913
+ chain_id=str(self.chain_id)
914
+ )
915
+ return result
916
+ except Exception as e:
917
+ logging.error(f"API error: {e}")
918
+ raise OpenApiError(f"Failed to get balances: {e}")
919
+
920
+ def get_my_trades(self, market_id=0, limit=10):
921
+ """Get user's trade history"""
922
+ try:
923
+ if not isinstance(market_id, int):
924
+ raise InvalidParamError('market_id must be an integer')
925
+
926
+ result = self.market_api.openapi_trade_get(
927
+ apikey=self.api_key,
928
+ topic_id=market_id if market_id > 0 else None,
929
+ limit=limit,
930
+ chain_id=str(self.chain_id)
931
+ )
932
+ return result
933
+ except InvalidParamError as e:
934
+ logging.error(f"Validation error: {e}")
935
+ raise
936
+ except Exception as e:
937
+ logging.error(f"API error: {e}")
938
+ raise OpenApiError(f"Failed to get trades: {e}")
939
+
940
+ def get_user_auth(self):
941
+ """Get authenticated user information"""
942
+ try:
943
+ result = self.user_api.openapi_user_auth_get(apikey=self.api_key)
944
+ return result
945
+ except Exception as e:
946
+ logging.error(f"API error: {e}")
947
+ raise OpenApiError(f"Failed to get user auth: {e}")