polynode 0.13.9

Rust SDK for the PolyNode API — real-time Polymarket 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
//! Redemption watcher — monitors wallets for redeemable positions after oracle resolution.
//!
//! # Example
//!
//! ```rust,no_run
//! # async fn example() -> polynode::Result<()> {
//! let client = std::sync::Arc::new(polynode::PolyNodeClient::new("pn_live_...")?);
//! let mut watcher = polynode::RedemptionWatcher::new(client, Default::default());
//! watcher.start(&["0xabc..."]).await?;
//!
//! while let Some(alert) = watcher.next_alert().await {
//!     println!("{}: {} — {} (payout: ${})",
//!         alert.wallet, alert.market_title, alert.outcome, alert.estimated_payout_usd);
//! }
//! # Ok(())
//! # }
//! ```

use serde::Serialize;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;

use crate::client::PolyNodeClient;
use crate::error::{Error, Result};
use crate::types::ws_messages::WsMessage;
use crate::ws::StreamOptions;

/// Configuration for the redemption watcher.
#[derive(Debug, Clone)]
pub struct RedemptionWatcherConfig {
    /// Track position changes via WebSocket. Default: true.
    pub track_position_changes: bool,
    /// Periodic REST refresh interval in seconds. 0 = disabled. Default: 300.
    pub refresh_interval_secs: u64,
    /// Enable zlib compression on WebSocket. Default: true.
    pub compress: bool,
}

impl Default for RedemptionWatcherConfig {
    fn default() -> Self {
        Self {
            track_position_changes: true,
            refresh_interval_secs: 300,
            compress: true,
        }
    }
}

/// Alert fired when an oracle resolves and a watched wallet holds a position.
#[derive(Debug, Clone, Serialize)]
pub struct RedeemableAlert {
    pub wallet: String,
    pub condition_id: String,
    pub token_id: String,
    pub outcome: String,
    pub winning_outcome: String,
    pub is_winner: bool,
    pub size: f64,
    pub estimated_payout_usd: f64,
    pub market_title: String,
    pub market_slug: String,
    pub market_image: Option<String>,
    pub resolved_price: f64,
    pub payouts: Vec<u64>,
    pub block_number: u64,
    pub timestamp: i64,
}

/// A tracked position for a wallet.
#[derive(Debug, Clone)]
pub struct TrackedPosition {
    pub wallet: String,
    pub token_id: String,
    pub condition_id: String,
    pub outcome: String,
    pub size: f64,
    pub market_title: String,
    pub market_slug: String,
    pub market_image: Option<String>,
    pub outcomes: Vec<String>,
    pub token_ids: Vec<String>,
}

/// Monitors wallets for redeemable positions after oracle resolution.
pub struct RedemptionWatcher {
    client: Arc<PolyNodeClient>,
    config: RedemptionWatcherConfig,
    by_condition: HashMap<String, Vec<TrackedPosition>>,
    by_wallet: HashMap<String, HashSet<String>>,
    alert_tx: tokio::sync::mpsc::UnboundedSender<RedeemableAlert>,
    alert_rx: tokio::sync::mpsc::UnboundedReceiver<RedeemableAlert>,
    closed: bool,
}

impl RedemptionWatcher {
    pub fn new(client: Arc<PolyNodeClient>, config: RedemptionWatcherConfig) -> Self {
        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
        Self {
            client,
            config,
            by_condition: HashMap::new(),
            by_wallet: HashMap::new(),
            alert_tx: tx,
            alert_rx: rx,
            closed: false,
        }
    }

    /// Start watching. Fetches positions via REST, then spawns a background task
    /// that listens to oracle events and position changes.
    pub async fn start(&mut self, wallets: &[&str]) -> Result<()> {
        if self.closed {
            return Err(Error::Api {
                status: 0,
                message: "Watcher is closed".into(),
            });
        }

        self.fetch_and_load(wallets).await?;

        // Clone what we need for the background task
        let client = self.client.clone();
        let alert_tx = self.alert_tx.clone();
        let compress = self.config.compress;
        let wallet_list: Vec<String> = self.by_wallet.keys().cloned().collect();
        let by_condition = self.by_condition.clone();
        let by_wallet = self.by_wallet.clone();
        let refresh_secs = self.config.refresh_interval_secs;
        let track_pos = self.config.track_position_changes;

        tokio::spawn(async move {
            run_watcher_loop(
                client,
                alert_tx,
                compress,
                wallet_list,
                by_condition,
                by_wallet,
                refresh_secs,
                track_pos,
            )
            .await;
        });

        Ok(())
    }

    /// Add wallets at runtime.
    pub async fn add_wallets(&mut self, wallets: &[&str]) -> Result<()> {
        self.fetch_and_load(wallets).await
    }

    /// Remove wallets from tracking.
    pub fn remove_wallets(&mut self, wallets: &[&str]) {
        for wallet in wallets {
            let w = wallet.to_lowercase();
            if let Some(conditions) = self.by_wallet.remove(&w) {
                for cond_id in conditions {
                    if let Some(positions) = self.by_condition.get_mut(&cond_id) {
                        positions.retain(|p| p.wallet.to_lowercase() != w);
                        if positions.is_empty() {
                            self.by_condition.remove(&cond_id);
                        }
                    }
                }
            }
        }
    }

    /// Receive the next alert. Returns None when the watcher is closed.
    pub async fn next_alert(&mut self) -> Option<RedeemableAlert> {
        self.alert_rx.recv().await
    }

    /// All tracked wallet addresses.
    pub fn wallets(&self) -> Vec<String> {
        self.by_wallet.keys().cloned().collect()
    }

    /// Get tracked positions for a wallet.
    pub fn positions_for(&self, wallet: &str) -> Vec<TrackedPosition> {
        let w = wallet.to_lowercase();
        let Some(conditions) = self.by_wallet.get(&w) else {
            return vec![];
        };
        let mut result = Vec::new();
        for cond_id in conditions {
            if let Some(positions) = self.by_condition.get(cond_id) {
                for p in positions {
                    if p.wallet.to_lowercase() == w {
                        result.push(p.clone());
                    }
                }
            }
        }
        result
    }

    /// Total tracked positions across all wallets.
    pub fn size(&self) -> usize {
        self.by_condition.values().map(|v| v.len()).sum()
    }

    /// Close the watcher.
    pub fn close(&mut self) {
        self.closed = true;
        // Dropping alert_tx will cause alert_rx.recv() to return None
    }

    // ── Internal ──

    async fn fetch_and_load(&mut self, wallets: &[&str]) -> Result<()> {
        for wallet in wallets {
            match self.client.wallet_positions_data(wallet, None, None).await {
                Ok(data) => self.load_positions(wallet, &data.positions),
                Err(e) => tracing::warn!("Failed to fetch positions for {}: {}", wallet, e),
            }
        }
        Ok(())
    }

    fn load_positions(&mut self, wallet: &str, positions: &[serde_json::Value]) {
        let w = wallet.to_lowercase();
        let wallet_conditions = self.by_wallet.entry(w.clone()).or_default();

        for pos in positions {
            let condition_id = pos
                .get("conditionId")
                .or_else(|| pos.get("condition_id"))
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();
            let token_id = pos
                .get("asset")
                .or_else(|| pos.get("token_id"))
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string();
            let size = pos
                .get("size")
                .and_then(|v| {
                    v.as_f64()
                        .or_else(|| v.as_str().and_then(|s| s.parse().ok()))
                })
                .unwrap_or(0.0);

            if condition_id.is_empty() || token_id.is_empty() || size <= 0.0 {
                continue;
            }

            let tracked = TrackedPosition {
                wallet: w.clone(),
                token_id: token_id.clone(),
                condition_id: condition_id.clone(),
                outcome: pos
                    .get("outcome")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .into(),
                size,
                market_title: pos
                    .get("market_title")
                    .or_else(|| pos.get("title"))
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .into(),
                market_slug: pos
                    .get("market_slug")
                    .or_else(|| pos.get("slug"))
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .into(),
                market_image: pos
                    .get("market_image")
                    .or_else(|| pos.get("image"))
                    .and_then(|v| v.as_str())
                    .map(String::from),
                outcomes: pos
                    .get("outcomes")
                    .and_then(|v| v.as_array())
                    .map(|a| {
                        a.iter()
                            .filter_map(|v| v.as_str().map(String::from))
                            .collect()
                    })
                    .unwrap_or_default(),
                token_ids: pos
                    .get("token_ids")
                    .and_then(|v| v.as_array())
                    .map(|a| {
                        a.iter()
                            .filter_map(|v| v.as_str().map(String::from))
                            .collect()
                    })
                    .unwrap_or_default(),
            };

            let existing = self.by_condition.entry(condition_id.clone()).or_default();
            // Avoid duplicates
            if let Some(idx) = existing
                .iter()
                .position(|p| p.wallet == w && p.token_id == token_id)
            {
                existing[idx] = tracked;
            } else {
                existing.push(tracked);
            }
            wallet_conditions.insert(condition_id);
        }
    }
}

/// Background task that listens for oracle events and emits alerts.
async fn run_watcher_loop(
    client: Arc<PolyNodeClient>,
    alert_tx: tokio::sync::mpsc::UnboundedSender<RedeemableAlert>,
    compress: bool,
    _wallet_list: Vec<String>,
    mut by_condition: HashMap<String, Vec<TrackedPosition>>,
    mut by_wallet: HashMap<String, HashSet<String>>,
    _refresh_secs: u64,
    _track_pos: bool,
) {
    let stream = match client
        .stream(StreamOptions {
            compress,
            auto_reconnect: true,
            ..Default::default()
        })
        .await
    {
        Ok(s) => s,
        Err(e) => {
            tracing::error!("Failed to connect WebSocket for redemption watcher: {}", e);
            return;
        }
    };

    // Subscribe to oracle events
    let sub = crate::ws::Subscription::new(crate::ws::SubscriptionType::Oracle);
    if let Err(e) = stream.subscribe(sub).await {
        tracing::error!("Failed to subscribe to oracle events: {}", e);
        return;
    }

    let mut stream = stream;
    while let Some(msg) = stream.next().await {
        let msg = match msg {
            Ok(m) => m,
            Err(e) => {
                tracing::warn!("WebSocket error in redemption watcher: {}", e);
                continue;
            }
        };

        if let WsMessage::Event(crate::types::events::PolyNodeEvent::Oracle(event)) = msg {
            if event.oracle_type != crate::types::common::OracleEventType::ConditionResolution {
                continue;
            }
            let Some(ref condition_id) = event.condition_id else {
                continue;
            };

            let positions = match by_condition.get(condition_id) {
                Some(p) if !p.is_empty() => p.clone(),
                _ => continue,
            };

            for pos in &positions {
                let token_index = event
                    .token_ids
                    .as_ref()
                    .and_then(|ids| ids.iter().position(|id| id == &pos.token_id));
                let is_winner = token_index
                    .and_then(|i| event.payouts.as_ref().and_then(|p| p.get(i)))
                    .map(|&p| p > 0)
                    .unwrap_or(false);

                let alert = RedeemableAlert {
                    wallet: pos.wallet.clone(),
                    condition_id: condition_id.clone(),
                    token_id: pos.token_id.clone(),
                    outcome: pos.outcome.clone(),
                    winning_outcome: event.resolved_outcome.clone().unwrap_or_default(),
                    is_winner,
                    size: pos.size,
                    estimated_payout_usd: if is_winner { pos.size } else { 0.0 },
                    market_title: pos.market_title.clone(),
                    market_slug: pos.market_slug.clone(),
                    market_image: pos.market_image.clone(),
                    resolved_price: event.resolved_price.unwrap_or(0.0),
                    payouts: event.payouts.clone().unwrap_or_default(),
                    block_number: event.block_number,
                    timestamp: event.timestamp,
                };

                if alert_tx.send(alert).is_err() {
                    return; // Receiver dropped, watcher closed
                }
            }

            // Evict resolved condition
            by_condition.remove(condition_id);
            for wallet_conds in by_wallet.values_mut() {
                wallet_conds.remove(condition_id);
            }
        }
    }
}