limitless-exchange-rust-sdk 1.0.13

Rust SDK for Limitless Exchange CLOB and NegRisk trading
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
use serde::{Deserialize, Serialize};
use serde_json::Value;
use url::form_urlencoded::Serializer;

use crate::{errors::Result, http_client::HttpClient};

#[derive(Clone)]
pub struct PortfolioFetcher {
    client: HttpClient,
}

impl PortfolioFetcher {
    pub fn new(client: HttpClient) -> Self {
        Self { client }
    }

    pub async fn get_profile(&self, address: &str) -> Result<UserProfile> {
        self.client.require_auth("get_profile")?;
        self.client.get(&profile_path(address)).await
    }

    pub async fn get_current_profile(&self) -> Result<UserProfile> {
        self.client.require_auth("get_current_profile")?;
        self.client.get(current_profile_path()).await
    }

    pub async fn get_positions(&self) -> Result<PortfolioPositionsResponse> {
        self.client.require_auth("get_positions")?;
        self.client.get("/portfolio/positions").await
    }

    pub async fn get_clob_positions(&self) -> Result<Vec<CLOBPosition>> {
        Ok(self.get_positions().await?.clob)
    }

    pub async fn get_amm_positions(&self) -> Result<Vec<AMMPosition>> {
        Ok(self.get_positions().await?.amm)
    }

    /// Fetch user history with cursor-based pagination.
    ///
    /// `cursor` — pass `None` for the first page (sends `cursor=` empty to
    /// opt into the cursor flow), or `Some("...")` with a previous `nextCursor`.
    /// `limit`  — items per page (1–100, defaults to 20 when omitted).
    pub async fn get_user_history(
        &self,
        cursor: Option<&str>,
        limit: Option<u32>,
    ) -> Result<HistoryResponse> {
        self.client.require_auth("get_user_history")?;
        let url = history_path(cursor, limit);
        self.client.get(&url).await
    }
}

fn profile_path(address: &str) -> String {
    format!("/profiles/{}", urlencoding::encode(address))
}

fn current_profile_path() -> &'static str {
    "/profiles/me"
}

fn history_path(cursor: Option<&str>, limit: Option<u32>) -> String {
    let mut query = Serializer::new(String::new());
    // Always send cursor=, using an empty value on the first page.
    query.append_pair("cursor", cursor.unwrap_or(""));
    query.append_pair("limit", &limit.unwrap_or(20).to_string());
    format!("/portfolio/history?{}", query.finish())
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct UserRank {
    pub id: i32,
    pub name: String,
    #[serde(rename = "feeRateBps")]
    pub fee_rate_bps: i32,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ReferralData {
    #[serde(rename = "createdAt")]
    pub created_at: String,
    pub id: i32,
    #[serde(rename = "referredProfileId")]
    pub referred_profile_id: i32,
    #[serde(rename = "pfpUrl", default)]
    pub pfp_url: Option<String>,
    #[serde(rename = "displayName")]
    pub display_name: String,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct UserProfile {
    pub id: i32,
    pub account: String,
    #[serde(default)]
    pub rank: Option<UserRank>,
    #[serde(rename = "createdAt", default)]
    pub created_at: Option<String>,
    #[serde(default)]
    pub username: Option<String>,
    #[serde(rename = "displayName", default)]
    pub display_name: Option<String>,
    #[serde(rename = "pfpUrl", default)]
    pub pfp_url: Option<String>,
    #[serde(default)]
    pub bio: Option<String>,
    #[serde(rename = "socialUrl", default)]
    pub social_url: Option<String>,
    #[serde(rename = "tradeWalletOption", default)]
    pub trade_wallet_option: Option<String>,
    #[serde(rename = "embeddedAccount", default)]
    pub embedded_account: Option<String>,
    #[serde(default)]
    pub points: Option<f64>,
    #[serde(rename = "accumulativePoints", default)]
    pub accumulative_points: Option<f64>,
    #[serde(rename = "enrolledInPointsProgram", default)]
    pub enrolled_in_points_program: Option<bool>,
    #[serde(rename = "leaderboardPosition", default)]
    pub leaderboard_position: Option<i32>,
    #[serde(rename = "isTop100", default)]
    pub is_top_100: Option<bool>,
    #[serde(rename = "isCaptain", default)]
    pub is_captain: Option<bool>,
    #[serde(rename = "referralData", default)]
    pub referral_data: Vec<ReferralData>,
    #[serde(rename = "referredUsersCount", default)]
    pub referred_users_count: Option<i32>,
}

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

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PositionMarket {
    pub id: Value,
    pub slug: String,
    pub title: String,
    #[serde(default)]
    pub status: Option<String>,
    pub closed: bool,
    pub deadline: String,
    #[serde(rename = "conditionId", default)]
    pub condition_id: Option<String>,
    #[serde(rename = "winningOutcomeIndex", default)]
    pub winning_outcome_index: Option<i32>,
    #[serde(default)]
    pub group: Option<PositionMarketGroup>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PositionSide {
    pub cost: String,
    #[serde(rename = "fillPrice")]
    pub fill_price: String,
    #[serde(rename = "marketValue")]
    pub market_value: String,
    #[serde(rename = "realisedPnl")]
    pub realised_pnl: String,
    #[serde(rename = "unrealizedPnl")]
    pub unrealized_pnl: String,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TokenBalance {
    pub yes: String,
    pub no: String,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct LatestTrade {
    #[serde(rename = "latestYesPrice", default)]
    pub latest_yes_price: Option<f64>,
    #[serde(rename = "latestNoPrice", default)]
    pub latest_no_price: Option<f64>,
    #[serde(rename = "outcomeTokenPrice", default)]
    pub outcome_token_price: Option<f64>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ClobPositionOrders {
    #[serde(rename = "liveOrders")]
    pub live_orders: Vec<Value>,
    #[serde(rename = "totalCollateralLocked")]
    pub total_collateral_locked: String,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ClobPositionRewards {
    pub epochs: Vec<Value>,
    #[serde(rename = "isEarning")]
    pub is_earning: bool,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ClobPositionSides {
    pub yes: PositionSide,
    pub no: PositionSide,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CLOBPosition {
    pub market: PositionMarket,
    #[serde(rename = "makerAddress")]
    pub maker_address: String,
    pub positions: ClobPositionSides,
    #[serde(rename = "tokensBalance")]
    pub tokens_balance: TokenBalance,
    #[serde(rename = "latestTrade")]
    pub latest_trade: LatestTrade,
    #[serde(default)]
    pub orders: Option<ClobPositionOrders>,
    #[serde(default)]
    pub rewards: Option<ClobPositionRewards>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AmmLatestTrade {
    #[serde(rename = "outcomeTokenPrice")]
    pub outcome_token_price: String,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AMMPosition {
    pub market: PositionMarket,
    pub account: String,
    #[serde(rename = "outcomeIndex")]
    pub outcome_index: i32,
    #[serde(rename = "collateralAmount")]
    pub collateral_amount: String,
    #[serde(rename = "outcomeTokenAmount")]
    pub outcome_token_amount: String,
    #[serde(rename = "averageFillPrice")]
    pub average_fill_price: String,
    #[serde(rename = "totalBuysCost")]
    pub total_buys_cost: String,
    #[serde(rename = "totalSellsCost")]
    pub total_sells_cost: String,
    #[serde(rename = "realizedPnl")]
    pub realized_pnl: String,
    #[serde(rename = "unrealizedPnl")]
    pub unrealized_pnl: String,
    #[serde(rename = "latestTrade", default)]
    pub latest_trade: Option<AmmLatestTrade>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PortfolioRewards {
    #[serde(rename = "todaysRewards")]
    pub todays_rewards: String,
    #[serde(rename = "rewardsByEpoch")]
    pub rewards_by_epoch: Vec<Value>,
    #[serde(rename = "rewardsChartData")]
    pub rewards_chart_data: Vec<Value>,
    #[serde(rename = "totalUnpaidRewards")]
    pub total_unpaid_rewards: String,
    #[serde(rename = "totalUserRewardsLastEpoch")]
    pub total_user_rewards_last_epoch: String,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PortfolioPositionsResponse {
    #[serde(default)]
    pub amm: Vec<AMMPosition>,
    #[serde(default)]
    pub clob: Vec<CLOBPosition>,
    #[serde(default)]
    pub group: Vec<Value>,
    #[serde(default)]
    pub points: Option<String>,
    #[serde(rename = "accumulativePoints", default)]
    pub accumulative_points: Option<String>,
    #[serde(default)]
    pub rewards: Option<PortfolioRewards>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Position {
    #[serde(rename = "type")]
    pub position_type: String,
    pub market: PositionMarket,
    pub side: String,
    #[serde(rename = "costBasis")]
    pub cost_basis: f64,
    #[serde(rename = "marketValue")]
    pub market_value: f64,
    #[serde(rename = "unrealizedPnl")]
    pub unrealized_pnl: f64,
    #[serde(rename = "realizedPnl")]
    pub realized_pnl: f64,
    #[serde(rename = "currentPrice")]
    pub current_price: f64,
    #[serde(rename = "avgPrice")]
    pub avg_price: f64,
    #[serde(rename = "tokenBalance")]
    pub token_balance: f64,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PortfolioBreakdownEntry {
    pub positions: i32,
    pub value: f64,
    pub pnl: f64,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PortfolioBreakdown {
    pub clob: PortfolioBreakdownEntry,
    pub amm: PortfolioBreakdownEntry,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PortfolioSummary {
    #[serde(rename = "totalValue")]
    pub total_value: f64,
    #[serde(rename = "totalCostBasis")]
    pub total_cost_basis: f64,
    #[serde(rename = "totalUnrealizedPnl")]
    pub total_unrealized_pnl: f64,
    #[serde(rename = "totalRealizedPnl")]
    pub total_realized_pnl: f64,
    #[serde(rename = "totalUnrealizedPnlPercent")]
    pub total_unrealized_pnl_percent: f64,
    #[serde(rename = "positionCount")]
    pub position_count: i32,
    #[serde(rename = "marketCount")]
    pub market_count: i32,
    pub breakdown: PortfolioBreakdown,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct HistoryMarketCollateral {
    pub symbol: String,
    pub id: String,
    pub decimals: i32,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct HistoryMarket {
    pub closed: bool,
    #[serde(default)]
    pub collateral: Option<HistoryMarketCollateral>,
    #[serde(default)]
    pub group: Option<Value>,
    #[serde(rename = "conditionId", default)]
    pub condition_id: Option<String>,
    #[serde(default)]
    pub funding: Option<String>,
    pub id: String,
    pub slug: String,
    pub title: String,
    #[serde(rename = "expirationDate", default)]
    pub expiration_date: Option<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct HistoryEntry {
    #[serde(rename = "blockTimestamp")]
    pub block_timestamp: i64,
    #[serde(rename = "collateralAmount", default)]
    pub collateral_amount: Option<String>,
    #[serde(default)]
    pub market: Option<HistoryMarket>,
    #[serde(rename = "outcomeIndex", default)]
    pub outcome_index: Option<i32>,
    #[serde(rename = "outcomeTokenAmount", default)]
    pub outcome_token_amount: Option<String>,
    #[serde(rename = "outcomeTokenAmounts", default)]
    pub outcome_token_amounts: Option<Vec<String>>,
    #[serde(rename = "outcomeTokenPrice", default)]
    pub outcome_token_price: Option<Value>,
    #[serde(default)]
    pub strategy: Option<String>,
    #[serde(rename = "transactionHash", default)]
    pub transaction_hash: Option<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct HistoryResponse {
    pub data: Vec<HistoryEntry>,
    #[serde(rename = "nextCursor")]
    pub next_cursor: Option<String>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{errors::LimitlessError, http_client::HttpClient};
    use serde_json::json;

    #[test]
    fn profile_paths_match_api_routes() {
        assert_eq!(
            profile_path("0xa00BCB04073B243E8A55f3B5899AefF596bF17C6"),
            "/profiles/0xa00BCB04073B243E8A55f3B5899AefF596bF17C6"
        );
        assert_eq!(profile_path("0xabc def"), "/profiles/0xabc%20def");
        assert_eq!(current_profile_path(), "/profiles/me");
    }

    #[tokio::test]
    async fn current_profile_requires_auth_before_network() {
        let fetcher = PortfolioFetcher::new(HttpClient::builder().build().unwrap());
        let err = fetcher.get_current_profile().await.unwrap_err();
        match err {
            LimitlessError::AuthenticationRequired { operation } => {
                assert_eq!(operation, "get_current_profile");
            }
            other => panic!("expected authentication error, got {other:?}"),
        }
    }

    #[test]
    fn history_path_uses_empty_cursor_and_default_limit_on_first_page() {
        assert_eq!(
            history_path(None, None),
            "/portfolio/history?cursor=&limit=20"
        );
    }

    #[test]
    fn history_path_forwards_cursor_and_limit() {
        assert_eq!(
            history_path(Some("cursor-1"), Some(5)),
            "/portfolio/history?cursor=cursor-1&limit=5"
        );
    }

    #[test]
    fn history_response_deserializes_cursor_shape() {
        let response: HistoryResponse = serde_json::from_value(json!({
            "data": [{
                "blockTimestamp": 1712345678,
                "collateralAmount": "15.25",
                "market": {
                    "closed": false,
                    "collateral": {
                        "symbol": "USDC",
                        "id": "usdc",
                        "decimals": 6
                    },
                    "conditionId": "0xcond",
                    "funding": "1000",
                    "id": "market-1",
                    "slug": "btc-above-100k",
                    "title": "BTC above 100k?",
                    "expirationDate": "2026-12-31T00:00:00.000Z"
                },
                "outcomeIndex": 0,
                "outcomeTokenAmount": "20",
                "outcomeTokenAmounts": ["20", "0"],
                "outcomeTokenPrice": 0.76,
                "strategy": "Buy",
                "transactionHash": "0xtx1"
            }],
            "nextCursor": "cursor-2"
        }))
        .expect("history response should deserialize");

        assert_eq!(response.next_cursor.as_deref(), Some("cursor-2"));
        assert_eq!(response.data.len(), 1);

        let entry = &response.data[0];
        assert_eq!(entry.block_timestamp, 1_712_345_678);
        assert_eq!(entry.strategy.as_deref(), Some("Buy"));
        assert_eq!(entry.transaction_hash.as_deref(), Some("0xtx1"));
        assert_eq!(
            entry.market.as_ref().map(|m| m.slug.as_str()),
            Some("btc-above-100k")
        );
        assert_eq!(entry.outcome_token_price, Some(json!(0.76)));
    }

    #[test]
    fn clob_position_latest_trade_deserializes_without_price_fields() {
        let position: CLOBPosition = serde_json::from_value(json!({
            "market": {
                "id": 1,
                "slug": "btc-above-100k",
                "title": "BTC above 100k?",
                "closed": false,
                "deadline": "2026-12-31T00:00:00.000Z"
            },
            "makerAddress": "0xmaker",
            "positions": {
                "yes": {
                    "cost": "10",
                    "fillPrice": "0.5",
                    "marketValue": "12",
                    "realisedPnl": "0",
                    "unrealizedPnl": "2"
                },
                "no": {
                    "cost": "0",
                    "fillPrice": "0",
                    "marketValue": "0",
                    "realisedPnl": "0",
                    "unrealizedPnl": "0"
                }
            },
            "tokensBalance": {
                "yes": "20",
                "no": "0"
            },
            "latestTrade": {}
        }))
        .expect("clob position should deserialize");

        assert_eq!(position.latest_trade.latest_yes_price, None);
        assert_eq!(position.latest_trade.latest_no_price, None);
        assert_eq!(position.latest_trade.outcome_token_price, None);
    }
}