hyperqit 0.1.1

rust sdk for interacting with hyperliquid
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
use log::{debug, error, info};
use std::time::SystemTime;

use alloy::primitives::{Address, FixedBytes};

use crate::errors::{Errors, Result};
use crate::hl::exchange::{
    ExchangeRequest, ExchangeResponse, generate_action_params, generate_transfer_params,
};
use crate::hl::info::{GetInfoReq, PerpetualsInfo, SpotResponse};
use crate::hl::message::SignedMessage;
use crate::hl::nonce::NonceManager;
use crate::hl::user_info::{
    FundingHistory, GetUserFundingHistoryReq, GetUserInfoReq, UserPerpPosition, UserSpotPosition,
};
use crate::hl::utils::*;
use crate::hl::{Actions, TransferRequest};
use crate::{CancelOrder, HyperLiquidSigningHash, Order, OrderRequest, PerpDeployAction, Signers};

pub trait HlAgentWallet {
    async fn sign_order(&self, to_sign: FixedBytes<32>) -> Result<SignedMessage>;
}

pub struct HyperliquidClient {
    client: reqwest::Client,
    signer: Signers,
    network: Network,
    user: Address,
    nonce_manager: NonceManager,
}

impl HyperliquidClient {
    pub fn new(network: Network, signer: Signers, user: Address) -> Self {
        info!("creating hyperliquid client for {} on {:?}", user, network);
        HyperliquidClient {
            client: reqwest::Client::new(),
            signer,
            network,
            user,
            nonce_manager: NonceManager::new(),
        }
    }

    pub async fn get_user_funding_history(&self, since: u128) -> Result<FundingHistory> {
        debug!(
            "fetching funding history for user {} since {}",
            self.user, since
        );

        let end_time = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)?
            .as_millis();

        let req = GetUserFundingHistoryReq {
            request_type: "userFunding".into(),
            user: self.user.to_string(),
            end_time,
            start_time: end_time - since,
        };

        let resp = self
            .client
            .post(format!("{}/info", Into::<String>::into(self.network)))
            .header("Content-Type", "application/json")
            .json(&req)
            .send()
            .await?;

        let status_code = resp.status().as_u16();
        let body = resp.text().await?;
        if status_code != 200 {
            error!("failed to get funding history: {} - {}", status_code, body);
            return Err(Errors::HyperLiquidApiError(status_code, body).into());
        }

        let out: FundingHistory = serde_json::from_str(body.as_str())?;
        debug!("retrieved funding history with {} entries", out.len());
        Ok(out)
    }

    pub async fn update_leverage(&self, a: u32, is_cross: bool, leverage: u32) -> Result<()> {
        info!(
            "updating leverage for asset {} to {}x (cross: {})",
            a, leverage, is_cross
        );

        let nonce = self.nonce_manager.get_next_nonce();

        let action: Actions = Actions::UpdateLeverage(crate::UpdateLeverage {
            asset: a,
            is_cross,
            leverage,
        });

        let is_mainnet = self.network == Network::Mainnet;
        let (to_sign, domain) = generate_action_params(&action, is_mainnet, nonce)?;

        let hash = to_sign.hyperliquid_signing_hash(&domain);

        let signature = self.signer.sign_order(hash).await?;

        let payload = ExchangeRequest {
            action: serde_json::to_value(action)?,
            signature,
            nonce,
        };

        debug!(
            "update leverage payload: {}",
            serde_json::to_string(&payload).unwrap()
        );

        let resp = self
            .client
            .post(format!("{}/exchange", Into::<String>::into(self.network)))
            .json(&payload)
            .send()
            .await?;

        let status_code = resp.status().as_u16();
        let body = resp.text().await?;
        if status_code != 200 {
            error!("failed to update leverage: {} - {}", status_code, body);
            return Err(Errors::HyperLiquidApiError(status_code, body).into());
        }

        let out: ExchangeResponse = serde_json::from_str(body.as_str())?;
        debug!("leverage update response: {:?}", out);
        info!("successfully updated leverage for asset {}", a);
        Ok(())
    }

    pub async fn create_position_with_size_in_usd(
        &self,
        a: u32,
        is_perp: bool,
        is_buy: bool,
        current_px: f64,
        sz: f64,
        reduce_only: bool,
        slippage: f64,
        sz_decimals: i32,
    ) -> Result<()> {
        info!(
            "creating {} position for asset {} with ${} USD (price: {}, slippage: {}%)",
            if is_buy { "buy" } else { "sell" },
            a,
            sz,
            current_px,
            slippage * 100.0
        );

        let (px, sz) = get_formatted_position_with_amount(
            current_px,
            sz,
            is_perp,
            is_buy,
            sz_decimals,
            slippage,
        );

        self.create_position(a, is_buy, px, sz, reduce_only).await?;
        Ok(())
    }

    pub async fn create_position_with_size(
        &self,
        a: u32,
        is_perp: bool,
        is_buy: bool,
        current_px: f64,
        sz: f64,
        reduce_only: bool,
        slippage: f64,
        sz_decimals: i32,
    ) -> Result<()> {
        info!(
            "creating {} position for asset {} with size {} (price: {}, slippage: {}%)",
            if is_buy { "buy" } else { "sell" },
            a,
            sz,
            current_px,
            slippage * 100.0
        );

        let (px, sz) = get_formatted_position_with_amount_raw(
            current_px,
            sz,
            is_perp,
            is_buy,
            sz_decimals,
            slippage,
        );

        self.create_position(a, is_buy, px, sz, reduce_only).await?;
        Ok(())
    }

    async fn create_position(
        &self,
        a: u32,
        is_buy: bool,
        px: String,
        sz: String,
        reduce_only: bool,
    ) -> Result<()> {
        let nonce = self.nonce_manager.get_next_nonce();

        let action: Actions = Actions::Order(crate::BulkOrder {
            orders: vec![OrderRequest {
                asset: a,
                is_buy,
                limit_px: px.clone(),
                sz: sz.clone(),
                reduce_only,
                order_type: Order::Limit(crate::Limit { tif: "Ioc".into() }),
                cloid: None,
            }],
            grouping: "na".to_string(),
        });

        let is_mainnet = self.network == Network::Mainnet;
        let (to_sign, domain) = generate_action_params(&action, is_mainnet, nonce)?;
        let hash = to_sign.hyperliquid_signing_hash(&domain);
        let signature = self.signer.sign_order(hash).await?;

        let payload = ExchangeRequest {
            action: serde_json::to_value(action)?,
            signature,
            nonce,
        };

        debug!(
            "order payload: {}",
            serde_json::to_string(&payload).unwrap()
        );

        let resp = self
            .client
            .post(format!("{}/exchange", Into::<String>::into(self.network)))
            .json(&payload)
            .send()
            .await?;

        let status_code = resp.status().as_u16();
        let body = resp.text().await?;
        if status_code != 200 {
            error!("failed to create position: {} - {}", status_code, body);
            return Err(Errors::HyperLiquidApiError(status_code, body).into());
        }

        let out: ExchangeResponse = serde_json::from_str(body.as_str())?;
        info!("order response: {:?}", out);
        info!(
            "successfully placed {} order for asset {} (px: {}, sz: {})",
            if is_buy { "buy" } else { "sell" },
            a,
            px,
            sz
        );
        Ok(())
    }

    pub async fn transfer_usd_to_spot(&self, amount: u64) -> Result<()> {
        info!("transferring ${} USD to spot", amount);

        let nonce = self.nonce_manager.get_next_nonce();

        let transfer_req = TransferRequest {
            chain: self.network.name(),
            sig_chain_id: "0xa4b1".to_string(),
            amount: amount.to_string(),
            to_perp: false,
            nonce: nonce,
        };

        debug!("transfer request: {:?}", transfer_req);

        let (to_sign, domain) = generate_transfer_params(&transfer_req)?;
        debug!("transfer domain: {:?}", domain);

        let hash = to_sign.hyperliquid_signing_hash(&domain);
        let signature = self.signer.sign_order(hash).await?;

        let payload = ExchangeRequest {
            nonce,
            signature,
            action: serde_json::to_value(Actions::UsdClassTransfer(transfer_req))?,
        };

        debug!(
            "transfer payload: {}",
            serde_json::to_string(&payload).unwrap()
        );

        let resp = self
            .client
            .post(format!("{}/exchange", Into::<String>::into(self.network)))
            .json(&payload)
            .send()
            .await?;

        let status_code = resp.status().as_u16();
        let body = resp.text().await?;
        if status_code != 200 {
            error!("failed to transfer USD: {} - {}", status_code, body);
            return Err(Errors::HyperLiquidApiError(status_code, body).into());
        }

        let out: ExchangeResponse = serde_json::from_str(body.as_str())?;
        debug!("transfer response: {:?}", out);
        info!("successfully transferred ${} USD to spot", amount);
        Ok(())
    }

    pub async fn get_perp_info(&self) -> Result<PerpetualsInfo> {
        debug!("fetching perpetuals info");

        let payload = GetInfoReq {
            asset_type: "metaAndAssetCtxs".into(),
        };

        let resp = self
            .client
            .post(format!("{}/info", Into::<String>::into(self.network)))
            .header("Content-Type", "application/json")
            .json(&payload)
            .send()
            .await?;

        let status_code = resp.status().as_u16();
        let body = resp.text().await?;
        if status_code != 200 {
            error!("failed to get perp info: {} - {}", status_code, body);
            return Err(Errors::HyperLiquidApiError(status_code, body).into());
        }

        let out: PerpetualsInfo = serde_json::from_str(body.as_str())?;
        Ok(out)
    }

    pub async fn get_spot_info(&self) -> Result<SpotResponse> {
        debug!("fetching spot info");

        let payload = GetInfoReq {
            asset_type: "spotMetaAndAssetCtxs".into(),
        };

        let resp = self
            .client
            .post(format!("{}/info", Into::<String>::into(self.network)))
            .header("Content-Type", "application/json")
            .json(&payload)
            .send()
            .await?;

        let status_code = resp.status().as_u16();
        let body = resp.text().await?;
        if status_code != 200 {
            error!("failed to get spot info: {} - {}", status_code, body);
            return Err(Errors::HyperLiquidApiError(status_code, body).into());
        }

        let out: SpotResponse = serde_json::from_str(body.as_str())?;
        Ok(out)
    }

    pub async fn get_user_spot_info(&self) -> Result<UserSpotPosition> {
        debug!("fetching user spot positions for {}", self.user);

        let payload = GetUserInfoReq {
            request_type: "spotClearinghouseState".into(),
            user: self.user.to_string(),
        };

        let resp = self
            .client
            .post(format!("{}/info", Into::<String>::into(self.network)))
            .header("Content-Type", "application/json")
            .json(&payload)
            .send()
            .await?;

        let status_code = resp.status().as_u16();
        let body = resp.text().await?;
        if status_code != 200 {
            error!("failed to get user spot info: {} - {}", status_code, body);
            return Err(Errors::HyperLiquidApiError(status_code, body).into());
        }

        debug!("user spot response: {}", body);
        let out: UserSpotPosition = serde_json::from_str(body.as_str())?;
        debug!("retrieved spot positions for user {}", self.user);
        Ok(out)
    }

    pub async fn get_user_perp_info(&self) -> Result<UserPerpPosition> {
        debug!("fetching user perp positions for {}", self.user);

        let payload = GetUserInfoReq {
            request_type: "clearinghouseState".into(),
            user: self.user.to_string(),
        };

        let resp = self
            .client
            .post(format!("{}/info", Into::<String>::into(self.network)))
            .header("Content-Type", "application/json")
            .json(&payload)
            .send()
            .await?;

        let status_code = resp.status().as_u16();
        let body = resp.text().await?;
        if status_code != 200 {
            error!("failed to get user perp info: {} - {}", status_code, body);
            return Err(Errors::HyperLiquidApiError(status_code, body).into());
        }

        let out: UserPerpPosition = serde_json::from_str(body.as_str())?;
        debug!("retrieved perp positions for user {}", self.user);
        Ok(out)
    }

    pub async fn cancel_order(&self, oid: i64, a: u32) -> Result<()> {
        info!("cancelling order {} for asset {}", oid, a);

        let nonce = self.nonce_manager.get_next_nonce();

        let action: Actions = Actions::Cancel(crate::BulkCancel {
            cancels: vec![CancelOrder { asset: a, oid }],
        });

        let is_mainnet = self.network == Network::Mainnet;
        let (to_sign, domain) = generate_action_params(&action, is_mainnet, nonce)?;
        let hash = to_sign.hyperliquid_signing_hash(&domain);
        let signature = self.signer.sign_order(hash).await?;

        let payload = ExchangeRequest {
            action: serde_json::to_value(action)?,
            signature,
            nonce,
        };

        debug!(
            "cancel order payload: {}",
            serde_json::to_string(&payload).unwrap()
        );

        let resp = self
            .client
            .post(format!("{}/exchange", Into::<String>::into(self.network)))
            .json(&payload)
            .send()
            .await?;

        let status_code = resp.status().as_u16();
        let body = resp.text().await?;
        if status_code != 200 {
            error!("failed to cancel order: {} - {}", status_code, body);
            return Err(Errors::HyperLiquidApiError(status_code, body).into());
        }

        let out: ExchangeResponse = serde_json::from_str(body.as_str())?;
        debug!("cancel order response: {:?}", out);
        info!("successfully cancelled order {} for asset {}", oid, a);
        Ok(())
    }

    pub async fn perp_deploy_action(&self, deploy_params: PerpDeployAction) -> Result<()> {
        debug!("creating perp deploy action {:?}", deploy_params.clone());

        let nonce = self.nonce_manager.get_next_nonce();

        let action: Actions = Actions::PerpDeploy(deploy_params.clone());

        let is_mainnet = self.network == Network::Mainnet;
        let (to_sign, domain) = generate_action_params(&action, is_mainnet, nonce)?;
        let hash = to_sign.hyperliquid_signing_hash(&domain);
        let signature = self.signer.sign_order(hash).await?;

        let payload = ExchangeRequest {
            action: serde_json::to_value(action)?,
            signature,
            nonce,
        };

        debug!(
            "perp deploy action: {}",
            serde_json::to_string(&payload).unwrap()
        );

        let resp = self
            .client
            .post(format!("{}/exchange", Into::<String>::into(self.network)))
            .json(&payload)
            .send()
            .await?;

        let status_code = resp.status().as_u16();
        let body = resp.text().await?;
        if status_code != 200 {
            error!(
                "failed to call perp deploy action: {} - {}",
                status_code, body
            );
            return Err(Errors::HyperLiquidApiError(status_code, body).into());
        }

        let out: ExchangeResponse = serde_json::from_str(body.as_str())?;
        debug!("perp deploy action response: {:?}", out);
        Ok(())
    }
}