polymarket-api 0.1.1

Rust client library for Polymarket REST and WebSocket APIs
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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
use {
    crate::{cache::FileCache, error::Result},
    serde::{Deserialize, Deserializer, Serialize},
};

/// Macro for conditional info logging based on tracing feature
#[cfg(feature = "tracing")]
macro_rules! log_info {
    ($($arg:tt)*) => { tracing::info!($($arg)*) };
}

#[cfg(not(feature = "tracing"))]
macro_rules! log_info {
    ($($arg:tt)*) => {};
}

/// Macro for conditional debug logging based on tracing feature
#[cfg(feature = "tracing")]
macro_rules! log_debug {
    ($($arg:tt)*) => { tracing::debug!($($arg)*) };
}

#[cfg(not(feature = "tracing"))]
macro_rules! log_debug {
    ($($arg:tt)*) => {};
}

/// Macro for conditional warn logging based on tracing feature
#[cfg(feature = "tracing")]
macro_rules! log_warn {
    ($($arg:tt)*) => { tracing::warn!($($arg)*) };
}

#[cfg(not(feature = "tracing"))]
macro_rules! log_warn {
    ($($arg:tt)*) => {};
}

/// Macro for conditional error logging based on tracing feature
#[cfg(feature = "tracing")]
macro_rules! log_error {
    ($($arg:tt)*) => { tracing::error!($($arg)*) };
}

#[cfg(not(feature = "tracing"))]
macro_rules! log_error {
    ($($arg:tt)*) => {};
}

const GAMMA_API_BASE: &str = "https://gamma-api.polymarket.com";

// Helper function to deserialize clobTokenIds which can be either a JSON string or an array
fn deserialize_clob_token_ids<'de, D>(
    deserializer: D,
) -> std::result::Result<Option<Vec<String>>, D::Error>
where
    D: Deserializer<'de>,
{
    use serde::de::Error;

    // First try to deserialize as Option
    let opt: Option<serde_json::Value> = Option::deserialize(deserializer)?;

    let value = match opt {
        Some(v) => v,
        None => return Ok(None),
    };

    if value.is_null() {
        return Ok(None);
    }

    match value {
        serde_json::Value::String(s) => {
            // It's a JSON string, parse it
            serde_json::from_str(&s).map(Some).map_err(Error::custom)
        },
        serde_json::Value::Array(arr) => {
            // It's already an array, convert it
            Ok(Some(
                arr.into_iter()
                    .map(|v| {
                        if let serde_json::Value::String(s) = v {
                            s
                        } else {
                            v.to_string()
                        }
                    })
                    .collect(),
            ))
        },
        _ => Ok(None),
    }
}

// Helper function to deserialize outcomes/outcomePrices which can be either a JSON string or an array
fn deserialize_string_array<'de, D>(deserializer: D) -> std::result::Result<Vec<String>, D::Error>
where
    D: Deserializer<'de>,
{
    use serde::de::Error;

    let value: serde_json::Value = serde_json::Value::deserialize(deserializer)?;

    match value {
        serde_json::Value::String(s) => {
            // It's a JSON string, parse it
            serde_json::from_str(&s).map_err(Error::custom)
        },
        serde_json::Value::Array(arr) => {
            // It's already an array, convert it
            Ok(arr
                .into_iter()
                .map(|v| {
                    if let serde_json::Value::String(s) = v {
                        s
                    } else {
                        v.to_string()
                    }
                })
                .collect())
        },
        _ => Ok(vec![]),
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Event {
    pub id: String,
    pub slug: String,
    pub title: String,
    pub active: bool,
    pub closed: bool,
    #[serde(default)]
    pub tags: Vec<Tag>,
    pub markets: Vec<Market>,
    #[serde(rename = "endDate", default)]
    pub end_date: Option<String>, // ISO 8601 date string
    #[serde(default)]
    pub image: Option<String>, // URL to event image/thumbnail
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Tag {
    pub id: String,
    pub label: String,
    pub slug: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Market {
    #[serde(default)]
    pub id: Option<String>,
    pub question: String,
    /// Short display name for grouped markets (e.g., "400-419" for tweet count ranges)
    #[serde(rename = "groupItemTitle", default)]
    pub group_item_title: Option<String>,
    #[serde(
        rename = "clobTokenIds",
        deserialize_with = "deserialize_clob_token_ids",
        default
    )]
    pub clob_token_ids: Option<Vec<String>>,
    #[serde(deserialize_with = "deserialize_string_array", default)]
    pub outcomes: Vec<String>,
    #[serde(
        rename = "outcomePrices",
        deserialize_with = "deserialize_string_array",
        default
    )]
    pub outcome_prices: Vec<String>,
    #[serde(rename = "volume24hr", default)]
    pub volume_24hr: Option<f64>,
    #[serde(rename = "volumeTotal", default)]
    pub volume_total: Option<f64>,
    /// Whether the market is active (accepting new trades)
    #[serde(default)]
    pub active: bool,
    /// Whether the market has been closed/resolved
    #[serde(default)]
    pub closed: bool,
    /// Market slug for URL construction
    #[serde(default)]
    pub slug: Option<String>,
    /// Whether the market is accepting orders
    #[serde(rename = "acceptingOrders", default)]
    pub accepting_orders: bool,
    /// UMA oracle resolution statuses (JSON string like "[\"proposed\", \"disputed\"]")
    #[serde(rename = "umaResolutionStatuses", default)]
    pub uma_resolution_statuses: Option<String>,
    /// Events this market belongs to (always 0 or 1 element)
    #[serde(default)]
    pub events: Vec<MarketEventRef>,
}

impl Market {
    /// Get the event this market belongs to (markets have at most one event)
    pub fn event(&self) -> Option<&MarketEventRef> {
        self.events.first()
    }

    /// Check if market is in resolution/review process
    pub fn is_in_review(&self) -> bool {
        if let Some(ref statuses) = self.uma_resolution_statuses {
            statuses.contains("proposed") || statuses.contains("disputed")
        } else {
            false
        }
    }

    /// Get human-readable status string
    pub fn status(&self) -> &'static str {
        if self.closed {
            "closed"
        } else if self.is_in_review() {
            "in-review"
        } else if self.active {
            "open"
        } else {
            "paused"
        }
    }
}

/// Lightweight event reference embedded in market responses
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MarketEventRef {
    pub id: String,
    pub slug: String,
    pub title: String,
    #[serde(rename = "endDate")]
    pub end_date: Option<String>,
    #[serde(default)]
    pub active: bool,
    #[serde(default)]
    pub closed: bool,
}

impl MarketEventRef {
    /// Get human-readable status string
    pub fn status(&self) -> &'static str {
        if self.closed {
            "closed"
        } else if self.active {
            "active"
        } else {
            "inactive"
        }
    }
}

pub struct GammaClient {
    client: reqwest::Client,
    cache: Option<FileCache>,
}

impl GammaClient {
    pub fn new() -> Self {
        Self {
            client: reqwest::Client::new(),
            cache: None,
        }
    }

    /// Create a new GammaClient with file-based caching
    pub fn with_cache<P: AsRef<std::path::Path>>(cache_dir: P) -> Result<Self> {
        let cache = FileCache::new(cache_dir)?;
        Ok(Self {
            client: reqwest::Client::new(),
            cache: Some(cache),
        })
    }

    /// Set cache TTL (time to live) in seconds
    pub fn set_cache_ttl(&mut self, ttl_seconds: u64) -> Result<()> {
        if let Some(ref mut cache) = self.cache {
            *cache = cache.clone().with_default_ttl(ttl_seconds);
        }
        Ok(())
    }

    /// Set cache for this client
    pub fn set_cache(&mut self, cache: FileCache) {
        self.cache = Some(cache);
    }

    pub async fn get_active_events(&self, limit: Option<usize>) -> Result<Vec<Event>> {
        let limit = limit.unwrap_or(100);
        let url = format!(
            "{}/events?active=true&closed=false&limit={}",
            GAMMA_API_BASE, limit
        );
        let events: Vec<Event> = self.client.get(&url).send().await?.json().await?;
        Ok(events)
    }

    /// Get trending events ordered by trading volume
    ///
    /// # Arguments
    /// * `order_by` - Field to order by (e.g., "volume24hr", "volume7d", "volume30d")
    /// * `ascending` - If true, sort ascending; if false, sort descending
    /// * `limit` - Maximum number of events to return
    pub async fn get_trending_events(
        &self,
        order_by: Option<&str>,
        ascending: Option<bool>,
        limit: Option<usize>,
    ) -> Result<Vec<Event>> {
        let limit = limit.unwrap_or(50);
        let order_by = order_by.unwrap_or("volume24hr");
        let ascending = ascending.unwrap_or(false);

        let url = format!(
            "{}/events?active=true&closed=false&order={}&ascending={}&limit={}",
            GAMMA_API_BASE, order_by, ascending, limit
        );

        log_info!("GET {}", url);

        let response = self.client.get(&url).send().await?;
        let _status = response.status();

        log_info!("GET {} -> status: {}", url, _status);

        let events: Vec<Event> = response.json().await?;
        Ok(events)
    }

    pub async fn get_market_by_slug(&self, slug: &str) -> Result<Vec<Market>> {
        let url = format!("{}/markets?slug={}", GAMMA_API_BASE, slug);
        let response: serde_json::Value = self.client.get(&url).send().await?.json().await?;

        // The API might return a single market or an array
        let markets = if response.is_array() {
            serde_json::from_value(response)?
        } else {
            vec![serde_json::from_value(response)?]
        };

        Ok(markets)
    }

    pub async fn get_all_active_asset_ids(&self) -> Result<Vec<String>> {
        let events = self.get_active_events(None).await?;
        let mut asset_ids = Vec::new();

        for event in events {
            for market in event.markets {
                if let Some(token_ids) = market.clob_token_ids {
                    asset_ids.extend(token_ids);
                }
            }
        }

        Ok(asset_ids)
    }

    /// Get event by ID
    pub async fn get_event_by_id(&self, event_id: &str) -> Result<Option<Event>> {
        let url = format!("{}/events/{}", GAMMA_API_BASE, event_id);
        let response = self.client.get(&url).send().await?;

        if response.status() == 404 {
            return Ok(None);
        }

        let event: Event = response.json().await?;
        Ok(Some(event))
    }

    /// Get event by slug
    pub async fn get_event_by_slug(&self, slug: &str) -> Result<Option<Event>> {
        let url = format!("{}/events?slug={}", GAMMA_API_BASE, slug);
        let events: Vec<Event> = self.client.get(&url).send().await?.json().await?;
        Ok(events.into_iter().next())
    }

    /// Get market by ID
    pub async fn get_market_by_id(&self, market_id: &str) -> Result<Option<Market>> {
        let url = format!("{}/markets/{}", GAMMA_API_BASE, market_id);
        let response = self.client.get(&url).send().await?;

        if response.status() == 404 {
            return Ok(None);
        }

        let market: Market = response.json().await?;
        Ok(Some(market))
    }

    /// Get all markets (with optional filters)
    pub async fn get_markets(
        &self,
        active: Option<bool>,
        closed: Option<bool>,
        limit: Option<usize>,
    ) -> Result<Vec<Market>> {
        let url = format!("{}/markets", GAMMA_API_BASE);
        let mut params = Vec::new();

        if let Some(active) = active {
            params.push(("active", active.to_string()));
        }
        if let Some(closed) = closed {
            params.push(("closed", closed.to_string()));
        }
        if let Some(limit) = limit {
            params.push(("limit", limit.to_string()));
        }

        let markets: Vec<Market> = self
            .client
            .get(&url)
            .query(&params)
            .send()
            .await?
            .json()
            .await?;
        Ok(markets)
    }

    /// Get categories/tags
    pub async fn get_categories(&self) -> Result<Vec<Tag>> {
        let url = format!("{}/categories", GAMMA_API_BASE);
        let categories: Vec<Tag> = self.client.get(&url).send().await?.json().await?;
        Ok(categories)
    }

    /// Get events by category/tag
    pub async fn get_events_by_category(
        &self,
        category_slug: &str,
        limit: Option<usize>,
    ) -> Result<Vec<Event>> {
        let limit = limit.unwrap_or(100);
        let url = format!(
            "{}/events?category={}&limit={}",
            GAMMA_API_BASE, category_slug, limit
        );
        let events: Vec<Event> = self.client.get(&url).send().await?.json().await?;
        Ok(events)
    }

    /// Search events by query string using the public-search endpoint
    pub async fn search_events(&self, query: &str, limit: Option<usize>) -> Result<Vec<Event>> {
        let limit_per_type = limit.unwrap_or(50);
        let url = format!(
            "{}/public-search?q={}&optimized=true&limit_per_type={}&type=events&search_tags=true&search_profiles=true&cache=true",
            GAMMA_API_BASE,
            urlencoding::encode(query),
            limit_per_type
        );

        // Log the API call
        log_info!("GET {}", url);

        let response = self.client.get(&url).send().await.inspect_err(|_e| {
            log_error!("Failed to send search request: {}", _e);
        })?;

        let status = response.status();
        log_info!("GET {} -> status: {}", url, status);

        let response_text = response.text().await.inspect_err(|_e| {
            log_error!("Failed to read search response body: {}", _e);
        })?;

        // Only log response body on error or in debug mode
        if !status.is_success() {
            log_debug!(
                "Search API response body (first 500 chars): {}",
                if response_text.len() > 500 {
                    &response_text[..500]
                } else {
                    &response_text
                }
            );
        }

        if !status.is_success() {
            log_warn!(
                "Search API error: status={}, body={}",
                status,
                response_text
            );
            return Err(crate::error::PolymarketError::InvalidData(format!(
                "Search API returned status {}: {}",
                status, response_text
            )));
        }

        #[derive(Deserialize)]
        struct SearchResponse {
            events: Vec<Event>,
            #[allow(dead_code)]
            profiles: Option<serde_json::Value>,
            #[allow(dead_code)]
            tags: Option<serde_json::Value>,
            #[allow(dead_code)]
            has_more: Option<bool>,
        }

        let search_response: SearchResponse =
            serde_json::from_str(&response_text).map_err(|e| {
                log_error!(
                    "Failed to parse search response: {}, body (first 1000 chars): {}",
                    e,
                    if response_text.len() > 1000 {
                        &response_text[..1000]
                    } else {
                        &response_text
                    }
                );
                crate::error::PolymarketError::Serialization(e)
            })?;

        log_info!("Search returned {} events", search_response.events.len());

        // The search endpoint doesn't return volume data, so we need to fetch
        // full event details for each result to get market volumes
        let mut full_events = Vec::with_capacity(search_response.events.len());
        for event in &search_response.events {
            match self.get_event_by_slug(&event.slug).await {
                Ok(Some(full_event)) => full_events.push(full_event),
                Ok(None) => {
                    // Event not found, use the search result as-is
                    log_debug!("Event not found by slug: {}", event.slug);
                    full_events.push(event.clone());
                },
                Err(_e) => {
                    // Failed to fetch, use the search result as-is
                    log_debug!("Failed to fetch event {}: {}", event.slug, _e);
                    full_events.push(event.clone());
                },
            }
        }

        log_info!(
            "Enriched {} search results with full event data",
            full_events.len()
        );

        Ok(full_events)
    }

    pub async fn get_market_info_by_asset_id(&self, asset_id: &str) -> Result<Option<MarketInfo>> {
        // Check cache first
        if let Some(ref cache) = self.cache {
            let cache_key = format!("market_info_{}", asset_id);
            if let Some(cached_info) = cache.get::<MarketInfo>(&cache_key)? {
                return Ok(Some(cached_info));
            }
        }

        let events = self.get_active_events(Some(1000)).await?;

        for event in events {
            for market in event.markets {
                if let Some(ref token_ids) = market.clob_token_ids
                    && token_ids.contains(&asset_id.to_string())
                {
                    let outcomes = market.outcomes.clone();
                    let prices = market.outcome_prices.clone();

                    let market_info = MarketInfo {
                        event_title: event.title,
                        event_slug: event.slug,
                        market_question: market.question,
                        market_id: market.id.clone().unwrap_or_default(),
                        asset_id: asset_id.to_string(),
                        outcomes,
                        prices,
                    };

                    // Cache the result
                    if let Some(ref cache) = self.cache {
                        let cache_key = format!("market_info_{}", asset_id);
                        let _ = cache.set(&cache_key, &market_info);
                    }

                    return Ok(Some(market_info));
                }
            }
        }

        Ok(None)
    }

    /// Check API health status
    pub async fn get_status(&self) -> Result<StatusResponse> {
        let url = format!("{}/status", GAMMA_API_BASE);
        let status: StatusResponse = self.client.get(&url).send().await?.json().await?;
        Ok(status)
    }

    /// Get tag by ID
    pub async fn get_tag_by_id(&self, tag_id: &str) -> Result<Option<Tag>> {
        let url = format!("{}/tags/{}", GAMMA_API_BASE, tag_id);
        let response = self.client.get(&url).send().await?;

        if response.status() == 404 {
            return Ok(None);
        }

        let tag: Tag = response.json().await?;
        Ok(Some(tag))
    }

    /// Get tag by slug
    pub async fn get_tag_by_slug(&self, slug: &str) -> Result<Option<Tag>> {
        let url = format!("{}/tags/slug/{}", GAMMA_API_BASE, slug);
        let response = self.client.get(&url).send().await?;

        if response.status() == 404 {
            return Ok(None);
        }

        let tag: Tag = response.json().await?;
        Ok(Some(tag))
    }

    /// Get related tags for a tag ID
    pub async fn get_related_tags(&self, tag_id: &str) -> Result<Vec<Tag>> {
        let url = format!("{}/tags/{}/related-tags", GAMMA_API_BASE, tag_id);
        let tags: Vec<Tag> = self.client.get(&url).send().await?.json().await?;
        Ok(tags)
    }

    /// Get all series
    pub async fn get_series(&self, limit: Option<usize>) -> Result<Vec<Series>> {
        let limit = limit.unwrap_or(100);
        let url = format!("{}/series?limit={}", GAMMA_API_BASE, limit);
        let series: Vec<Series> = self.client.get(&url).send().await?.json().await?;
        Ok(series)
    }

    /// Get series by ID
    pub async fn get_series_by_id(&self, series_id: &str) -> Result<Option<Series>> {
        let url = format!("{}/series/{}", GAMMA_API_BASE, series_id);
        let response = self.client.get(&url).send().await?;

        if response.status() == 404 {
            return Ok(None);
        }

        let series: Series = response.json().await?;
        Ok(Some(series))
    }

    /// Get public profile by wallet address
    pub async fn get_public_profile(&self, address: &str) -> Result<Option<PublicProfile>> {
        let url = format!("{}/public-profile", GAMMA_API_BASE);
        let params = [("address", address)];
        let response = self.client.get(&url).query(&params).send().await?;

        if response.status() == 404 {
            return Ok(None);
        }

        let profile: PublicProfile = response.json().await?;
        Ok(Some(profile))
    }

    /// Get tags for a specific event
    pub async fn get_event_tags(&self, event_id: &str) -> Result<Vec<Tag>> {
        let url = format!("{}/events/{}/tags", GAMMA_API_BASE, event_id);
        let tags: Vec<Tag> = self.client.get(&url).send().await?.json().await?;
        Ok(tags)
    }

    /// Get tags for a specific market
    pub async fn get_market_tags(&self, market_id: &str) -> Result<Vec<Tag>> {
        let url = format!("{}/markets/{}/tags", GAMMA_API_BASE, market_id);
        let tags: Vec<Tag> = self.client.get(&url).send().await?.json().await?;
        Ok(tags)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MarketInfo {
    pub event_title: String,
    pub event_slug: String,
    pub market_question: String,
    pub market_id: String,
    pub asset_id: String,
    pub outcomes: Vec<String>,
    pub prices: Vec<String>,
}

/// API status response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StatusResponse {
    pub status: String,
}

/// Series information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Series {
    pub id: String,
    #[serde(default)]
    pub title: Option<String>,
    #[serde(default)]
    pub slug: Option<String>,
    #[serde(default)]
    pub description: Option<String>,
}

/// Public profile information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PublicProfile {
    #[serde(default)]
    pub address: Option<String>,
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub pseudonym: Option<String>,
    #[serde(default)]
    pub bio: Option<String>,
    #[serde(rename = "profileImage", default)]
    pub profile_image: Option<String>,
    #[serde(rename = "profileImageOptimized", default)]
    pub profile_image_optimized: Option<String>,
}

impl Default for GammaClient {
    fn default() -> Self {
        Self::new()
    }
}