Skip to main content

hypercall_client/
vaults.rs

1//! Managed vaults: read vaults, their settlement history and a holder's
2//! position, create a vault, and queue deposits and withdrawals. Every write
3//! is EIP-712 signed in the Hypercall domain by the owner or holder it names.
4//!
5//! Deposits and withdrawals queue and fill at the next keeper settlement, at
6//! the vault's NAV. Poll [`HypercallClient::get_vault_holder`] for the fill.
7
8#![expect(
9    clippy::result_large_err,
10    reason = "these helpers preserve the established unboxed public ClientError contract"
11)]
12
13use alloy::sol;
14use reqwest::Method;
15use rust_decimal::Decimal;
16use serde::{Deserialize, Serialize};
17
18use crate::api::HypercallClient;
19use crate::error::{ClientError, Result};
20use crate::wallet::{AccountAddress, HypercallWallet};
21
22const API_ROUTE_VAULTS: &str = "/v1/vaults";
23
24fn vault_route(vault_id: u64, suffix: &str) -> String {
25    format!("{API_ROUTE_VAULTS}/{vault_id}{suffix}")
26}
27
28sol! {
29    /// `POST /v1/vaults`, signed by the owner.
30    #[derive(Debug, PartialEq, Eq)]
31    struct CreateVault {
32        address owner;
33        uint64 salt;
34        string initialSharePrice;
35        string minSeedUsdc;
36        string minDepositUsdc;
37        string minWithdrawUsdc;
38        uint64 cooldownMs;
39        uint64 settleIntervalMs;
40        uint64 withdrawalDeadlineMs;
41        uint32 forcedUnwindSlippageBps;
42        uint64 nonce;
43    }
44
45    /// `POST /v1/vaults/:id/deposit`, signed by the holder.
46    #[derive(Debug, PartialEq, Eq)]
47    struct VaultDeposit {
48        address holder;
49        uint64 vault;
50        string amount;
51        uint64 nonce;
52    }
53
54    /// `POST /v1/vaults/:id/withdraw`, signed by the holder.
55    #[derive(Debug, PartialEq, Eq)]
56    struct VaultWithdraw {
57        address holder;
58        uint64 vault;
59        string shares;
60        uint64 nonce;
61    }
62
63    /// `POST /v1/vaults/:id/cancel`, signed by the holder.
64    #[derive(Debug, PartialEq, Eq)]
65    struct VaultCancel {
66        address holder;
67        uint64 vault;
68        uint64 nonce;
69    }
70
71    /// `POST /v1/vaults/:id/close`, signed by the owner.
72    #[derive(Debug, PartialEq, Eq)]
73    struct VaultClose {
74        address owner;
75        uint64 vault;
76        uint64 nonce;
77    }
78}
79
80/// The exact decimal string a request sends and signs: positive, normalized
81/// (`60.50` signs as `60.5`).
82fn signed_decimal(field: &str, value: Decimal) -> Result<String> {
83    if value <= Decimal::ZERO {
84        return Err(ClientError::InvalidInput(format!(
85            "{field} must be positive"
86        )));
87    }
88    Ok(value.normalize().to_string())
89}
90
91/// A vault's owner-signed terms.
92#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
93pub struct VaultConfigParams {
94    pub initial_share_price: Decimal,
95    pub min_seed_usdc: Decimal,
96    pub min_deposit_usdc: Decimal,
97    pub min_withdraw_usdc: Decimal,
98    pub cooldown_ms: u64,
99    pub settle_interval_ms: u64,
100    pub withdrawal_deadline_ms: u64,
101    pub forced_unwind_slippage_bps: u32,
102}
103
104#[derive(Debug, Serialize)]
105struct VaultConfigBody {
106    initial_share_price: String,
107    min_seed_usdc: String,
108    min_deposit_usdc: String,
109    min_withdraw_usdc: String,
110    cooldown_ms: u64,
111    settle_interval_ms: u64,
112    withdrawal_deadline_ms: u64,
113    forced_unwind_slippage_bps: u32,
114}
115
116impl VaultConfigParams {
117    fn body(&self) -> Result<VaultConfigBody> {
118        Ok(VaultConfigBody {
119            initial_share_price: signed_decimal("initial_share_price", self.initial_share_price)?,
120            min_seed_usdc: signed_decimal("min_seed_usdc", self.min_seed_usdc)?,
121            min_deposit_usdc: signed_decimal("min_deposit_usdc", self.min_deposit_usdc)?,
122            min_withdraw_usdc: signed_decimal("min_withdraw_usdc", self.min_withdraw_usdc)?,
123            cooldown_ms: self.cooldown_ms,
124            settle_interval_ms: self.settle_interval_ms,
125            withdrawal_deadline_ms: self.withdrawal_deadline_ms,
126            forced_unwind_slippage_bps: self.forced_unwind_slippage_bps,
127        })
128    }
129}
130
131#[derive(Debug, Serialize)]
132struct CreateVaultRequest {
133    owner: AccountAddress,
134    salt: u64,
135    config: VaultConfigBody,
136    nonce: u64,
137    signature: String,
138}
139
140#[derive(Debug, Serialize)]
141struct VaultHolderRequest {
142    holder: AccountAddress,
143    #[serde(skip_serializing_if = "Option::is_none")]
144    amount: Option<String>,
145    #[serde(skip_serializing_if = "Option::is_none")]
146    shares: Option<String>,
147    nonce: u64,
148    signature: String,
149}
150
151/// `POST /v1/vaults` response: the derived account and the owner's
152/// `VaultManager` calldata.
153#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
154pub struct CreateVaultResponse {
155    pub success: bool,
156    pub request_id: String,
157    pub vault_id: Option<u64>,
158    pub account: AccountAddress,
159    pub vault_manager: AccountAddress,
160    /// Send with the HYPE creation deposit as `msg.value`.
161    pub create_vault_calldata: String,
162    /// Send once HyperCore has processed the creation deposit.
163    pub activate_vault_calldata: String,
164}
165
166/// A queued deposit, withdrawal or cancel.
167#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
168pub struct VaultRequestResponse {
169    pub success: bool,
170    pub request_id: String,
171    pub vault_id: u64,
172}
173
174#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
175pub struct VaultSettlement {
176    pub seq: u64,
177    pub at_ms: u64,
178    pub nav: Decimal,
179    pub share_price: Decimal,
180    pub total_shares: Decimal,
181    pub paged: bool,
182}
183
184#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
185pub struct VaultMetadata {
186    pub name: String,
187    pub description: String,
188    pub website_url: Option<String>,
189    pub logo_url: Option<String>,
190    pub updated_at_ms: u64,
191}
192
193/// One vault, from the engine snapshot.
194#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
195pub struct Vault {
196    pub vault_id: u64,
197    pub account: AccountAddress,
198    pub owner: AccountAddress,
199    /// `deploying`, `active`, `deposits_paused`, `halted`, `frozen` or
200    /// `closed`.
201    pub status: String,
202    pub config: VaultConfigParams,
203    pub total_shares: Decimal,
204    pub holder_count: usize,
205    pub queued_deposits: usize,
206    pub queued_withdrawals: usize,
207    pub last_settlement: Option<VaultSettlement>,
208    pub metadata: Option<VaultMetadata>,
209}
210
211#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
212pub struct VaultQueuedRequest {
213    pub request_id: String,
214    /// `deposit` or `withdrawal`.
215    pub kind: String,
216    /// USDC for a deposit, shares for a withdrawal.
217    pub amount: Decimal,
218    pub at_ms: u64,
219}
220
221/// One holder's shares and queued requests.
222#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
223pub struct VaultHolder {
224    pub vault_id: u64,
225    pub wallet: AccountAddress,
226    pub free_shares: Decimal,
227    pub locked_shares: Decimal,
228    pub last_deposit_fill_ms: Option<u64>,
229    pub queued: Vec<VaultQueuedRequest>,
230}
231
232#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
233pub struct VaultSettlementsPage {
234    pub vault_id: u64,
235    pub settlements: Vec<VaultSettlement>,
236    pub next_before_seq: Option<u64>,
237}
238
239#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
240pub struct VaultFill {
241    pub seq: u64,
242    pub at_ms: u64,
243    pub request_id: String,
244    /// `redemption`, `mint`, `release` or `close_redemption`.
245    pub kind: String,
246    pub usdc: Decimal,
247    pub shares: Decimal,
248    pub share_price: Decimal,
249}
250
251#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
252pub struct VaultHistoryPage {
253    pub vault_id: u64,
254    pub wallet: AccountAddress,
255    pub fills: Vec<VaultFill>,
256    pub next_before_seq: Option<u64>,
257}
258
259#[derive(Debug, Serialize)]
260struct VaultCloseRequest {
261    owner: AccountAddress,
262    nonce: u64,
263    signature: String,
264}
265
266/// One status transition (pause, resume, freeze, close).
267#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
268pub struct VaultStatusChange {
269    pub at_ms: u64,
270    pub from: String,
271    pub to: String,
272    /// `admin`, `keeper` or `owner`.
273    pub signer: String,
274    pub signer_wallet: Option<AccountAddress>,
275    pub cursor: u64,
276}
277
278#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
279pub struct VaultStatusChangesPage {
280    pub vault_id: u64,
281    pub changes: Vec<VaultStatusChange>,
282    /// Pass as `before` for the next page.
283    pub next_before: Option<u64>,
284}
285
286/// A page of history: older than `before_seq`, at most `limit` settlements.
287#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
288pub struct VaultPage {
289    pub before_seq: Option<u64>,
290    pub limit: Option<u32>,
291}
292
293impl VaultPage {
294    fn query(&self) -> Vec<(&'static str, String)> {
295        let mut query = Vec::new();
296        if let Some(before_seq) = self.before_seq {
297            query.push(("before_seq", before_seq.to_string()));
298        }
299        if let Some(limit) = self.limit {
300            query.push(("limit", limit.to_string()));
301        }
302        query
303    }
304}
305
306impl HypercallWallet {
307    /// Sign a `CreateVault` for this wallet as owner.
308    pub async fn sign_create_vault(
309        &self,
310        salt: u64,
311        config: &VaultConfigParams,
312        nonce: u64,
313    ) -> Result<String> {
314        let body = config.body()?;
315        let message = CreateVault {
316            owner: self.address.as_wallet_address().inner(),
317            salt,
318            initialSharePrice: body.initial_share_price,
319            minSeedUsdc: body.min_seed_usdc,
320            minDepositUsdc: body.min_deposit_usdc,
321            minWithdrawUsdc: body.min_withdraw_usdc,
322            cooldownMs: body.cooldown_ms,
323            settleIntervalMs: body.settle_interval_ms,
324            withdrawalDeadlineMs: body.withdrawal_deadline_ms,
325            forcedUnwindSlippageBps: body.forced_unwind_slippage_bps,
326            nonce,
327        };
328        self.sign_hypercall_action(&message, "CreateVault").await
329    }
330}
331
332impl HypercallClient {
333    /// Every vault, in id order.
334    pub async fn list_vaults(&self) -> Result<Vec<Vault>> {
335        Self::send_reqwest_json(self.request(Method::GET, API_ROUTE_VAULTS), "list vaults").await
336    }
337
338    /// One vault.
339    pub async fn get_vault(&self, vault_id: u64) -> Result<Vault> {
340        Self::send_reqwest_json(
341            self.request(Method::GET, &vault_route(vault_id, "")),
342            "get vault",
343        )
344        .await
345    }
346
347    /// One holder's shares and queued requests.
348    pub async fn get_vault_holder(
349        &self,
350        vault_id: u64,
351        wallet: AccountAddress,
352    ) -> Result<VaultHolder> {
353        Self::send_reqwest_json(
354            self.request(Method::GET, &vault_route(vault_id, "/me"))
355                .query(&[("wallet", wallet.to_string())]),
356            "get vault holder",
357        )
358        .await
359    }
360
361    /// A vault's settlements (NAV and share price per page), newest first.
362    pub async fn get_vault_settlements(
363        &self,
364        vault_id: u64,
365        page: VaultPage,
366    ) -> Result<VaultSettlementsPage> {
367        Self::send_reqwest_json(
368            self.request(Method::GET, &vault_route(vault_id, "/settlements"))
369                .query(&page.query()),
370            "get vault settlements",
371        )
372        .await
373    }
374
375    /// One holder's settlement fills in a vault, newest first.
376    pub async fn get_vault_history(
377        &self,
378        vault_id: u64,
379        wallet: AccountAddress,
380        page: VaultPage,
381    ) -> Result<VaultHistoryPage> {
382        let mut query = page.query();
383        query.push(("wallet", wallet.to_string()));
384        Self::send_reqwest_json(
385            self.request(Method::GET, &vault_route(vault_id, "/history"))
386                .query(&query),
387            "get vault history",
388        )
389        .await
390    }
391
392    /// Create a vault owned by `owner`. Send the returned calldata from the
393    /// owner to `VaultManager` to deploy and then activate it.
394    pub async fn create_vault(
395        &self,
396        owner: &HypercallWallet,
397        salt: u64,
398        config: &VaultConfigParams,
399    ) -> Result<CreateVaultResponse> {
400        let nonce = owner.next_nonce();
401        let signature = owner.sign_create_vault(salt, config, nonce).await?;
402        let request = CreateVaultRequest {
403            owner: owner.address,
404            salt,
405            config: config.body()?,
406            nonce,
407            signature,
408        };
409        Self::send_json_body(
410            self.request(Method::POST, API_ROUTE_VAULTS),
411            &request,
412            "create vault",
413        )
414        .await
415    }
416
417    /// Queue a deposit of `amount` USDC of the holder's free engine cash.
418    pub async fn deposit_to_vault(
419        &self,
420        holder: &HypercallWallet,
421        vault_id: u64,
422        amount: Decimal,
423    ) -> Result<VaultRequestResponse> {
424        let amount = signed_decimal("amount", amount)?;
425        let nonce = holder.next_nonce();
426        let message = VaultDeposit {
427            holder: holder.address.as_wallet_address().inner(),
428            vault: vault_id,
429            amount: amount.clone(),
430            nonce,
431        };
432        let signature = holder
433            .sign_hypercall_action(&message, "VaultDeposit")
434            .await?;
435        self.post_holder_request(
436            vault_id,
437            "/deposit",
438            VaultHolderRequest {
439                holder: holder.address,
440                amount: Some(amount),
441                shares: None,
442                nonce,
443                signature,
444            },
445        )
446        .await
447    }
448
449    /// Queue a withdrawal of `shares`.
450    pub async fn withdraw_from_vault(
451        &self,
452        holder: &HypercallWallet,
453        vault_id: u64,
454        shares: Decimal,
455    ) -> Result<VaultRequestResponse> {
456        let shares = signed_decimal("shares", shares)?;
457        let nonce = holder.next_nonce();
458        let message = VaultWithdraw {
459            holder: holder.address.as_wallet_address().inner(),
460            vault: vault_id,
461            shares: shares.clone(),
462            nonce,
463        };
464        let signature = holder
465            .sign_hypercall_action(&message, "VaultWithdraw")
466            .await?;
467        self.post_holder_request(
468            vault_id,
469            "/withdraw",
470            VaultHolderRequest {
471                holder: holder.address,
472                amount: None,
473                shares: Some(shares),
474                nonce,
475                signature,
476            },
477        )
478        .await
479    }
480
481    /// A vault's status transitions, newest first. `page.before_seq` is a
482    /// previous page's `next_before`; this route names it `before`.
483    pub async fn get_vault_status_changes(
484        &self,
485        vault_id: u64,
486        page: VaultPage,
487    ) -> Result<VaultStatusChangesPage> {
488        let mut query = Vec::new();
489        if let Some(before) = page.before_seq {
490            query.push(("before", before.to_string()));
491        }
492        if let Some(limit) = page.limit {
493            query.push(("limit", limit.to_string()));
494        }
495        Self::send_reqwest_json(
496            self.request(Method::GET, &vault_route(vault_id, "/status-changes"))
497                .query(&query),
498            "get vault status changes",
499        )
500        .await
501    }
502
503    /// Request that a vault close, as its owner. A deploying vault closes at
504    /// once; a live one freezes, is unwound, and redeems every holder. Repeat
505    /// the request to advance a frozen vault's close pages.
506    pub async fn close_vault(
507        &self,
508        owner: &HypercallWallet,
509        vault_id: u64,
510    ) -> Result<VaultRequestResponse> {
511        let nonce = owner.next_nonce();
512        let message = VaultClose {
513            owner: owner.address.as_wallet_address().inner(),
514            vault: vault_id,
515            nonce,
516        };
517        let signature = owner.sign_hypercall_action(&message, "VaultClose").await?;
518        Self::send_json_body(
519            self.request(Method::POST, &vault_route(vault_id, "/close")),
520            &VaultCloseRequest {
521                owner: owner.address,
522                nonce,
523                signature,
524            },
525            "close vault",
526        )
527        .await
528    }
529
530    /// Release every queued deposit and withdrawal the holder has in a vault.
531    pub async fn cancel_vault_requests(
532        &self,
533        holder: &HypercallWallet,
534        vault_id: u64,
535    ) -> Result<VaultRequestResponse> {
536        let nonce = holder.next_nonce();
537        let message = VaultCancel {
538            holder: holder.address.as_wallet_address().inner(),
539            vault: vault_id,
540            nonce,
541        };
542        let signature = holder
543            .sign_hypercall_action(&message, "VaultCancel")
544            .await?;
545        self.post_holder_request(
546            vault_id,
547            "/cancel",
548            VaultHolderRequest {
549                holder: holder.address,
550                amount: None,
551                shares: None,
552                nonce,
553                signature,
554            },
555        )
556        .await
557    }
558
559    async fn post_holder_request(
560        &self,
561        vault_id: u64,
562        suffix: &str,
563        request: VaultHolderRequest,
564    ) -> Result<VaultRequestResponse> {
565        Self::send_json_body(
566            self.request(Method::POST, &vault_route(vault_id, suffix)),
567            &request,
568            "vault request",
569        )
570        .await
571    }
572}
573
574#[cfg(test)]
575#[path = "vaults_test.rs"]
576mod tests;