predict-sdk 0.1.0

Rust SDK for Predict.fun prediction market - order building, EIP-712 signing, and real-time WebSocket data
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
/// HTTP client for the predict.fun REST API
///
/// This module provides a client for interacting with the predict.fun API,
/// including fetching markets, orderbooks, placing/cancelling orders, and JWT authentication.

use crate::api_types::*;
use crate::errors::{Error, Result};
use crate::onchain::{OnchainClient, SplitOptions};
use crate::order_builder::OrderBuilder;
use crate::types::{BuildOrderInput, ChainId, LimitOrderData, OrderStrategy, Side};
use alloy::signers::local::PrivateKeySigner;
use alloy::signers::Signer;
use reqwest::Client as HttpClient;
use rust_decimal::Decimal;
use std::sync::Arc;
use tracing::{debug, info};

/// Client for interacting with predict.fun
pub struct PredictClient {
    order_builder: Arc<OrderBuilder>,
    http_client: HttpClient,
    api_base_url: String,
    chain_id: ChainId,
    api_key: Option<String>,
    jwt_token: std::sync::RwLock<Option<String>>,
}

impl PredictClient {
    /// Create a new PredictClient with full trading capability
    pub fn new(
        chain_id: u64,
        private_key: &str,
        api_base_url: String,
        api_key: Option<String>,
    ) -> Result<Self> {
        let chain_id = ChainId::try_from(chain_id)?;
        let signer = Self::parse_private_key(private_key)?;
        let order_builder =
            OrderBuilder::new(chain_id, Some(signer), None).map_err(|e| Error::Other(e.to_string()))?;

        Ok(Self {
            order_builder: Arc::new(order_builder),
            http_client: HttpClient::new(),
            api_base_url,
            chain_id,
            api_key,
            jwt_token: std::sync::RwLock::new(None),
        })
    }

    /// Create a new PredictClient with Predict Smart Wallet (Kernel) signing
    pub fn new_with_predict_account(
        chain_id: u64,
        privy_private_key: &str,
        predict_account: &str,
        api_base_url: String,
        api_key: Option<String>,
    ) -> Result<Self> {
        let chain_id = ChainId::try_from(chain_id)?;
        let signer = Self::parse_private_key(privy_private_key)?;
        let order_builder = OrderBuilder::with_predict_account(
            chain_id,
            signer,
            predict_account,
            None,
        ).map_err(|e| Error::Other(e.to_string()))?;

        Ok(Self {
            order_builder: Arc::new(order_builder),
            http_client: HttpClient::new(),
            api_base_url,
            chain_id,
            api_key,
            jwt_token: std::sync::RwLock::new(None),
        })
    }

    /// Create a read-only PredictClient for market data operations
    pub fn new_readonly(
        chain_id: u64,
        api_base_url: String,
        api_key: Option<String>,
    ) -> Result<Self> {
        let chain_id = ChainId::try_from(chain_id)?;
        let order_builder =
            OrderBuilder::new(chain_id, None, None).map_err(|e| Error::Other(e.to_string()))?;

        Ok(Self {
            order_builder: Arc::new(order_builder),
            http_client: HttpClient::new(),
            api_base_url,
            chain_id,
            api_key,
            jwt_token: std::sync::RwLock::new(None),
        })
    }

    /// Check if this client has signing capability
    pub fn can_sign(&self) -> bool {
        self.order_builder.signer_address().is_ok()
    }

    /// Check if this client uses Predict Account (Kernel) signing
    pub fn uses_predict_account(&self) -> bool {
        self.order_builder.uses_predict_account()
    }

    /// Get the Predict Account address if configured
    pub fn predict_account(&self) -> Option<String> {
        self.order_builder.predict_account().map(|addr| format!("{}", addr))
    }

    /// Parse private key from hex string
    fn parse_private_key(private_key: &str) -> Result<PrivateKeySigner> {
        let key = private_key.trim().trim_start_matches("0x");
        let bytes = hex::decode(key)
            .map_err(|e| Error::ConfigError(format!("Invalid private key format: {}", e)))?;

        if bytes.len() != 32 {
            return Err(Error::ConfigError("Private key must be 32 bytes".into()));
        }

        let mut key_bytes = [0u8; 32];
        key_bytes.copy_from_slice(&bytes);

        PrivateKeySigner::from_bytes(&key_bytes.into())
            .map_err(|e| Error::ConfigError(format!("Failed to create signer: {}", e)))
    }

    /// Add authentication headers to a request
    ///
    /// Adds `x-api-key` if configured, and `Authorization: Bearer {jwt}` if authenticated.
    fn add_auth_headers(&self, request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
        let mut request = request;
        if let Some(ref api_key) = self.api_key {
            request = request.header("x-api-key", api_key);
        }
        if let Ok(guard) = self.jwt_token.read() {
            if let Some(ref jwt) = *guard {
                request = request.header("Authorization", format!("Bearer {}", jwt));
            }
        }
        request
    }

    // ========================================================================
    // Authentication
    // ========================================================================

    /// Authenticate with Predict API and obtain a JWT token
    ///
    /// Flow:
    /// 1. GET /v1/auth/message → dynamic message to sign
    /// 2. Sign message with wallet private key (EIP-191 personal sign)
    /// 3. POST /v1/auth → submit signature → receive JWT
    ///
    /// The JWT is required for authenticated WebSocket subscriptions
    /// (e.g., `predictWalletEvents/{jwt}` for order fill notifications).
    pub async fn authenticate(&self) -> Result<String> {
        let signer = self.order_builder.signer()
            .ok_or_else(|| Error::Other("No signer configured - cannot authenticate".into()))?;

        // Step 1: Get the dynamic auth message
        let url = format!("{}/v1/auth/message", self.api_base_url);
        let request = self.add_auth_headers(self.http_client.get(&url));
        let response = request.send().await?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            return Err(Error::ApiError(format!(
                "Failed to get auth message: {}", error_text
            )));
        }

        let auth_msg: AuthMessageResponse = response.json().await?;
        if !auth_msg.success {
            return Err(Error::ApiError("Auth message request returned success=false".into()));
        }

        let message = auth_msg.data.message;
        debug!("Got auth message to sign: {}", &message[..message.len().min(50)]);

        // Step 2: Sign the message
        // For Predict Accounts: use Kernel-wrapped signing, signer = predict_account
        // For EOA: use plain EIP-191 personal sign, signer = EOA address
        let (signature_hex, signer_address) = if let Some(predict_account) = self.order_builder.predict_account() {
            let ecdsa_validator = self.order_builder.addresses().ecdsa_validator
                .parse::<alloy::primitives::Address>()
                .map_err(|e| Error::Other(format!("Invalid ECDSA validator address: {}", e)))?;

            let sig = crate::internal::signing::sign_message_for_predict_account(
                message.as_bytes(),
                self.chain_id,
                predict_account,
                ecdsa_validator,
                &signer,
            ).await?;

            (sig, format!("{}", predict_account))
        } else {
            let signature = signer
                .sign_message(message.as_bytes())
                .await
                .map_err(|e| Error::SigningError(format!("Failed to sign auth message: {}", e)))?;

            let mut sig_bytes = signature.as_bytes().to_vec();
            if sig_bytes[64] < 27 {
                sig_bytes[64] += 27;
            }

            (format!("0x{}", hex::encode(sig_bytes)), format!("{}", signer.address()))
        };

        // Step 3: Submit signature to get JWT
        let url = format!("{}/v1/auth", self.api_base_url);
        let auth_request = AuthRequest {
            signer: signer_address,
            signature: signature_hex,
            message,
        };

        let request = self.add_auth_headers(self.http_client.post(&url))
            .json(&auth_request);
        let response = request.send().await?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            return Err(Error::ApiError(format!(
                "Failed to authenticate: {}", error_text
            )));
        }

        let auth_response: AuthResponse = response.json().await?;
        if !auth_response.success {
            return Err(Error::ApiError("Authentication returned success=false".into()));
        }

        info!("Successfully authenticated with Predict API");
        Ok(auth_response.data.token)
    }

    /// Authenticate and store the JWT token for subsequent REST API requests
    ///
    /// This calls `authenticate()` and stores the resulting JWT so that
    /// `add_auth_headers()` will include `Authorization: Bearer {jwt}` on all requests.
    pub async fn authenticate_and_store(&self) -> Result<String> {
        let jwt = self.authenticate().await?;
        if let Ok(mut guard) = self.jwt_token.write() {
            *guard = Some(jwt.clone());
        }
        Ok(jwt)
    }

    /// Get the stored JWT token (if authenticated)
    pub fn jwt_token(&self) -> Option<String> {
        self.jwt_token.read().ok().and_then(|guard| guard.clone())
    }

    // ========================================================================
    // Market Data
    // ========================================================================

    /// Fetch all markets from Predict
    pub async fn get_markets(&self) -> Result<Vec<PredictMarket>> {
        let url = format!("{}/markets", self.api_base_url);
        debug!("Fetching markets from: {}", url);

        let response = self.http_client.get(&url).send().await?;

        if !response.status().is_success() {
            return Err(Error::ApiError(format!(
                "Failed to fetch markets: status={}",
                response.status()
            )));
        }

        let markets: Vec<PredictMarket> = response.json().await?;
        info!("Fetched {} markets from Predict", markets.len());
        Ok(markets)
    }

    /// Fetch orderbook for a specific market
    pub async fn get_orderbook(&self, market_id: &str) -> Result<PredictOrderBook> {
        let url = format!("{}/markets/{}/orderbook", self.api_base_url, market_id);
        debug!("Fetching orderbook from: {}", url);

        let response = self.http_client.get(&url).send().await?;

        if !response.status().is_success() {
            return Err(Error::ApiError(format!(
                "Failed to fetch orderbook for market {}: status={}",
                market_id,
                response.status()
            )));
        }

        let orderbook: PredictOrderBook = response.json().await?;
        Ok(orderbook)
    }

    // ========================================================================
    // Order Management
    // ========================================================================

    /// Place a limit order on Predict
    ///
    /// Builds, signs, and submits a limit order to the Predict API.
    /// Returns the order ID and hash on success.
    pub async fn place_limit_order(
        &self,
        token_id: &str,
        side: Side,
        price: Decimal,
        quantity: Decimal,
        is_neg_risk: bool,
        is_yield_bearing: bool,
        fee_rate_bps: u64,
    ) -> Result<PlaceOrderResponse> {
        info!(
            "Placing limit order: token_id={}, side={:?}, price={}, quantity={}",
            token_id, side, price, quantity
        );

        // Calculate order amounts
        let amounts = self
            .order_builder
            .get_limit_order_amounts(LimitOrderData {
                side,
                price_per_share_wei: price,
                quantity_wei: quantity,
            })
            .map_err(|e| Error::Other(format!("Failed to calculate order amounts: {}", e)))?;

        // Build order - let build_order handle maker/signer based on config:
        // - With predict_account: maker=predict_account, signer=predict_account (matching official SDKs)
        // - Without: maker=EOA, signer=EOA
        let order = self
            .order_builder
            .build_order(
                OrderStrategy::Limit,
                BuildOrderInput {
                    side,
                    token_id: token_id.to_string(),
                    maker_amount: amounts.maker_amount.trunc().to_string(),
                    taker_amount: amounts.taker_amount.trunc().to_string(),
                    fee_rate_bps,
                    signer: None,
                    nonce: None,
                    salt: None,
                    maker: None,
                    taker: None,
                    signature_type: None,
                    expires_at: None,
                },
            )
            .map_err(|e| Error::Other(format!("Failed to build order: {}", e)))?;

        let verifying_contract = self.order_builder.get_verifying_contract(is_neg_risk, is_yield_bearing);
        info!(
            "Signing order: chain_id={:?}, is_neg_risk={}, is_yield_bearing={}, verifying_contract={}, maker={}, signer={}, uses_predict_account={}",
            self.chain_id, is_neg_risk, is_yield_bearing, verifying_contract,
            order.maker, order.signer, self.order_builder.uses_predict_account(),
        );

        // Sign order — automatically uses Kernel-wrapped signing for predict accounts,
        // or plain EOA EIP-712 for direct wallets.
        let signed_order = self
            .order_builder
            .sign_typed_data_order(order, is_neg_risk, is_yield_bearing)
            .await
            .map_err(|e| Error::Other(format!("Failed to sign order: {}", e)))?;

        // Build the API request body per Predict API spec:
        // POST /v1/orders with body: {"data": {"order": {...}, "pricePerShare": "...", "strategy": "LIMIT"}}
        let order_json = serde_json::to_value(&signed_order)?;
        let price_per_share = amounts.price_per_share.to_string();

        let request_body = CreateOrderRequest {
            data: CreateOrderData {
                order: order_json,
                price_per_share,
                strategy: "LIMIT".to_string(),
            },
        };

        info!("Order request body: {}", serde_json::to_string(&request_body).unwrap_or_default());

        // Submit to API
        let url = format!("{}/v1/orders", self.api_base_url);
        let request = self.add_auth_headers(self.http_client.post(&url))
            .json(&request_body);
        let response = request.send().await?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response
                .text()
                .await
                .unwrap_or_else(|_| "Unknown error".to_string());
            return Err(Error::ApiError(format!(
                "Failed to place order: status={}, error={}",
                status, error_text
            )));
        }

        let place_response: PlaceOrderResponse = response.json().await?;

        if !place_response.success {
            return Err(Error::ApiError("Order placement returned success=false".into()));
        }

        if let Some(ref data) = place_response.data {
            info!(
                "Order placed successfully: order_id={}, hash={}",
                data.order_id, data.order_hash
            );
        }

        Ok(place_response)
    }

    /// Cancel orders by their IDs
    ///
    /// Removes orders from the Predict orderbook.
    /// Note: This removes orders from the orderbook but does not cancel on-chain.
    ///
    /// # Arguments
    /// * `order_ids` - Order IDs to cancel (max 100)
    pub async fn cancel_orders(&self, order_ids: &[String]) -> Result<RemoveOrdersResponse> {
        if order_ids.is_empty() {
            return Ok(RemoveOrdersResponse {
                success: true,
                removed: vec![],
                noop: vec![],
            });
        }

        if order_ids.len() > 100 {
            return Err(Error::Other("Cannot cancel more than 100 orders at once".into()));
        }

        info!("Cancelling {} orders on Predict", order_ids.len());

        let request_body = RemoveOrdersRequest {
            data: RemoveOrdersData {
                ids: order_ids.to_vec(),
            },
        };

        let url = format!("{}/v1/orders/remove", self.api_base_url);
        let request = self.add_auth_headers(self.http_client.post(&url))
            .json(&request_body);
        let response = request.send().await?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response.text().await.unwrap_or_default();
            return Err(Error::ApiError(format!(
                "Failed to cancel orders: status={}, error={}",
                status, error_text
            )));
        }

        let cancel_response: RemoveOrdersResponse = response.json().await?;

        info!(
            "Cancel result: removed={}, noop={}",
            cancel_response.removed.len(),
            cancel_response.noop.len()
        );

        Ok(cancel_response)
    }

    /// Fetch open orders for this account
    ///
    /// Returns all orders with status OPEN for the authenticated user.
    pub async fn get_open_orders(&self) -> Result<Vec<PredictOrder>> {
        let url = format!("{}/v1/orders?status=OPEN", self.api_base_url);
        debug!("Fetching open orders from: {}", url);

        let request = self.add_auth_headers(self.http_client.get(&url));
        let response = request.send().await?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response.text().await.unwrap_or_default();
            return Err(Error::ApiError(format!(
                "Failed to fetch open orders: status={}, error={}",
                status, error_text
            )));
        }

        let body = response.text().await?;
        debug!("get_open_orders raw response: {}", &body[..500.min(body.len())]);

        let orders_response: GetOrdersResponse = serde_json::from_str(&body)
            .map_err(|e| Error::ApiError(format!(
                "Failed to parse open orders: {} | body: {}",
                e, &body[..500.min(body.len())]
            )))?;

        if !orders_response.success {
            return Err(Error::ApiError("Get orders returned success=false".into()));
        }

        debug!("Fetched {} open orders", orders_response.data.len());
        Ok(orders_response.data)
    }

    /// Fetch positions (token balances) for this account
    pub async fn get_positions(&self) -> Result<Vec<PredictPosition>> {
        let url = format!("{}/v1/positions", self.api_base_url);
        debug!("Fetching positions from: {}", url);

        let request = self.add_auth_headers(self.http_client.get(&url));
        let response = request.send().await?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response.text().await.unwrap_or_default();
            return Err(Error::ApiError(format!(
                "Failed to fetch positions: status={}, error={}",
                status, error_text
            )));
        }

        let positions_response: GetPositionsResponse = response.json().await?;

        if !positions_response.success {
            return Err(Error::ApiError("Get positions returned success=false".into()));
        }

        debug!("Fetched {} positions", positions_response.data.len());
        Ok(positions_response.data)
    }

    // ========================================================================
    // Accessors
    // ========================================================================

    /// Get the signer address
    pub fn signer_address(&self) -> Result<String> {
        self.order_builder
            .signer_address()
            .map(|addr| format!("{}", addr))
            .map_err(|e| Error::Other(format!("Failed to get signer address: {}", e)))
    }

    /// Get the chain ID
    pub fn chain_id(&self) -> ChainId {
        self.chain_id
    }

    /// Get the API key (if set)
    pub fn api_key(&self) -> Option<&str> {
        self.api_key.as_deref()
    }

    /// Get the order builder
    pub fn order_builder(&self) -> &OrderBuilder {
        &self.order_builder
    }

    /// Get the API base URL
    pub fn api_base_url(&self) -> &str {
        &self.api_base_url
    }

    // ========================================================================
    // Category API for Market Matching
    // ========================================================================

    /// Fetch a category by slug from Predict
    pub async fn get_category(&self, slug: &str) -> Result<PredictCategory> {
        let url = format!("{}/v1/categories/{}", self.api_base_url, slug);
        debug!("Fetching category from: {}", url);

        let request = self.add_auth_headers(self.http_client.get(&url));
        let response = request.send().await?;
        let status = response.status();

        if status == reqwest::StatusCode::NOT_FOUND {
            return Err(Error::ApiError(format!("Category not found: slug={}", slug)));
        }

        if !status.is_success() {
            let error_text = response
                .text()
                .await
                .unwrap_or_else(|_| "Unknown error".to_string());
            return Err(Error::ApiError(format!(
                "Failed to fetch category {}: status={}, error={}",
                slug, status, error_text
            )));
        }

        let wrapper: CategoryResponse = response.json().await?;
        debug!(
            "Fetched category '{}' with {} markets",
            wrapper.data.slug,
            wrapper.data.markets.len()
        );

        Ok(wrapper.data)
    }

    /// Fetch a category by slug, returning None if not found
    pub async fn get_category_optional(&self, slug: &str) -> Result<Option<PredictCategory>> {
        match self.get_category(slug).await {
            Ok(category) => Ok(Some(category)),
            Err(Error::ApiError(msg)) if msg.contains("not found") => Ok(None),
            Err(e) => Err(e),
        }
    }

    // ========================================================================
    // On-chain Operations (Split/Merge/Approvals)
    // ========================================================================

    /// Set all necessary on-chain approvals for trading.
    ///
    /// This must be called once before placing orders. It sets:
    /// - ERC-1155 approval on Conditional Tokens for the CTF Exchange
    /// - ERC-20 approval on USDT for the CTF Exchange
    /// - Neg Risk Adapter approval (if is_neg_risk)
    pub async fn set_approvals(
        &self,
        is_neg_risk: bool,
        is_yield_bearing: bool,
    ) -> Result<()> {
        let signer = self
            .order_builder
            .signer()
            .ok_or_else(|| Error::Other("No signer configured - cannot set approvals".into()))?;

        // Approvals must be set for the trading address (predict_account or EOA).
        // For predict_account: the smart wallet holds tokens, so it needs approvals.
        // set_approvals checks `trading_address()` which returns predict_account if set.
        let onchain_client = if let Some(predict_account) = self.order_builder.predict_account() {
            OnchainClient::with_predict_account(
                self.chain_id,
                signer,
                &format!("{}", predict_account),
            )?
        } else {
            OnchainClient::new(self.chain_id, signer)
        };
        onchain_client.set_approvals(is_neg_risk, is_yield_bearing).await
    }

    /// Split USDT into UP/DOWN outcome tokens for a market.
    ///
    /// When a predict_account is configured, splits via Kernel so tokens land
    /// on the predict_account (which is the order maker).
    /// When using direct EOA, splits directly.
    pub async fn split_positions(
        &self,
        condition_id: &str,
        amount: f64,
        is_neg_risk: bool,
        is_yield_bearing: bool,
    ) -> Result<String> {
        let signer = self
            .order_builder
            .signer()
            .ok_or_else(|| Error::Other("No signer configured - cannot perform on-chain operations".into()))?;

        let onchain_client = if let Some(predict_account) = self.order_builder.predict_account() {
            OnchainClient::with_predict_account(
                self.chain_id,
                signer,
                &format!("{}", predict_account),
            )?
        } else {
            OnchainClient::new(self.chain_id, signer)
        };

        let options = SplitOptions {
            condition_id: condition_id.to_string(),
            amount,
            is_neg_risk,
            is_yield_bearing,
        };

        onchain_client.split_positions(options).await
    }

}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_private_key() {
        // Test with 0x prefix
        let key_with_prefix =
            "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef";
        let result = PredictClient::parse_private_key(key_with_prefix);
        assert!(result.is_ok());

        // Test without 0x prefix
        let key_without_prefix =
            "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef";
        let result = PredictClient::parse_private_key(key_without_prefix);
        assert!(result.is_ok());

        // Test invalid key
        let invalid_key = "invalid";
        let result = PredictClient::parse_private_key(invalid_key);
        assert!(result.is_err());
    }
}