koios_sdk/api/
pool.rs

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
use crate::{
    error::Result,
    models::{
        pool::{PoolDelegator, PoolDelegatorsHistory, PoolInfo, PoolList, PoolSnapshot},
        requests::PoolIdsRequest,
        PoolHistoryInfo, PoolIdsOptionalRequest, PoolMetadataInfo, PoolRegistration, PoolRelay,
        PoolUpdate, PoolVotes,
    },
    types::{EpochNo, PoolBech32},
    Client,
};
use urlencoding::encode;

impl Client {
    /// Get list of brief info for all pools
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use koios_sdk::Client;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = Client::new()?;
    ///     let pools = client.get_pool_list().await?;
    ///     println!("Pool list: {:?}", pools);
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_pool_list(&self) -> Result<Vec<PoolList>> {
        self.get("/pool_list").await
    }

    /// Get current pool statuses and details for a specified list of pool ids
    ///
    /// # Arguments
    ///
    /// * `pool_ids` - List of pool IDs to query
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use koios_sdk::Client;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = Client::new()?;
    ///     let pool_ids = vec![
    ///         "pool1pu5jlj4q9w9jlxeu370a3c9myx47md5j5m2str0naunn2q3lkdy".to_string()
    ///     ];
    ///     let info = client.get_pool_info(&pool_ids).await?;
    ///     println!("Pool info: {:?}", info);
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_pool_info(&self, pool_ids: &[String]) -> Result<Vec<PoolInfo>> {
        let request = PoolIdsRequest::new(pool_ids.to_vec());
        self.post("/pool_info", &request).await
    }

    /// Get Mark, Set and Go stake snapshots for the selected pool
    ///
    /// # Arguments
    ///
    /// * `pool_bech32` - Pool ID in bech32 format
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use koios_sdk::Client;
    /// use koios_sdk::types::PoolBech32;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = Client::new()?;
    ///     let pool_id = PoolBech32::new(
    ///         "pool1pu5jlj4q9w9jlxeu370a3c9myx47md5j5m2str0naunn2q3lkdy"
    ///     );
    ///     let snapshot = client.get_pool_stake_snapshot(&pool_id).await?;
    ///     println!("Pool stake snapshot: {:?}", snapshot);
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_pool_stake_snapshot(
        &self,
        pool_bech32: &PoolBech32,
    ) -> Result<Vec<PoolSnapshot>> {
        self.get(&format!(
            "/pool_stake_snapshot?_pool_bech32={}",
            encode(pool_bech32.value())
        ))
        .await
    }

    /// Get information about live delegators for a given pool
    ///
    /// # Arguments
    ///
    /// * `pool_bech32` - Pool ID in bech32 format
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use koios_sdk::Client;
    /// use koios_sdk::types::PoolBech32;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = Client::new()?;
    ///     let pool_id = PoolBech32::new(
    ///         "pool1pu5jlj4q9w9jlxeu370a3c9myx47md5j5m2str0naunn2q3lkdy"
    ///     );
    ///     let delegators = client.get_pool_delegators(&pool_id).await?;
    ///     println!("Pool delegators: {:?}", delegators);
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_pool_delegators(
        &self,
        pool_bech32: &PoolBech32,
    ) -> Result<Vec<PoolDelegator>> {
        self.get(&format!(
            "/pool_delegators?_pool_bech32={}",
            encode(pool_bech32.value())
        ))
        .await
    }

    /// Get information about active delegators (incl. history) for a given pool and epoch number
    ///
    /// # Arguments
    ///
    /// * `pool_bech32` - Pool ID in bech32 format
    /// * `epoch_no` - Optional epoch number to query
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use koios_sdk::Client;
    /// use koios_sdk::types::{PoolBech32, EpochNo};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = Client::new()?;
    ///     let pool_id = PoolBech32::new(
    ///         "pool1pu5jlj4q9w9jlxeu370a3c9myx47md5j5m2str0naunn2q3lkdy"
    ///     );
    ///     let history = client.get_pool_delegators_history(
    ///         &pool_id,
    ///         Some(EpochNo::new("320"))
    ///     ).await?;
    ///     println!("Pool delegators history: {:?}", history);
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_pool_delegators_history(
        &self,
        pool_bech32: &PoolBech32,
        epoch_no: Option<EpochNo>,
    ) -> Result<Vec<PoolDelegatorsHistory>> {
        let mut endpoint = format!(
            "/pool_delegators_history?_pool_bech32={}",
            encode(pool_bech32.value())
        );

        if let Some(epoch) = epoch_no {
            endpoint.push_str(&format!("&_epoch_no={}", encode(epoch.value())));
        }

        self.get(&endpoint).await
    }

    /// Get pool stake, block and reward history for a specific epoch or all epochs
    ///
    /// # Arguments
    ///
    /// * `pool_bech32` - Pool ID in bech32 format
    /// * `epoch_no` - Optional epoch number to query
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use koios_sdk::Client;
    /// use koios_sdk::types::{PoolBech32, EpochNo};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = Client::new()?;
    ///     let pool_id = PoolBech32::new(
    ///         "pool1pu5jlj4q9w9jlxeu370a3c9myx47md5j5m2str0naunn2q3lkdy"
    ///     );
    ///     let history = client.get_pool_history(
    ///         &pool_id,
    ///         Some(EpochNo::new("320"))
    ///     ).await?;
    ///     println!("Pool history: {:?}", history);
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_pool_history(
        &self,
        pool_bech32: &PoolBech32,
        epoch_no: Option<EpochNo>,
    ) -> Result<Vec<PoolHistoryInfo>> {
        let mut endpoint = format!("/pool_history?_pool_bech32={}", encode(pool_bech32.value()));

        if let Some(epoch) = epoch_no {
            endpoint.push_str(&format!("&_epoch_no={}", encode(epoch.value())));
        }

        self.get(&endpoint).await
    }

    /// Get update history for all pools or a specific pool
    ///
    /// # Arguments
    ///
    /// * `pool_bech32` - Optional pool ID in bech32 format to filter by
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use koios_sdk::Client;
    /// use koios_sdk::types::PoolBech32;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = Client::new()?;
    ///     let pool_id = PoolBech32::new(
    ///         "pool1pu5jlj4q9w9jlxeu370a3c9myx47md5j5m2str0naunn2q3lkdy"
    ///     );
    ///     let updates = client.get_pool_updates(Some(&pool_id)).await?;
    ///     println!("Pool updates: {:?}", updates);
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_pool_updates(
        &self,
        pool_bech32: Option<&PoolBech32>,
    ) -> Result<Vec<PoolUpdate>> {
        let endpoint = if let Some(pool_id) = pool_bech32 {
            format!("/pool_updates?_pool_bech32={}", encode(pool_id.value()))
        } else {
            "/pool_updates".to_string()
        };
        self.get(&endpoint).await
    }

    /// Get all pool registrations initiated in the requested epoch
    ///
    /// # Arguments
    ///
    /// * `epoch_no` - Optional epoch number to query
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use koios_sdk::Client;
    /// use koios_sdk::types::EpochNo;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = Client::new()?;
    ///     let registrations = client.get_pool_registrations(
    ///         Some(EpochNo::new("320"))
    ///     ).await?;
    ///     println!("Pool registrations: {:?}", registrations);
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_pool_registrations(
        &self,
        epoch_no: Option<EpochNo>,
    ) -> Result<Vec<PoolRegistration>> {
        let endpoint = if let Some(epoch) = epoch_no {
            format!("/pool_registrations?_epoch_no={}", encode(epoch.value()))
        } else {
            "/pool_registrations".to_string()
        };
        self.get(&endpoint).await
    }
    /// Get all pool retirements initiated in the requested epoch
    ///
    /// # Arguments
    ///
    /// * `epoch_no` - Optional epoch number to query
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use koios_sdk::Client;
    /// use koios_sdk::types::EpochNo;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = Client::new()?;
    ///     let retirements = client.get_pool_retirements(
    ///         Some(EpochNo::new("320"))
    ///     ).await?;
    ///     println!("Pool retirements: {:?}", retirements);
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_pool_retirements(
        &self,
        epoch_no: Option<EpochNo>,
    ) -> Result<Vec<PoolRegistration>> {
        let endpoint = if let Some(epoch) = epoch_no {
            format!("/pool_retirements?_epoch_no={}", encode(epoch.value()))
        } else {
            "/pool_retirements".to_string()
        };
        self.get(&endpoint).await
    }

    /// Get a list of registered relays for all pools
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use koios_sdk::Client;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = Client::new()?;
    ///     let relays = client.get_pool_relays().await?;
    ///     println!("Pool relays: {:?}", relays);
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_pool_relays(&self) -> Result<Vec<PoolRelay>> {
        self.get("/pool_relays").await
    }

    /// Get list of all votes cast by a pool
    ///
    /// # Arguments
    ///
    /// * `pool_bech32` - Pool ID in bech32 format
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use koios_sdk::Client;
    /// use koios_sdk::types::PoolBech32;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = Client::new()?;
    ///     let pool_id = PoolBech32::new(
    ///         "pool1pu5jlj4q9w9jlxeu370a3c9myx47md5j5m2str0naunn2q3lkdy"
    ///     );
    ///     let votes = client.get_pool_votes(&pool_id).await?;
    ///     println!("Pool votes: {:?}", votes);
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_pool_votes(&self, pool_bech32: &PoolBech32) -> Result<Vec<PoolVotes>> {
        self.get(&format!(
            "/pool_votes?_pool_bech32={}",
            encode(pool_bech32.value())
        ))
        .await
    }

    /// Get metadata (on & off-chain) for all pools or specific pools
    ///
    /// # Arguments
    ///
    /// * `pool_ids` - Optional list of pool IDs to query
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use koios_sdk::Client;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = Client::new()?;
    ///     let pool_ids = Some(vec![
    ///         "pool1pu5jlj4q9w9jlxeu370a3c9myx47md5j5m2str0naunn2q3lkdy".to_string()
    ///     ]);
    ///     let metadata = client.get_pool_metadata(pool_ids.as_deref()).await?;
    ///     println!("Pool metadata: {:?}", metadata);
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_pool_metadata(
        &self,
        pool_ids: Option<&[String]>,
    ) -> Result<Vec<PoolMetadataInfo>> {
        let request = PoolIdsOptionalRequest::new(pool_ids.map(|ids| ids.to_vec()));
        self.post("/pool_metadata", &request).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use wiremock::matchers::{method, path, query_param};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    #[tokio::test]
    async fn test_get_pool_list() {
        let mock_server = MockServer::start().await;
        let client = Client::builder()
            .base_url(mock_server.uri())
            .build()
            .unwrap();

        let mock_response = json!([{
            "pool_id_bech32": "pool1pu5jlj4q9w9jlxeu370a3c9myx47md5j5m2str0naunn2q3lkdy",
            "pool_id_hex": "0f292fcaa02b8b2f9b3c8f9fd8e0bb21abedb692a6d5058df3ef2735",
            "active_epoch_no": 321,
            "margin": 0.015,
            "fixed_cost": "340000000",
            "pledge": "10000000000",
            "reward_addr": "stake1uxkptsa4lkr55jleztw43t37vgdn88l6ghclfwuxld2eykq7dls9w",
            "owners": ["stake1u98nnlkvkk23vtvf9273uq7cph5ww6u2yq2389psuqet90sv4xv9v"],
            "relays": [],
            "ticker": "TEST",
            "meta_url": "https://example.com/metadata.json",
            "meta_hash": "e394c39f06741ace92445d61d0853d8358fd49d1fd08a0b26599bda520",
            "pool_status": "registered",
            "retiring_epoch": null
        }]);

        Mock::given(method("GET"))
            .and(path("/pool_list"))
            .respond_with(ResponseTemplate::new(200).set_body_json(&mock_response))
            .mount(&mock_server)
            .await;

        let response = client.get_pool_list().await.unwrap();
        assert_eq!(response.len(), 1);
        assert_eq!(
            response[0].pool_id_bech32,
            "pool1pu5jlj4q9w9jlxeu370a3c9myx47md5j5m2str0naunn2q3lkdy"
        );
    }

    #[tokio::test]
    async fn test_get_pool_history() {
        let mock_server = MockServer::start().await;
        let client = Client::builder()
            .base_url(mock_server.uri())
            .build()
            .unwrap();

        let pool_id = "pool1pu5jlj4q9w9jlxeu370a3c9myx47md5j5m2str0naunn2q3lkdy";
        let mock_response = json!([{
            "epoch_no": 321,
            "active_stake": "1000000000000",
            "active_stake_pct": 0.5,
            "saturation_pct": 0.75,
            "block_cnt": 100,
            "delegator_cnt": 1000,
            "margin": 0.015,
            "fixed_cost": "340000000",
            "pool_fees": "1500000000",
            "deleg_rewards": "10000000000",
            "epoch_ros": 0.05
        }]);

        Mock::given(method("GET"))
            .and(path("/pool_history"))
            .and(query_param("_pool_bech32", pool_id))
            .respond_with(ResponseTemplate::new(200).set_body_json(&mock_response))
            .mount(&mock_server)
            .await;

        let response = client
            .get_pool_history(&PoolBech32::new(pool_id), None)
            .await
            .unwrap();
        assert_eq!(response.len(), 1);
        assert_eq!(response[0].epoch_no, 321);
    }

    // Add more tests for other endpoints...
}