wf-market 0.2.2

A Rust client library for the warframe.market API
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
//! Orders API endpoints.

use serde_json::json;

use crate::client::{AuthState, Authenticated, Client};
use crate::error::{ApiErrorResponse, Error, Result};
use crate::internal::BASE_URL;
use crate::models::{
    CreateOrder, Order, OrderListing, OwnedOrder, OwnedOrderId, TopOrderFilters, TopOrders,
    Transaction, UpdateOrder,
};

use super::ApiResponse;

// === Public endpoints (both authenticated and unauthenticated) ===

impl<S: AuthState> Client<S> {
    /// Get orders for an item, including seller/buyer information.
    ///
    /// Returns orders from users who were online in the last 7 days.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use wf_market::Client;
    ///
    /// async fn example() -> wf_market::Result<()> {
    ///     let client = Client::builder().build()?;
    ///     let orders = client.get_orders("nikana_prime_set").await?;
    ///
    ///     for order in &orders {
    ///         println!(
    ///             "{} wants to {} for {}p ({})",
    ///             order.user.ingame_name,
    ///             order.order_type,
    ///             order.platinum,
    ///             order.user.status
    ///         );
    ///     }
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_orders(&self, slug: &str) -> Result<Vec<OrderListing>> {
        self.wait_for_rate_limit().await;

        let response = self
            .http
            .get(format!("{}/orders/item/{}", BASE_URL, slug))
            .send()
            .await
            .map_err(Error::Network)?;

        let status = response.status();

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

        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();

            if let Ok(error_response) = serde_json::from_str::<ApiErrorResponse>(&body) {
                return Err(Error::api_with_response(
                    status,
                    format!("Failed to fetch orders for: {}", slug),
                    error_response,
                ));
            }

            return Err(Error::api(
                status,
                format!("Failed to fetch orders: {}", body),
            ));
        }

        let body = response.text().await.map_err(Error::Network)?;

        let api_response: ApiResponse<Vec<OrderListing>> =
            serde_json::from_str(&body).map_err(|e| Error::parse_with_body(e.to_string(), body))?;

        Ok(api_response.data)
    }

    /// Get orders for an item without user information.
    ///
    /// This is a lighter response when you only need order data
    /// (price, quantity, etc.) without seller/buyer details.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use wf_market::Client;
    ///
    /// async fn example() -> wf_market::Result<()> {
    ///     let client = Client::builder().build()?;
    ///     let orders = client.get_listings("nikana_prime_set").await?;
    ///
    ///     let avg_price: f64 = orders.iter()
    ///         .map(|o| o.platinum as f64)
    ///         .sum::<f64>() / orders.len() as f64;
    ///
    ///     println!("Average price: {:.0}p", avg_price);
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_listings(&self, slug: &str) -> Result<Vec<Order>> {
        let listings = self.get_orders(slug).await?;
        Ok(listings.into_iter().map(|l| l.order).collect())
    }

    /// Get top orders for an item (best buy and sell prices).
    ///
    /// Returns the top 5 buy orders (highest prices) and top 5 sell
    /// orders (lowest prices). Only includes orders from online users.
    ///
    /// # Arguments
    ///
    /// * `slug` - The item's URL-friendly identifier
    /// * `filters` - Optional filters for mod rank, charges, stars, or subtype
    ///
    /// # Example
    ///
    /// ```ignore
    /// use wf_market::{Client, TopOrderFilters};
    ///
    /// async fn example() -> wf_market::Result<()> {
    ///     let client = Client::builder().build()?;
    ///
    ///     // Get top orders without filters
    ///     let top = client.get_top_orders("nikana_prime_set", None).await?;
    ///
    ///     // Get top orders for max rank mods
    ///     let filters = TopOrderFilters::new().rank(10);
    ///     let top = client.get_top_orders("serration", Some(&filters)).await?;
    ///
    ///     // Get top orders for sculptures with specific stars
    ///     let filters = TopOrderFilters::new().amber_stars(2).cyan_stars(4);
    ///     let top = client.get_top_orders("ayatan_anasa_sculpture", Some(&filters)).await?;
    ///
    ///     if let (Some(sell), Some(buy)) = (top.best_sell_price(), top.best_buy_price()) {
    ///         println!("Best sell: {}p, Best buy: {}p", sell, buy);
    ///         if let Some(spread) = top.spread() {
    ///             println!("Spread: {}p", spread);
    ///         }
    ///     }
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_top_orders(
        &self,
        slug: &str,
        filters: Option<&TopOrderFilters>,
    ) -> Result<TopOrders> {
        self.wait_for_rate_limit().await;

        let query = filters.map_or(String::new(), |f| f.to_query_string());
        let url = format!("{}/orders/item/{}/top{}", BASE_URL, slug, query);

        let response = self.http.get(&url).send().await.map_err(Error::Network)?;

        let status = response.status();

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

        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();
            return Err(Error::api(
                status,
                format!("Failed to fetch top orders: {}", body),
            ));
        }

        let body = response.text().await.map_err(Error::Network)?;

        let api_response: ApiResponse<TopOrders> =
            serde_json::from_str(&body).map_err(|e| Error::parse_with_body(e.to_string(), body))?;

        Ok(api_response.data)
    }

    /// Get recent orders from the last 4 hours.
    ///
    /// Returns up to 500 of the most recent orders, sorted by creation time.
    /// Results are cached server-side with a 1-minute refresh interval.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use wf_market::Client;
    ///
    /// async fn example() -> wf_market::Result<()> {
    ///     let client = Client::builder().build()?;
    ///     let recent = client.get_recent_orders().await?;
    ///
    ///     for order in &recent {
    ///         println!(
    ///             "{} wants to {} {} for {}p",
    ///             order.user.ingame_name,
    ///             order.order_type,
    ///             order.order.item_id,
    ///             order.order.platinum
    ///         );
    ///     }
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_recent_orders(&self) -> Result<Vec<OrderListing>> {
        self.wait_for_rate_limit().await;

        let response = self
            .http
            .get(format!("{}/orders/recent", BASE_URL))
            .send()
            .await
            .map_err(Error::Network)?;

        let status = response.status();

        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();

            if let Ok(error_response) = serde_json::from_str::<ApiErrorResponse>(&body) {
                return Err(Error::api_with_response(
                    status,
                    "Failed to fetch recent orders",
                    error_response,
                ));
            }

            return Err(Error::api(
                status,
                format!("Failed to fetch recent orders: {}", body),
            ));
        }

        let body = response.text().await.map_err(Error::Network)?;

        let api_response: ApiResponse<Vec<OrderListing>> =
            serde_json::from_str(&body).map_err(|e| Error::parse_with_body(e.to_string(), body))?;

        Ok(api_response.data)
    }

    /// Get all public orders for a specific user.
    ///
    /// Returns orders without user information (since the user is known).
    ///
    /// # Example
    ///
    /// ```ignore
    /// use wf_market::Client;
    ///
    /// async fn example() -> wf_market::Result<()> {
    ///     let client = Client::builder().build()?;
    ///     let orders = client.get_user_orders("some_user").await?;
    ///
    ///     for order in &orders {
    ///         println!(
    ///             "{}: {} @ {}p",
    ///             order.order_type,
    ///             order.item_id,
    ///             order.platinum
    ///         );
    ///     }
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_user_orders(&self, user_slug: &str) -> Result<Vec<Order>> {
        self.wait_for_rate_limit().await;

        let response = self
            .http
            .get(format!("{}/orders/user/{}", BASE_URL, user_slug))
            .send()
            .await
            .map_err(Error::Network)?;

        let status = response.status();

        if status == reqwest::StatusCode::NOT_FOUND {
            return Err(Error::not_found(format!("User not found: {}", user_slug)));
        }

        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();

            if let Ok(error_response) = serde_json::from_str::<ApiErrorResponse>(&body) {
                return Err(Error::api_with_response(
                    status,
                    format!("Failed to fetch orders for user: {}", user_slug),
                    error_response,
                ));
            }

            return Err(Error::api(
                status,
                format!("Failed to fetch user orders: {}", body),
            ));
        }

        let body = response.text().await.map_err(Error::Network)?;

        let api_response: ApiResponse<Vec<Order>> =
            serde_json::from_str(&body).map_err(|e| Error::parse_with_body(e.to_string(), body))?;

        Ok(api_response.data)
    }

    /// Get a single order by ID.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use wf_market::Client;
    ///
    /// async fn example() -> wf_market::Result<()> {
    ///     let client = Client::builder().build()?;
    ///     let order = client.get_order("order-id-here").await?;
    ///     println!("Order: {} @ {}p", order.item_id, order.platinum);
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_order(&self, id: &str) -> Result<Order> {
        self.wait_for_rate_limit().await;

        let response = self
            .http
            .get(format!("{}/order/{}", BASE_URL, id))
            .send()
            .await
            .map_err(Error::Network)?;

        let status = response.status();

        if status == reqwest::StatusCode::NOT_FOUND {
            return Err(Error::not_found(format!("Order not found: {}", id)));
        }

        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();

            if let Ok(error_response) = serde_json::from_str::<ApiErrorResponse>(&body) {
                return Err(Error::api_with_response(
                    status,
                    format!("Failed to fetch order: {}", id),
                    error_response,
                ));
            }

            return Err(Error::api(
                status,
                format!("Failed to fetch order: {}", body),
            ));
        }

        let body = response.text().await.map_err(Error::Network)?;

        let api_response: ApiResponse<Order> =
            serde_json::from_str(&body).map_err(|e| Error::parse_with_body(e.to_string(), body))?;

        Ok(api_response.data)
    }
}

// === Authenticated endpoints ===

impl Client<Authenticated> {
    /// Get the authenticated user's orders.
    ///
    /// Returns orders as [`OwnedOrder`] which provides type-safe
    /// access to mutation operations.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use wf_market::{Client, Credentials};
    ///
    /// async fn example() -> wf_market::Result<()> {
    ///     let client = Client::from_credentials(/* ... */).await?;
    ///
    ///     let orders = client.my_orders().await?;
    ///     for order in &orders {
    ///         println!(
    ///             "{}: {} @ {}p (qty: {})",
    ///             order.id(),
    ///             order.item_id(),
    ///             order.platinum(),
    ///             order.quantity()
    ///         );
    ///     }
    ///     Ok(())
    /// }
    /// # fn main() {}
    /// ```
    pub async fn my_orders(&self) -> Result<Vec<OwnedOrder>> {
        self.wait_for_rate_limit().await;

        let response = self
            .http
            .get(format!("{}/orders/my", BASE_URL))
            .send()
            .await
            .map_err(Error::Network)?;

        let status = response.status();

        if status == reqwest::StatusCode::UNAUTHORIZED {
            return Err(Error::auth("Session expired or invalid"));
        }

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

        let body = response.text().await.map_err(Error::Network)?;

        let api_response: ApiResponse<Vec<Order>> =
            serde_json::from_str(&body).map_err(|e| Error::parse_with_body(e.to_string(), body))?;

        Ok(api_response.data.into_iter().map(OwnedOrder::new).collect())
    }

    /// Create a new order.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use wf_market::{Client, Credentials, CreateOrder};
    ///
    /// async fn example() -> wf_market::Result<()> {
    ///     let client = Client::from_credentials(/* ... */).await?;
    ///
    ///     // Simple sell order
    ///     let order = client.create_order(
    ///         CreateOrder::sell("nikana_prime_set", 100, 1)
    ///     ).await?;
    ///
    ///     // Mod order with rank
    ///     let order = client.create_order(
    ///         CreateOrder::sell("serration", 50, 1).with_mod_rank(10)
    ///     ).await?;
    ///
    ///     println!("Created order: {}", order.id());
    ///     Ok(())
    /// }
    /// # fn main() {}
    /// ```
    pub async fn create_order(&self, request: CreateOrder) -> Result<OwnedOrder> {
        self.wait_for_rate_limit().await;

        let response = self
            .http
            .post(format!("{}/order", BASE_URL))
            .json(&request)
            .send()
            .await
            .map_err(Error::Network)?;

        let status = response.status();

        if status == reqwest::StatusCode::UNAUTHORIZED {
            return Err(Error::auth("Session expired or invalid"));
        }

        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();

            if let Ok(error_response) = serde_json::from_str::<ApiErrorResponse>(&body) {
                return Err(Error::api_with_response(
                    status,
                    "Failed to create order",
                    error_response,
                ));
            }

            return Err(Error::api(
                status,
                format!("Failed to create order: {}", body),
            ));
        }

        let body = response.text().await.map_err(Error::Network)?;

        let api_response: ApiResponse<Order> =
            serde_json::from_str(&body).map_err(|e| Error::parse_with_body(e.to_string(), body))?;

        Ok(OwnedOrder::new(api_response.data))
    }

    /// Update an existing order.
    ///
    /// Only include the fields you want to change in the [`UpdateOrder`].
    ///
    /// # Example
    ///
    /// ```ignore
    /// use wf_market::{Client, Credentials, UpdateOrder};
    ///
    /// async fn example() -> wf_market::Result<()> {
    ///     let client = Client::from_credentials(/* ... */).await?;
    ///
    ///     let orders = client.my_orders().await?;
    ///     if let Some(order) = orders.first() {
    ///         // Update price
    ///         let updated = client.update_order(
    ///             order.id(),
    ///             UpdateOrder::new().platinum(90)
    ///         ).await?;
    ///
    ///         println!("Updated to {}p", updated.platinum());
    ///     }
    ///     Ok(())
    /// }
    /// # fn main() {}
    /// ```
    pub async fn update_order(&self, id: &OwnedOrderId, update: UpdateOrder) -> Result<OwnedOrder> {
        self.wait_for_rate_limit().await;

        let response = self
            .http
            .patch(format!("{}/order/{}", BASE_URL, id.as_str()))
            .json(&update)
            .send()
            .await
            .map_err(Error::Network)?;

        let status = response.status();

        if status == reqwest::StatusCode::UNAUTHORIZED {
            return Err(Error::auth("Session expired or invalid"));
        }

        if status == reqwest::StatusCode::NOT_FOUND {
            return Err(Error::not_found(format!("Order not found: {}", id)));
        }

        if status == reqwest::StatusCode::FORBIDDEN {
            return Err(Error::auth("You don't own this order"));
        }

        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();

            if let Ok(error_response) = serde_json::from_str::<ApiErrorResponse>(&body) {
                return Err(Error::api_with_response(
                    status,
                    "Failed to update order",
                    error_response,
                ));
            }

            return Err(Error::api(
                status,
                format!("Failed to update order: {}", body),
            ));
        }

        let body = response.text().await.map_err(Error::Network)?;

        let api_response: ApiResponse<Order> =
            serde_json::from_str(&body).map_err(|e| Error::parse_with_body(e.to_string(), body))?;

        Ok(OwnedOrder::new(api_response.data))
    }

    /// Delete an order.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use wf_market::{Client, Credentials};
    ///
    /// async fn example() -> wf_market::Result<()> {
    ///     let client = Client::from_credentials(/* ... */).await?;
    ///
    ///     let orders = client.my_orders().await?;
    ///     if let Some(order) = orders.first() {
    ///         client.delete_order(order.id()).await?;
    ///         println!("Deleted order");
    ///     }
    ///     Ok(())
    /// }
    /// # fn main() {}
    /// ```
    pub async fn delete_order(&self, id: &OwnedOrderId) -> Result<()> {
        self.wait_for_rate_limit().await;

        let response = self
            .http
            .delete(format!("{}/order/{}", BASE_URL, id.as_str()))
            .send()
            .await
            .map_err(Error::Network)?;

        let status = response.status();

        if status == reqwest::StatusCode::UNAUTHORIZED {
            return Err(Error::auth("Session expired or invalid"));
        }

        if status == reqwest::StatusCode::NOT_FOUND {
            return Err(Error::not_found(format!("Order not found: {}", id)));
        }

        if status == reqwest::StatusCode::FORBIDDEN {
            return Err(Error::auth("You don't own this order"));
        }

        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();
            return Err(Error::api(
                status,
                format!("Failed to delete order: {}", body),
            ));
        }

        Ok(())
    }

    /// Close (partially or fully) an order.
    ///
    /// This records a transaction for the specified quantity. If you
    /// close the entire remaining quantity, the order will be removed.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use wf_market::{Client, Credentials};
    ///
    /// async fn example() -> wf_market::Result<()> {
    ///     let client = Client::from_credentials(/* ... */).await?;
    ///
    ///     let orders = client.my_orders().await?;
    ///     if let Some(order) = orders.first() {
    ///         // Close 5 units of the order
    ///         let transaction = client.close_order(order.id(), 5).await?;
    ///         println!(
    ///             "Closed {} units for {} total platinum",
    ///             transaction.quantity,
    ///             transaction.total_value()
    ///         );
    ///     }
    ///     Ok(())
    /// }
    /// # fn main() {}
    /// ```
    pub async fn close_order(&self, id: &OwnedOrderId, quantity: u32) -> Result<Transaction> {
        self.wait_for_rate_limit().await;

        let response = self
            .http
            .post(format!("{}/order/{}/close", BASE_URL, id.as_str()))
            .json(&json!({ "quantity": quantity }))
            .send()
            .await
            .map_err(Error::Network)?;

        let status = response.status();

        if status == reqwest::StatusCode::UNAUTHORIZED {
            return Err(Error::auth("Session expired or invalid"));
        }

        if status == reqwest::StatusCode::NOT_FOUND {
            return Err(Error::not_found(format!("Order not found: {}", id)));
        }

        if status == reqwest::StatusCode::FORBIDDEN {
            return Err(Error::auth("You don't own this order"));
        }

        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();

            if let Ok(error_response) = serde_json::from_str::<ApiErrorResponse>(&body) {
                return Err(Error::api_with_response(
                    status,
                    "Failed to close order",
                    error_response,
                ));
            }

            return Err(Error::api(
                status,
                format!("Failed to close order: {}", body),
            ));
        }

        let body = response.text().await.map_err(Error::Network)?;

        let api_response: ApiResponse<Transaction> =
            serde_json::from_str(&body).map_err(|e| Error::parse_with_body(e.to_string(), body))?;

        Ok(api_response.data)
    }
}