maxt 0.2.1

One Rust API for Upbit, Bithumb, Binance, and Hyperliquid market data, accounts, and orders.
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
//! Hyperliquid-specific data exposed by [`HyperliquidAdapter`].

use rust_decimal::Decimal;
use serde_json::Value;

use crate::error::{Error, Result};
use crate::types::{Deposit, DepositStatus, Timestamp, Withdrawal, WithdrawalStatus};

use super::parse::{self, RawAssetCtx, RawLedgerUpdate};

/// One account-wide entry from Hyperliquid's non-funding ledger.
///
/// These entries describe deposits, withdrawals, transfers, and liquidations;
/// they are not market-scoped [`FundingPayment`](crate::FundingPayment) records.
///
/// Fields not supplied for an entry kind are `None`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct HyperliquidLedgerEntry {
    /// What kind of movement this was.
    pub kind: HyperliquidLedgerKind,
    /// When Hyperliquid recorded it.
    pub time: Timestamp,
    /// The on-chain transaction hash.
    pub hash: String,
    /// The asset that moved, uppercase. Spot transfers name their token;
    /// other amount-bearing entries use `USDC`.
    pub asset: Option<String>,
    /// How much moved, **unsigned**.
    ///
    /// Direction is represented by [`HyperliquidLedgerEntry::kind`], not by the
    /// sign of this value.
    pub amount: Option<Decimal>,
    /// The fee charged on top, when the kind has one.
    pub fee: Option<Decimal>,
    /// The other address, for the kinds that move funds between two of them.
    pub counterparty: Option<String>,
}

/// What kind of movement a [`HyperliquidLedgerEntry`] records.
///
/// Unrecognized wire values are preserved by
/// [`HyperliquidLedgerKind::Other`].
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum HyperliquidLedgerKind {
    /// USDC arrived from the bridge.
    Deposit,
    /// USDC left over the bridge.
    Withdraw,
    /// USDC moved to another Hyperliquid address.
    InternalTransfer,
    /// USDC moved between this account and one of its subaccounts.
    SubAccountTransfer,
    /// A spot token moved to another Hyperliquid address.
    SpotTransfer,
    /// USDC moved between the spot wallet and the perpetual wallet.
    AccountClassTransfer,
    /// USDC went into a vault.
    VaultDeposit,
    /// USDC came out of a vault.
    VaultWithdraw,
    /// A vault paid out profits.
    VaultDistribution,
    /// A position was closed by the liquidation engine.
    Liquidation,
    /// A kind this release does not name, under Hyperliquid's own spelling.
    Other(String),
}

impl HyperliquidLedgerKind {
    fn from_name(name: &str) -> Self {
        match name {
            "deposit" => Self::Deposit,
            "withdraw" => Self::Withdraw,
            "internalTransfer" => Self::InternalTransfer,
            "subAccountTransfer" => Self::SubAccountTransfer,
            "spotTransfer" => Self::SpotTransfer,
            "accountClassTransfer" => Self::AccountClassTransfer,
            "vaultDeposit" => Self::VaultDeposit,
            "vaultWithdraw" => Self::VaultWithdraw,
            "vaultDistribution" => Self::VaultDistribution,
            "liquidation" | "ledgerLiquidation" => Self::Liquidation,
            other => Self::Other(other.to_string()),
        }
    }
}

/// Hyperliquid's current context and order precision for one market.
///
/// [`HyperliquidAssetContext::funding_rate`] is the provider's current market
/// rate. [`FundingRate`](crate::FundingRate) contains historical market-rate
/// observations, while [`FundingPayment`](crate::FundingPayment) contains
/// amounts actually charged or credited to an account.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct HyperliquidAssetContext {
    /// The provider's mid price, or `None` when unavailable.
    pub mid_price: Option<Decimal>,
    /// The provider's mark price.
    pub mark_price: Option<Decimal>,
    /// The provider's oracle price. Perpetual markets only.
    pub oracle_price: Option<Decimal>,
    /// The current funding rate as a signed ratio.
    ///
    /// Perpetual markets only; `None` on spot, which pays no funding.
    pub funding_rate: Option<Decimal>,
    /// Open interest in the base asset. Perpetual markets only.
    pub open_interest: Option<Decimal>,
    /// Maximum decimal places accepted for order size.
    ///
    /// Finer sizes are rejected locally before signing.
    pub size_decimals: u32,
    /// Maximum decimal places accepted for a fractional order price.
    ///
    /// This is `6 - size_decimals` for perpetuals and `8 - size_decimals` for
    /// spot. Fractional prices are also limited to five significant digits;
    /// integer prices are exempt from the significant-digit limit.
    pub price_decimals: u32,
}

/// Reads a page of non-funding ledger entries.
pub(crate) fn ledger_entries(raw: &[RawLedgerUpdate]) -> Result<Vec<HyperliquidLedgerEntry>> {
    raw.iter().map(ledger_entry).collect()
}

fn ledger_entry(raw: &RawLedgerUpdate) -> Result<HyperliquidLedgerEntry> {
    let name = kind_name(raw);

    // Spot transfers use `token`/`amount`; other amount-bearing entries use
    // `USDC`/`usdc`. Liquidations carry neither amount field.
    let (asset, amount_field) = match text(&raw.delta, "token") {
        Some(token) => (token.to_ascii_uppercase(), "amount"),
        None => (parse::SETTLE_ASSET.to_string(), "usdc"),
    };
    let amount = decimal_field(&raw.delta, amount_field)?.map(|value| value.abs());

    Ok(HyperliquidLedgerEntry {
        kind: HyperliquidLedgerKind::from_name(name),
        time: parse::millis(raw.time, "time")?,
        hash: raw.hash.clone(),
        asset: amount.map(|_| asset),
        amount,
        fee: decimal_field(&raw.delta, "fee")?,
        counterparty: text(&raw.delta, "destination").map(str::to_string),
    })
}

/// Maps credited bridge deposits into the common transfer history model.
pub(crate) fn deposits(raw: &[RawLedgerUpdate]) -> Result<Vec<(Deposit, i64)>> {
    raw.iter()
        .filter(|entry| kind_name(entry) == "deposit")
        .map(|entry| {
            let hash = entry.hash.clone();
            Ok((
                Deposit {
                    id: hash.clone(),
                    asset: parse::SETTLE_ASSET.to_string(),
                    // The ledger event does not identify the source bridge.
                    network: None,
                    provider_network: None,
                    amount: required_decimal(&entry.delta, "usdc")?.abs(),
                    // Hyperliquid publishes neither a generated address nor memo.
                    address: None,
                    memo: None,
                    // `deposit` is an event kind, not an explicit lifecycle status.
                    status: DepositStatus::Unknown,
                    provider_status: "deposit".to_string(),
                    tx_id: Some(hash),
                    created_at: Some(parse::millis(entry.time, "time")?),
                },
                entry.time,
            ))
        })
        .collect()
}

/// Maps bridge withdrawals into the common transfer history model.
pub(crate) fn withdrawals(raw: &[RawLedgerUpdate]) -> Result<Vec<(Withdrawal, i64)>> {
    raw.iter()
        .filter(|entry| kind_name(entry) == "withdraw")
        .map(|entry| {
            let hash = entry.hash.clone();
            Ok((
                Withdrawal {
                    id: hash.clone(),
                    asset: parse::SETTLE_ASSET.to_string(),
                    // The ledger event omits both bridge network and destination.
                    network: None,
                    provider_network: None,
                    amount: required_decimal(&entry.delta, "usdc")?.abs(),
                    fee: decimal_field(&entry.delta, "fee")?,
                    destination: None,
                    // `withdraw` does not prove that the bridge finalized.
                    status: WithdrawalStatus::Unknown,
                    provider_status: "withdraw".to_string(),
                    tx_id: Some(hash),
                    created_at: Some(parse::millis(entry.time, "time")?),
                },
                entry.time,
            ))
        })
        .collect()
}

fn kind_name(raw: &RawLedgerUpdate) -> &str {
    raw.delta
        .get("type")
        .and_then(Value::as_str)
        .unwrap_or("unknown")
}

fn text<'a>(delta: &'a Value, field: &str) -> Option<&'a str> {
    delta.get(field).and_then(Value::as_str)
}

fn required_decimal(delta: &Value, field: &'static str) -> Result<Decimal> {
    decimal_field(delta, field)?
        .ok_or_else(|| Error::decode(format!("Hyperliquid ledger delta has no `{field}`")))
}

fn decimal_field(delta: &Value, field: &'static str) -> Result<Option<Decimal>> {
    match delta.get(field) {
        None | Some(Value::Null) => Ok(None),
        Some(Value::String(value)) => parse::decimal(value, field).map(Some),
        Some(Value::Number(value)) => parse::decimal(&value.to_string(), field).map(Some),
        Some(other) => Err(Error::decode(format!(
            "Hyperliquid ledger `{field}` is not a number: {other}"
        ))),
    }
}

/// Reads the current context of one market.
pub(crate) fn asset_context(
    raw: &RawAssetCtx,
    asset: &parse::Asset,
) -> Result<HyperliquidAssetContext> {
    let optional = |value: Option<&str>, field: &'static str| {
        value.map(|value| parse::decimal(value, field)).transpose()
    };

    Ok(HyperliquidAssetContext {
        size_decimals: asset.size_decimals,
        price_decimals: asset.price_decimals(),
        mid_price: optional(raw.mid_px.as_deref(), "midPx")?,
        mark_price: optional(raw.mark_px.as_deref(), "markPx")?,
        oracle_price: optional(raw.oracle_px.as_deref(), "oraclePx")?,
        funding_rate: optional(raw.funding.as_deref(), "funding")?,
        open_interest: optional(raw.open_interest.as_deref(), "openInterest")?,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{Exchange, Market, MarketStatus};

    // https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#retrieve-a-users-funding-history-or-non-funding-ledger-updates
    const LEDGER: &str = r#"[
      {
        "delta": {"type": "deposit", "usdc": "1000.0"},
        "hash": "0x0000000000000000000000000000000000000000000000000000000000000001",
        "time": 1681222254710
      },
      {
        "delta": {
          "type": "withdraw",
          "usdc": "250.0",
          "nonce": 1681222254711,
          "fee": "1.0"
        },
        "hash": "0x0000000000000000000000000000000000000000000000000000000000000002",
        "time": 1681222354710
      },
      {
        "delta": {
          "type": "spotTransfer",
          "token": "PURR",
          "amount": "12.5",
          "usdcValue": "3.75",
          "user": "0x14791697260e4c9a71f18484c9f997b308e59325",
          "destination": "0x0000000000000000000000000000000000000009",
          "fee": "0.0"
        },
        "hash": "0x0000000000000000000000000000000000000000000000000000000000000003",
        "time": 1681222454710
      },
      {
        "delta": {
          "type": "liquidation",
          "accountValue": "12.0",
          "leverage": 20.0,
          "liquidatedPositions": [{"coin": "ETH", "szi": "-0.5"}]
        },
        "hash": "0x0000000000000000000000000000000000000000000000000000000000000004",
        "time": 1681222554710
      },
      {
        "delta": {"type": "somethingHyperliquidAddedLater", "usdc": "1.0"},
        "hash": "0x0000000000000000000000000000000000000000000000000000000000000005",
        "time": 1681222654710
      }
    ]"#;

    fn entries() -> Vec<HyperliquidLedgerEntry> {
        let raw: Vec<RawLedgerUpdate> =
            parse::json(LEDGER).expect("official ledger updates payload");

        ledger_entries(&raw).expect("a page of entries")
    }

    #[test]
    fn each_kind_of_cash_movement_keeps_its_own_meaning() {
        let entries = entries();

        assert_eq!(entries[0].kind, HyperliquidLedgerKind::Deposit);
        assert_eq!(entries[0].amount, Some(Decimal::from(1_000)));
        assert_eq!(entries[0].asset.as_deref(), Some("USDC"));
        assert_eq!(entries[0].fee, None);
        assert_eq!(entries[0].time, Timestamp::from_millis(1_681_222_254_710));

        // Direction is encoded by the kind; amount remains a magnitude.
        assert_eq!(entries[1].kind, HyperliquidLedgerKind::Withdraw);
        assert_eq!(entries[1].amount, Some(Decimal::from(250)));
        assert_eq!(entries[1].fee, Some(Decimal::ONE));
    }

    #[test]
    fn bridge_events_map_without_inventing_network_destination_or_status() {
        let raw: Vec<RawLedgerUpdate> = parse::json(LEDGER).expect("official ledger payload");
        let deposits = deposits(&raw).expect("deposit history");
        let withdrawals = withdrawals(&raw).expect("withdrawal history");

        let deposit = &deposits[0].0;
        assert_eq!(deposit.asset, "USDC");
        assert_eq!(deposit.amount, Decimal::from(1_000));
        assert_eq!(deposit.network, None);
        assert_eq!(deposit.provider_network, None);
        assert_eq!(deposit.address, None);
        assert_eq!(deposit.status, DepositStatus::Unknown);
        assert_eq!(deposit.provider_status, "deposit");
        assert_eq!(deposit.tx_id.as_deref(), Some(deposit.id.as_str()));

        let withdrawal = &withdrawals[0].0;
        assert_eq!(withdrawal.asset, "USDC");
        assert_eq!(withdrawal.amount, Decimal::from(250));
        assert_eq!(withdrawal.fee, Some(Decimal::ONE));
        assert_eq!(withdrawal.network, None);
        assert_eq!(withdrawal.provider_network, None);
        assert_eq!(withdrawal.destination, None);
        assert_eq!(withdrawal.status, WithdrawalStatus::Unknown);
        assert_eq!(withdrawal.provider_status, "withdraw");
        assert_eq!(withdrawal.tx_id.as_deref(), Some(withdrawal.id.as_str()));
    }

    #[test]
    fn numeric_ledger_amounts_are_read_without_float_round_trips() {
        let raw: Vec<RawLedgerUpdate> = parse::json(
            r#"[{
              "delta": {"type": "deposit", "usdc": 0.125},
              "hash": "0x01",
              "time": 1681222254710
            }]"#,
        )
        .expect("numeric ledger payload");

        assert_eq!(
            deposits(&raw).expect("deposit")[0].0.amount,
            Decimal::new(125, 3)
        );
    }

    #[test]
    fn a_spot_transfer_names_its_token_rather_than_assuming_usdc() {
        let entries = entries();

        assert_eq!(entries[2].kind, HyperliquidLedgerKind::SpotTransfer);
        assert_eq!(entries[2].asset.as_deref(), Some("PURR"));
        assert_eq!(entries[2].amount, Some(Decimal::new(125, 1)));
        assert_eq!(
            entries[2].counterparty.as_deref(),
            Some("0x0000000000000000000000000000000000000009")
        );
    }

    #[test]
    fn a_liquidation_has_no_single_amount_and_does_not_invent_one() {
        let entries = entries();

        assert_eq!(entries[3].kind, HyperliquidLedgerKind::Liquidation);
        assert_eq!(entries[3].amount, None);
        assert_eq!(entries[3].asset, None);
        assert!(entries[3].hash.ends_with("04"));
    }

    #[test]
    fn a_kind_this_release_does_not_know_arrives_named_rather_than_dropped() {
        let entries = entries();

        assert_eq!(
            entries[4].kind,
            HyperliquidLedgerKind::Other("somethingHyperliquidAddedLater".to_string())
        );
        assert_eq!(entries[4].amount, Some(Decimal::ONE));
    }

    #[test]
    fn an_asset_context_carries_the_numbers_the_common_api_has_no_field_for() {
        // `activeAssetCtx` context payload.
        // https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/websocket/subscriptions
        let body = r#"{
          "dayNtlVlm": "1169046.29406",
          "funding": "0.0000125",
          "markPx": "14.3161",
          "midPx": "14.314",
          "openInterest": "688.11",
          "oraclePx": "14.325",
          "prevDayPx": "15.322"
        }"#;
        let raw: RawAssetCtx = parse::json(body).expect("official asset context payload");
        // Order precision comes from market metadata, not the context payload.
        let asset = parse::Asset {
            market: Market::perpetual(Exchange::Hyperliquid, "HYPE", "USDC"),
            native: "HYPE".to_string(),
            asset_id: 0,
            size_decimals: 2,
            max_leverage: Some(3),
            only_isolated: false,
            status: MarketStatus::Active,
        };
        let context = asset_context(&raw, &asset).expect("a context");

        // Perpetual price decimals are `6 - size_decimals`.
        assert_eq!(context.size_decimals, 2);
        assert_eq!(context.price_decimals, 4);
        assert_eq!(context.funding_rate, Some(Decimal::new(125, 7)));
        assert_eq!(context.open_interest, Some(Decimal::new(68_811, 2)));
        assert_eq!(context.oracle_price, Some(Decimal::new(14_325, 3)));
        assert_eq!(context.mark_price, Some(Decimal::new(143_161, 4)));
        assert_eq!(context.mid_price, Some(Decimal::new(14_314, 3)));
    }
}