digdigdig3 0.3.17

Unified async Rust API for 47 exchange connectors (REST + WebSocket). The core layer — pure ExchangeHub + connectors. Higher-level builder, persistence, replay, OB tracker live in `digdigdig3-station`.
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
//! # Lighter Exchange Endpoints
//!
//! URL'ы и endpoint enum для Lighter API.

use crate::core::types::AccountType;

// ═══════════════════════════════════════════════════════════════════════════════
// URLs
// ═══════════════════════════════════════════════════════════════════════════════

/// URL'ы для Lighter API
#[derive(Debug, Clone)]
pub struct LighterUrls {
    pub rest: &'static str,
    pub ws: &'static str,
    pub explorer: &'static str,
}

impl LighterUrls {
    /// Mainnet URLs
    pub const MAINNET: Self = Self {
        rest: "https://mainnet.zklighter.elliot.ai",
        ws: "wss://mainnet.zklighter.elliot.ai/stream",
        explorer: "https://explorer.elliot.ai",
    };

    /// Testnet URLs
    pub const TESTNET: Self = Self {
        rest: "https://testnet.zklighter.elliot.ai",
        ws: "wss://testnet.zklighter.elliot.ai/stream",
        explorer: "https://explorer.elliot.ai",
    };

    /// Get REST base URL (same for all account types)
    pub fn rest_url(&self) -> &str {
        self.rest
    }

    /// Get WebSocket URL (same for all account types)
    pub fn ws_url(&self) -> &str {
        self.ws
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// ENDPOINTS
// ═══════════════════════════════════════════════════════════════════════════════

/// Lighter API endpoints
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LighterEndpoint {
    // === GENERAL ===
    Status,
    Info,
    CurrentHeight,

    // === MARKET DATA ===
    OrderBooks,
    OrderBookDetails,
    OrderBookOrders,
    RecentTrades,
    Trades,
    Candlesticks,
    Fundings,
    ExchangeStats,

    // === TRADING ===
    SendTx,
    SendTxBatch,
    NextNonce,

    // === ACCOUNT ===
    Account,
    AccountsByL1Address,
    ApiKeys,
    AccountActiveOrders,
    AccountInactiveOrders,
    AccountTxs,
    Pnl,

    // === DEPOSIT/WITHDRAWAL ===
    DepositHistory,
    DepositLatest,
    WithdrawHistory,

    // === BLOCKCHAIN ===
    Block,
    Blocks,
    Transaction,
    Transactions,
    BlockTxs,
    TxFromL1TxHash,

    // === MISC ===
    PublicPools,
    TransferFeeInfo,

    // === MARKET DATA (Extended) ===
    /// GET /api/v1/funding-rates — latest funding rates per market
    FundingRates,
    /// GET /api/v1/exchangeMetrics — aggregate exchange metrics
    ExchangeMetrics,
    /// GET /api/v1/markPriceCandles — historical mark price OHLC candles per market.
    /// Params: `market_id` (int), `resolution` (1m/5m/15m/30m/1h/4h/12h/1d),
    /// `start_timestamp`, `end_timestamp`, `count_back`; ≤500 candles/call.
    MarkPriceCandles,

    // === ACCOUNT (Extended) ===
    /// GET /api/v1/accountLimits — account-level trading limits
    AccountLimits,
    /// GET /api/v1/accountMetadata — account metadata (tier, settings)
    AccountMetadata,
    /// GET /api/v1/positionFunding — per-position funding payments
    PositionFunding,
    /// GET /api/v1/liquidations — account liquidation history
    Liquidations,

    // === CUSTODIAL ===
    /// GET /api/v1/withdrawalDelays — pending withdrawal delay info
    WithdrawalDelays,
}

impl LighterEndpoint {
    /// Get path for endpoint
    pub fn path(&self) -> &'static str {
        match self {
            // General
            Self::Status => "/",
            Self::Info => "/info",
            Self::CurrentHeight => "/api/v1/currentHeight",

            // Market Data
            Self::OrderBooks => "/api/v1/orderBooks",
            Self::OrderBookDetails => "/api/v1/orderBookDetails",
            Self::OrderBookOrders => "/api/v1/orderBookOrders",
            Self::RecentTrades => "/api/v1/recentTrades",
            Self::Trades => "/api/v1/trades",
            Self::Candlesticks => "/api/v1/candles",
            Self::Fundings => "/api/v1/fundings",
            Self::ExchangeStats => "/api/v1/exchangeStats",

            // Trading
            Self::SendTx => "/api/v1/sendTx",
            Self::SendTxBatch => "/api/v1/sendTxBatch",
            Self::NextNonce => "/api/v1/nextNonce",

            // Account
            Self::Account => "/api/v1/account",
            Self::AccountsByL1Address => "/api/v1/accountsByL1Address",
            Self::ApiKeys => "/api/v1/apikeys",
            Self::AccountActiveOrders => "/api/v1/accountActiveOrders",
            Self::AccountInactiveOrders => "/api/v1/accountInactiveOrders",
            Self::AccountTxs => "/api/v1/accountTxs",
            Self::Pnl => "/api/v1/pnl",

            // Deposit/Withdrawal
            Self::DepositHistory => "/api/v1/deposit/history",
            Self::DepositLatest => "/api/v1/deposit/latest",
            Self::WithdrawHistory => "/api/v1/withdraw/history",

            // Blockchain
            Self::Block => "/api/v1/block",
            Self::Blocks => "/api/v1/blocks",
            Self::Transaction => "/api/v1/tx",
            Self::Transactions => "/api/v1/txs",
            Self::BlockTxs => "/api/v1/blockTxs",
            Self::TxFromL1TxHash => "/api/v1/txFromL1TxHash",

            // Misc
            Self::PublicPools => "/api/v1/publicPools",
            Self::TransferFeeInfo => "/api/v1/transferFeeInfo",

            // Market Data (Extended)
            Self::FundingRates => "/api/v1/funding-rates",
            Self::ExchangeMetrics => "/api/v1/exchangeMetrics",
            Self::MarkPriceCandles => "/api/v1/markPriceCandles",

            // Account (Extended)
            Self::AccountLimits => "/api/v1/accountLimits",
            Self::AccountMetadata => "/api/v1/accountMetadata",
            Self::PositionFunding => "/api/v1/positionFunding",
            Self::Liquidations => "/api/v1/liquidations",

            // Custodial
            Self::WithdrawalDelays => "/api/v1/withdrawalDelays",
        }
    }

    /// Does endpoint require authentication
    pub fn requires_auth(&self) -> bool {
        match self {
            // Public endpoints
            Self::Status
            | Self::Info
            | Self::CurrentHeight
            | Self::OrderBooks
            | Self::OrderBookDetails
            | Self::OrderBookOrders
            | Self::RecentTrades
            | Self::Trades
            | Self::Candlesticks
            | Self::Fundings
            | Self::ExchangeStats
            | Self::Block
            | Self::Blocks
            | Self::Transaction
            | Self::Transactions
            | Self::BlockTxs
            | Self::TxFromL1TxHash
            | Self::PublicPools
            | Self::TransferFeeInfo
            | Self::FundingRates
            | Self::ExchangeMetrics
            | Self::MarkPriceCandles => false,

            // Private endpoints
            _ => true,
        }
    }

    /// HTTP method for endpoint
    pub fn method(&self) -> &'static str {
        match self {
            Self::SendTx | Self::SendTxBatch => "POST",
            _ => "GET",
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// SYMBOL FORMATTING
// ═══════════════════════════════════════════════════════════════════════════════

/// Format symbol for Lighter
///
/// # Symbol Format
/// - Perpetuals: `ETH` (single asset symbol, quote is USDC)
/// - Spot: `ETH/USDC` (BASE/QUOTE with slash)
///
/// # Examples
/// - Perpetual: `ETH`, `BTC`, `SOL`
/// - Spot: `ETH/USDC`, `BTC/USDC`
pub fn format_symbol(base: &str, quote: &str, account_type: AccountType) -> String {
    match account_type {
        AccountType::Spot | AccountType::Margin => {
            // Spot: BASE/QUOTE with slash
            format!("{}/{}", base.to_uppercase(), quote.to_uppercase())
        }
        AccountType::FuturesCross | AccountType::FuturesIsolated => {
            // Perpetuals: Just base symbol (quote is implied USDC)
            base.to_uppercase()
        }
        _ => {
            // Unsupported account types default to spot format
            format!("{}/{}", base.to_uppercase(), quote.to_uppercase())
        }
    }
}

/// Normalize user input symbol to Lighter format
///
/// # Examples
/// - `BTCUSDC` → `BTC` (for perp) or `BTC/USDC` (for spot)
/// - `ETH-USDC` → `ETH` (for perp) or `ETH/USDC` (for spot)
/// - `eth` → `ETH`
/// - `ETHPERP` → `ETH`
pub fn normalize_symbol(input: &str) -> String {
    let upper = input.to_uppercase();

    // Remove common separators
    let clean = upper.replace(['-', '_'], "");

    // Remove PERP suffix if present
    let clean = if clean.ends_with("PERP") {
        &clean[..clean.len() - 4]
    } else {
        &clean
    };

    // Check if ends with USDC (spot market)
    if clean.ends_with("USDC") && clean.len() > 4 {
        let base = &clean[..clean.len() - 4];
        format!("{}/USDC", base)
    } else {
        clean.to_string()
    }
}

/// Map a symbol base asset to Lighter's numeric market ID.
///
/// Lighter uses numeric market indices for WebSocket channels and REST params:
/// - Perpetuals: 0=ETH, 1=BTC, 2=SOL, etc.
/// - Spot markets start at 2048.
///
/// This is a static mapping derived from actual API data.
pub fn symbol_to_market_id(base: &str) -> Option<u16> {
    // Tolerate both bare ("ETH") and slash-pair ("ETH/USDC") inputs — Lighter
    // exchange_info emits the slash form for Spot symbols, so callers that
    // pass the raw SymbolInfo.symbol back as-is end up here with "ETH/USDC".
    // Strip the quote part before matching against the static market table.
    let coin = base.split('/').next().unwrap_or(base);
    match coin.to_uppercase().as_str() {
        "ETH" => Some(0),
        "BTC" => Some(1),
        "SOL" => Some(2),
        "ARB" => Some(3),
        "OP" => Some(4),
        "DOGE" => Some(5),
        "MATIC" | "POL" => Some(6),
        "AVAX" => Some(7),
        "LINK" => Some(8),
        "SUI" => Some(9),
        "1000PEPE" | "PEPE" => Some(10),
        "WIF" => Some(11),
        "SEI" => Some(12),
        "AAVE" => Some(13),
        "NEAR" => Some(14),
        "WLD" => Some(15),
        "FTM" | "S" => Some(16),
        "BONK" => Some(17),
        "APT" => Some(19),
        "BNB" => Some(25),
        _ => None,
    }
}

/// Map kline interval to Lighter resolution
///
/// # Supported Resolutions
/// - `1m`, `5m`, `15m`, `1h`, `4h`, `1d`
///
/// # Default
/// Returns `1h` for unsupported intervals
pub fn map_kline_interval(interval: &str) -> &'static str {
    match interval {
        "1m" => "1m",
        "5m" => "5m",
        "15m" => "15m",
        "1h" | "60m" => "1h",
        "4h" | "240m" => "4h",
        "1d" | "1D" => "1d",
        _ => "1h", // default
    }
}

/// Map kline interval to Lighter mark price candle resolution.
///
/// `GET /api/v1/markPriceCandles` supports `1m`, `5m`, `15m`, `30m`, `1h`, `4h`, `12h`, `1d`.
/// Returns the nearest supported resolution; defaults to `1h`.
pub fn map_mark_price_kline_interval(interval: &str) -> &'static str {
    match interval {
        "1m" => "1m",
        "5m" => "5m",
        "15m" => "15m",
        "30m" => "30m",
        "1h" | "60m" => "1h",
        "4h" | "240m" => "4h",
        "12h" | "720m" => "12h",
        "1d" | "1D" => "1d",
        _ => "1h",
    }
}

/// Map interval to Lighter funding-rate candle resolution.
///
/// `GET /api/v1/funding-rates` only accepts `1h` or `1d`.
/// Any sub-hourly interval is rounded up to `1h`; anything ≥ 1 day maps to `1d`.
pub fn map_funding_rate_interval(interval: &str) -> &'static str {
    match interval {
        "1d" | "1D" => "1d",
        _ => "1h",
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_normalize_symbol() {
        assert_eq!(normalize_symbol("BTCUSDC"), "BTC/USDC");
        assert_eq!(normalize_symbol("ETH-PERP"), "ETH");
        assert_eq!(normalize_symbol("eth"), "ETH");
        assert_eq!(normalize_symbol("SOL-USDC"), "SOL/USDC");
        assert_eq!(normalize_symbol("ETHUSDC"), "ETH/USDC");
    }

    #[test]
    fn test_format_symbol() {
        assert_eq!(
            format_symbol("ETH", "USDC", AccountType::Spot),
            "ETH/USDC"
        );
        assert_eq!(
            format_symbol("ETH", "USDC", AccountType::FuturesCross),
            "ETH"
        );
    }

    #[test]
    fn test_map_kline_interval() {
        assert_eq!(map_kline_interval("1m"), "1m");
        assert_eq!(map_kline_interval("1h"), "1h");
        assert_eq!(map_kline_interval("1d"), "1d");
        assert_eq!(map_kline_interval("invalid"), "1h");
    }
}