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