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
/// API types for predict.fun REST API responses
///
/// These types represent the data structures returned by the predict.fun API.

use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};

/// Represents a Predict market
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PredictMarket {
    /// Market ID
    pub id: u64,
    /// Market title
    pub title: String,
    /// Market question
    pub question: String,
    /// Condition ID (for on-chain settlement)
    pub condition_id: String,
    /// Market status (REGISTERED, OPEN, RESOLVED)
    pub status: String,
    /// Category slug this market belongs to
    pub category_slug: String,
    /// Whether this is a neg risk market
    pub is_neg_risk: bool,
    /// Whether yield bearing is enabled
    pub is_yield_bearing: bool,
    /// Fee rate in basis points (fetched from GET /markets endpoint)
    #[serde(default)]
    pub fee_rate_bps: u64,
    /// Market outcomes
    pub outcomes: Vec<PredictOutcome>,
    /// Created at timestamp
    pub created_at: String,

    // --- Strike price fields (populated from GraphQL) ---

    /// Strike price (Pyth) - populated from GraphQL marketData.startPrice
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub start_price: Option<Decimal>,
    /// Price feed ID (e.g., "1" for BTC/USD) - populated from GraphQL
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub price_feed_id: Option<String>,
}

impl PredictMarket {
    /// Get the strike price if available
    pub fn strike_price(&self) -> Option<Decimal> {
        self.start_price
    }

    /// Set the strike price from GraphQL market data
    pub fn set_strike_price(&mut self, start_price: Decimal, price_feed_id: String) {
        self.start_price = Some(start_price);
        self.price_feed_id = Some(price_feed_id);
    }
}

/// Represents a market outcome
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PredictOutcome {
    /// Outcome name (e.g., "Up", "Down")
    pub name: String,
    /// Index set for this outcome
    pub index_set: u64,
    /// On-chain token ID
    pub on_chain_id: String,
    /// Resolution status (null if not resolved)
    pub status: Option<String>,
}

/// Represents an order book for a Predict market
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PredictOrderBook {
    /// Market ID
    pub market_id: String,
    /// Best bid price
    pub best_bid: Option<Decimal>,
    /// Best ask price
    pub best_ask: Option<Decimal>,
    /// Bid orders (price, size)
    pub bids: Vec<(Decimal, Decimal)>,
    /// Ask orders (price, size)
    pub asks: Vec<(Decimal, Decimal)>,
}

// ============================================================================
// Order types matching Predict API v1
// ============================================================================

/// Order status
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum OrderStatus {
    Open,
    Filled,
    Expired,
    Cancelled,
    Invalidated,
}

/// The signed order data embedded in an order response
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PredictOrderData {
    pub hash: String,
    #[serde(deserialize_with = "string_or_number")]
    pub salt: String,
    pub maker: String,
    pub signer: String,
    pub taker: String,
    pub token_id: String,
    #[serde(deserialize_with = "string_or_number")]
    pub maker_amount: String,
    #[serde(deserialize_with = "string_or_number")]
    pub taker_amount: String,
    #[serde(deserialize_with = "string_or_number")]
    pub expiration: String,
    #[serde(deserialize_with = "string_or_number")]
    pub nonce: String,
    #[serde(deserialize_with = "string_or_number")]
    pub fee_rate_bps: String,
    /// 0 = BUY, 1 = SELL
    pub side: u8,
    /// 0 = EOA
    pub signature_type: u8,
    pub signature: String,
}

/// Deserialize a field that can be either a string or a number, always returning a String
fn string_or_number<'de, D>(deserializer: D) -> std::result::Result<String, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::de;

    struct StringOrNumberVisitor;

    impl<'de> de::Visitor<'de> for StringOrNumberVisitor {
        type Value = String;

        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
            formatter.write_str("a string or number")
        }

        fn visit_str<E: de::Error>(self, v: &str) -> std::result::Result<String, E> {
            Ok(v.to_string())
        }

        fn visit_string<E: de::Error>(self, v: String) -> std::result::Result<String, E> {
            Ok(v)
        }

        fn visit_u64<E: de::Error>(self, v: u64) -> std::result::Result<String, E> {
            Ok(v.to_string())
        }

        fn visit_i64<E: de::Error>(self, v: i64) -> std::result::Result<String, E> {
            Ok(v.to_string())
        }

        fn visit_f64<E: de::Error>(self, v: f64) -> std::result::Result<String, E> {
            Ok(v.to_string())
        }
    }

    deserializer.deserialize_any(StringOrNumberVisitor)
}

/// Represents an order on Predict (from GET /v1/orders)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PredictOrder {
    /// Order ID (bigint as string)
    pub id: String,
    /// Market ID (can be number or string depending on endpoint)
    #[serde(deserialize_with = "deserialize_market_id")]
    pub market_id: u64,
    /// Currency (e.g., "USDT")
    #[serde(default)]
    pub currency: Option<String>,
    /// Total order amount (wei string)
    pub amount: String,
    /// Amount filled so far (wei string)
    pub amount_filled: String,
    /// Whether this is a neg risk market
    #[serde(default)]
    pub is_neg_risk: bool,
    /// Whether yield bearing is enabled
    #[serde(default)]
    pub is_yield_bearing: bool,
    /// Order strategy: "LIMIT" or "MARKET"
    #[serde(default)]
    pub strategy: String,
    /// Order status
    pub status: OrderStatus,
    /// The signed order payload
    pub order: PredictOrderData,
}

/// Deserialize market_id from either a number or a string
fn deserialize_market_id<'de, D>(deserializer: D) -> std::result::Result<u64, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::de;

    struct MarketIdVisitor;

    impl<'de> de::Visitor<'de> for MarketIdVisitor {
        type Value = u64;

        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
            formatter.write_str("a number or string containing a number")
        }

        fn visit_u64<E: de::Error>(self, v: u64) -> std::result::Result<u64, E> {
            Ok(v)
        }

        fn visit_i64<E: de::Error>(self, v: i64) -> std::result::Result<u64, E> {
            Ok(v as u64)
        }

        fn visit_str<E: de::Error>(self, v: &str) -> std::result::Result<u64, E> {
            v.parse::<u64>().map_err(de::Error::custom)
        }
    }

    deserializer.deserialize_any(MarketIdVisitor)
}

// ============================================================================
// API response wrappers
// ============================================================================

/// Response from GET /v1/orders
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GetOrdersResponse {
    pub success: bool,
    pub cursor: Option<String>,
    pub data: Vec<PredictOrder>,
}

/// Response from POST /v1/orders (place order)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PlaceOrderResponse {
    pub success: bool,
    pub data: Option<PlaceOrderData>,
}

/// Inner data from place order response
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PlaceOrderData {
    pub code: Option<String>,
    pub order_id: String,
    pub order_hash: String,
}

/// Request body for POST /v1/orders
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateOrderRequest {
    pub data: CreateOrderData,
}

/// Inner data for create order request
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateOrderData {
    pub order: serde_json::Value,
    pub price_per_share: String,
    pub strategy: String,
}

/// Response from POST /v1/orders/remove (cancel orders)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RemoveOrdersResponse {
    pub success: bool,
    pub removed: Vec<String>,
    pub noop: Vec<String>,
}

/// Request body for POST /v1/orders/remove
#[derive(Debug, Clone, Serialize)]
pub struct RemoveOrdersRequest {
    pub data: RemoveOrdersData,
}

/// Inner data for remove orders request
#[derive(Debug, Clone, Serialize)]
pub struct RemoveOrdersData {
    pub ids: Vec<String>,
}

// ============================================================================
// Auth types
// ============================================================================

/// Response from GET /v1/auth/message
#[derive(Debug, Clone, Deserialize)]
pub struct AuthMessageResponse {
    pub success: bool,
    pub data: AuthMessageData,
}

/// Inner data from auth message response
#[derive(Debug, Clone, Deserialize)]
pub struct AuthMessageData {
    pub message: String,
}

/// Request body for POST /v1/auth
#[derive(Debug, Clone, Serialize)]
pub struct AuthRequest {
    pub signer: String,
    pub signature: String,
    pub message: String,
}

/// Response from POST /v1/auth
#[derive(Debug, Clone, Deserialize)]
pub struct AuthResponse {
    pub success: bool,
    pub data: AuthResponseData,
}

/// Inner data from auth response
#[derive(Debug, Clone, Deserialize)]
pub struct AuthResponseData {
    pub token: String,
}

// ============================================================================
// Position types
// ============================================================================

/// Response from GET /v1/positions
#[derive(Debug, Clone, Deserialize)]
pub struct GetPositionsResponse {
    pub success: bool,
    pub cursor: Option<String>,
    pub data: Vec<PredictPosition>,
}

/// A position on Predict
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PredictPosition {
    pub id: String,
    pub market: PredictPositionMarket,
    pub outcome: PredictPositionOutcome,
    /// Token amount (wei string)
    pub amount: String,
    /// USD value
    #[serde(default)]
    pub value_usd: Option<String>,
}

/// Market info embedded in a position
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PredictPositionMarket {
    pub id: u64,
    pub title: String,
    #[serde(default)]
    pub condition_id: Option<String>,
}

/// Outcome info embedded in a position
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PredictPositionOutcome {
    pub name: String,
    pub index_set: u64,
    pub on_chain_id: String,
    pub status: Option<String>,
}

// ============================================================================
// Wallet event types (from predictWalletEvents WebSocket topic)
// ============================================================================

/// Details from a wallet event's `details` object (present on transaction events)
#[derive(Debug, Clone, Default)]
pub struct WalletEventDetails {
    /// Fill price (e.g., "0.290")
    pub price: Option<String>,
    /// Order quantity (e.g., "5.000")
    pub quantity: Option<String>,
    /// Quantity filled (e.g., "5.000")
    pub quantity_filled: Option<String>,
    /// Outcome side (e.g., "YES" or "NO")
    pub outcome: Option<String>,
    /// Quote type (e.g., "ASK" or "BID")
    pub quote_type: Option<String>,
}

/// Wallet events received via predictWalletEvents/{jwt} WebSocket topic
#[derive(Debug, Clone)]
pub enum PredictWalletEvent {
    /// Order successfully placed in orderbook
    OrderAccepted {
        order_hash: String,
        order_id: String,
    },
    /// Order rejected
    OrderNotAccepted {
        order_hash: String,
        order_id: String,
        reason: Option<String>,
    },
    /// Order expired
    OrderExpired {
        order_hash: String,
        order_id: String,
    },
    /// Order cancelled by user
    OrderCancelled {
        order_hash: String,
        order_id: String,
    },
    /// Order matched, transaction sent to blockchain
    OrderTransactionSubmitted {
        order_hash: String,
        order_id: String,
        tx_hash: Option<String>,
        details: WalletEventDetails,
    },
    /// On-chain transaction succeeded (order filled)
    OrderTransactionSuccess {
        order_hash: String,
        order_id: String,
        tx_hash: Option<String>,
        details: WalletEventDetails,
    },
    /// On-chain transaction failed
    OrderTransactionFailed {
        order_hash: String,
        order_id: String,
        tx_hash: Option<String>,
        details: WalletEventDetails,
    },
    /// Unknown wallet event type
    Unknown {
        event_type: String,
        data: serde_json::Value,
    },
}

// ============================================================================
// Category types
// ============================================================================

/// API response wrapper for category endpoint
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CategoryResponse {
    pub success: bool,
    pub data: PredictCategory,
}

/// Predict category (collection of related markets)
///
/// Categories group markets by asset, time, and duration.
/// The slug follows the pattern: `{asset}-usd-up-down-{yyyy}-{mm}-{dd}-{hh}-{mm}-{duration}`
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PredictCategory {
    /// Category ID
    pub id: u64,
    /// Category slug (used for lookup)
    pub slug: String,
    /// Category title
    pub title: String,
    /// Markets within this category
    pub markets: Vec<PredictMarket>,
}