hyperliquid-sdk-rs 0.1.2

High-performance Rust SDK for Hyperliquid Protocol
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
//! Managed exchange provider with safety features and optimizations.

use std::sync::Arc;

use alloy::primitives::Address;
use tokio::sync::Mutex as TokioMutex;

use crate::{
    constants::Network,
    errors::HyperliquidError,
    providers::{
        agent::{AgentConfig, AgentManager, AgentWallet},
        batcher::{BatchConfig, OrderBatcher, OrderHandle},
        nonce::NonceManager,
    },
    signers::HyperliquidSigner,
    types::{
        requests::{CancelRequest, OrderRequest},
        responses::ExchangeResponseStatus,
    },
};

use super::RawExchangeProvider;

type Result<T> = std::result::Result<T, HyperliquidError>;

/// Configuration for managed exchange provider.
#[derive(Clone, Debug)]
pub struct ManagedExchangeConfig {
    /// Enable automatic order batching
    pub batch_orders: bool,
    /// Batch configuration
    pub batch_config: BatchConfig,

    /// Agent lifecycle management
    pub auto_rotate_agents: bool,
    /// Agent configuration
    pub agent_config: AgentConfig,

    /// Nonce isolation per subaccount
    pub isolate_subaccount_nonces: bool,

    /// Safety features
    pub prevent_agent_address_queries: bool,
    pub warn_on_high_nonce_velocity: bool,
}

impl Default for ManagedExchangeConfig {
    fn default() -> Self {
        Self {
            batch_orders: false,
            batch_config: BatchConfig::default(),
            auto_rotate_agents: true,
            agent_config: AgentConfig::default(),
            isolate_subaccount_nonces: true,
            prevent_agent_address_queries: true,
            warn_on_high_nonce_velocity: true,
        }
    }
}

/// Managed exchange provider with safety features and optimizations.
///
/// This provider wraps `RawExchangeProvider` and adds:
/// - Automatic agent rotation for security
/// - Order batching for performance
/// - Nonce management for correctness
///
/// # Example
/// ```ignore
/// let provider = ManagedExchangeProvider::builder(signer)
///     .with_network(Network::Mainnet)
///     .with_auto_batching(Duration::from_millis(100))
///     .build()
///     .await?;
/// ```
pub struct ManagedExchangeProvider<S: HyperliquidSigner> {
    /// Inner raw provider
    inner: Arc<RawExchangeProvider<S>>,

    /// Agent manager for lifecycle
    agent_manager: Option<Arc<AgentManager<S>>>,

    /// Nonce tracking
    nonce_manager: Arc<NonceManager>,

    /// Order batching
    batcher: Option<Arc<OrderBatcher>>,
    batcher_handle: Option<Arc<TokioMutex<Option<tokio::task::JoinHandle<()>>>>>,

    /// Configuration
    config: ManagedExchangeConfig,
}

impl<S: HyperliquidSigner + Clone + 'static> ManagedExchangeProvider<S> {
    /// Create a builder for managed provider.
    pub fn builder(signer: S) -> ManagedExchangeProviderBuilder<S> {
        ManagedExchangeProviderBuilder::new(signer)
    }

    /// Create with default configuration for mainnet.
    pub async fn mainnet(signer: S) -> Result<Arc<Self>> {
        Self::builder(signer)
            .with_network(Network::Mainnet)
            .build()
            .await
    }

    /// Create with default configuration for testnet.
    pub async fn testnet(signer: S) -> Result<Arc<Self>> {
        Self::builder(signer)
            .with_network(Network::Testnet)
            .build()
            .await
    }

    /// Place an order with all managed features.
    pub async fn place_order(&self, order: &OrderRequest) -> Result<OrderHandle> {
        // Get nonce based on configuration
        let nonce = if self.config.auto_rotate_agents {
            if let Some(agent_mgr) = &self.agent_manager {
                let agent = agent_mgr.get_or_rotate_agent("default").await?;
                // Use agent's nonce
                agent.next_nonce()
            } else {
                // Fallback to regular nonce
                self.nonce_manager.next_nonce(None)
            }
        } else {
            // Not using agents, use regular nonce
            if self.config.isolate_subaccount_nonces {
                // For subaccounts, we'd need to extract the address from somewhere
                // For now, just use global nonce
                self.nonce_manager.next_nonce(None)
            } else {
                self.nonce_manager.next_nonce(None)
            }
        };

        // Check nonce validity
        if !NonceManager::is_valid_nonce(nonce) {
            return Err(HyperliquidError::InvalidRequest(
                "Generated nonce is outside valid time bounds".to_string(),
            ));
        }

        // For now, we always use the main provider
        // In a full implementation, we'd need to handle agent signing differently
        // This is a limitation of the current design where we can't easily swap signers

        // Batch or direct execution
        if self.config.batch_orders {
            if let Some(batcher) = &self.batcher {
                Ok(batcher.add_order(order.clone(), nonce).await)
            } else {
                // Fallback to direct
                let result = self.inner.place_order(order).await?;
                Ok(OrderHandle::Immediate(Ok(result)))
            }
        } else {
            // Direct execution
            let result = self.inner.place_order(order).await?;
            Ok(OrderHandle::Immediate(Ok(result)))
        }
    }

    /// Place order immediately, bypassing batch.
    pub async fn place_order_immediate(
        &self,
        order: &OrderRequest,
    ) -> Result<ExchangeResponseStatus> {
        self.inner.place_order(order).await
    }

    /// Access the raw provider for advanced usage.
    pub fn raw(&self) -> &RawExchangeProvider<S> {
        &self.inner
    }

    /// Get current agent status.
    pub async fn get_agent_status(&self) -> Option<Vec<(String, AgentWallet)>> {
        if let Some(agent_mgr) = &self.agent_manager {
            Some(agent_mgr.get_active_agents().await)
        } else {
            None
        }
    }

    /// Shutdown the managed provider cleanly.
    pub async fn shutdown(self: Arc<Self>) {
        // Stop batcher if running
        if let Some(handle_mutex) = &self.batcher_handle {
            if let Some(handle) = handle_mutex.lock().await.take() {
                handle.abort();
            }
        }
    }
}

/// Builder for ManagedExchangeProvider.
pub struct ManagedExchangeProviderBuilder<S: HyperliquidSigner> {
    signer: S,
    network: Network,
    config: ManagedExchangeConfig,
    vault_address: Option<Address>,
    initial_agent: Option<String>,
    builder_address: Option<Address>,
}

impl<S: HyperliquidSigner + Clone + 'static> ManagedExchangeProviderBuilder<S> {
    fn new(signer: S) -> Self {
        Self {
            signer,
            network: Network::Mainnet,
            config: ManagedExchangeConfig::default(),
            vault_address: None,
            initial_agent: None,
            builder_address: None,
        }
    }

    /// Set network.
    pub fn with_network(mut self, network: Network) -> Self {
        self.network = network;
        self
    }

    /// Enable automatic order batching.
    pub fn with_auto_batching(mut self, interval: std::time::Duration) -> Self {
        self.config.batch_orders = true;
        self.config.batch_config.interval = interval;
        self
    }

    /// Configure agent rotation.
    pub fn with_agent_rotation(mut self, ttl: std::time::Duration) -> Self {
        self.config.auto_rotate_agents = true;
        self.config.agent_config.ttl = ttl;
        self
    }

    /// Start with an agent.
    pub fn with_agent(mut self, name: Option<String>) -> Self {
        self.initial_agent = name;
        self.config.auto_rotate_agents = true;
        self
    }

    /// Set vault address.
    pub fn with_vault(mut self, vault: Address) -> Self {
        self.vault_address = Some(vault);
        self
    }

    /// Set builder address.
    pub fn with_builder(mut self, builder: Address) -> Self {
        self.builder_address = Some(builder);
        self
    }

    /// Disable agent rotation.
    pub fn without_agent_rotation(mut self) -> Self {
        self.config.auto_rotate_agents = false;
        self
    }

    /// Build the provider.
    pub async fn build(self) -> Result<Arc<ManagedExchangeProvider<S>>> {
        // Create raw provider
        let raw = match self.network {
            Network::Mainnet => {
                if let Some(vault) = self.vault_address {
                    RawExchangeProvider::mainnet_vault(self.signer.clone(), vault)
                } else if let Some(builder) = self.builder_address {
                    RawExchangeProvider::mainnet_builder(self.signer.clone(), builder)
                } else {
                    RawExchangeProvider::mainnet(self.signer.clone())
                }
            }
            Network::Testnet => {
                if let Some(vault) = self.vault_address {
                    RawExchangeProvider::testnet_vault(self.signer.clone(), vault)
                } else if let Some(builder) = self.builder_address {
                    RawExchangeProvider::testnet_builder(self.signer.clone(), builder)
                } else {
                    RawExchangeProvider::testnet(self.signer.clone())
                }
            }
        };

        let inner = Arc::new(raw);

        // Create agent manager if needed
        let agent_manager = if self.config.auto_rotate_agents {
            Some(Arc::new(AgentManager::new(
                self.signer,
                self.config.agent_config.clone(),
                self.network,
            )))
        } else {
            None
        };

        // Create nonce manager
        let nonce_manager =
            Arc::new(NonceManager::new(self.config.isolate_subaccount_nonces));

        // Create batcher if needed
        let (batcher, batcher_handle) = if self.config.batch_orders {
            let (batcher, handle) = OrderBatcher::new(self.config.batch_config.clone());
            let batcher = Arc::new(batcher);

            // Spawn batch processing task
            let inner_clone = inner.clone();
            let inner_clone2 = inner.clone();
            let handle_future = tokio::spawn(async move {
                handle
                    .run(
                        move |orders| {
                            let inner = inner_clone.clone();
                            Box::pin(async move {
                                // Execute batch
                                let order_requests: Vec<OrderRequest> =
                                    orders.iter().map(|o| o.order.clone()).collect();

                                match inner.bulk_orders(order_requests).await {
                                    Ok(status) => {
                                        // Return same status for all orders in batch
                                        orders
                                            .iter()
                                            .map(|_| Ok(status.clone()))
                                            .collect()
                                    }
                                    Err(e) => {
                                        // Return same error for all orders in batch
                                        let err_str = e.to_string();
                                        orders
                                            .iter()
                                            .map(|_| {
                                                Err(HyperliquidError::InvalidResponse(
                                                    err_str.clone(),
                                                ))
                                            })
                                            .collect()
                                    }
                                }
                            })
                        },
                        move |cancels| {
                            let inner = inner_clone2.clone();
                            Box::pin(async move {
                                // Execute cancel batch
                                let cancel_requests: Vec<CancelRequest> =
                                    cancels.iter().map(|c| c.cancel.clone()).collect();

                                match inner.bulk_cancel(cancel_requests).await {
                                    Ok(status) => {
                                        // Return same status for all cancels in batch
                                        cancels
                                            .iter()
                                            .map(|_| Ok(status.clone()))
                                            .collect()
                                    }
                                    Err(e) => {
                                        // Return same error for all cancels in batch
                                        let err_str = e.to_string();
                                        cancels
                                            .iter()
                                            .map(|_| {
                                                Err(HyperliquidError::InvalidResponse(
                                                    err_str.clone(),
                                                ))
                                            })
                                            .collect()
                                    }
                                }
                            })
                        },
                    )
                    .await;
            });

            (
                Some(batcher),
                Some(Arc::new(TokioMutex::new(Some(handle_future)))),
            )
        } else {
            (None, None)
        };

        let provider = Arc::new(ManagedExchangeProvider {
            inner,
            agent_manager,
            nonce_manager,
            batcher,
            batcher_handle,
            config: self.config,
        });

        // Initialize agent if requested
        if let Some(agent_name) = self.initial_agent {
            if let Some(agent_mgr) = &provider.agent_manager {
                agent_mgr.get_or_rotate_agent(&agent_name).await?;
            }
        }

        Ok(provider)
    }
}