hypersdk 0.2.8

Rust SDK for 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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
//! Morpho Blue lending protocol integration.
//!
//! This module provides clients for interacting with Morpho Blue, a decentralized
//! lending protocol, and MetaMorpho vaults on HyperEVM.
//!
//! # Overview
//!
//! Morpho Blue is an efficient lending protocol that allows users to:
//! - Supply assets to earn interest
//! - Borrow assets with collateral
//! - Create isolated lending markets
//!
//! MetaMorpho vaults aggregate multiple Morpho markets to optimize yields.
//!
//! # Clients
//!
//! - [`Client`]: For interacting with individual Morpho Blue markets
//! - [`MetaClient`]: For interacting with MetaMorpho vaults
//!
//! # Examples
//!
//! ## Query Market APY
//!
//! ```no_run
//! use hypersdk::hyperevm::morpho;
//! use hypersdk::Address;
//!
//! # async fn example() -> anyhow::Result<()> {
//! let client = morpho::Client::mainnet().await?;
//!
//! let morpho_addr: Address = "0x...".parse()?;
//! let market_id = [0u8; 32].into();
//!
//! let apy = client.apy::<f64, _>(morpho_addr, market_id, |e| e.exp()).await?;
//! println!("Borrow APY: {:.2}%", apy.borrow * 100.0);
//! println!("Supply APY: {:.2}%", apy.supply * 100.0);
//! # Ok(())
//! # }
//! ```
//!
//! ## Query MetaMorpho Vault APY
//!
//! ```no_run
//! use hypersdk::hyperevm::morpho;
//! use hypersdk::{U256, Address};
//!
//! # async fn example() -> anyhow::Result<()> {
//! let client = morpho::MetaClient::mainnet().await?;
//!
//! let vault_addr: Address = "0x...".parse()?;
//! let vault_apy = client.apy::<f64, _>(vault_addr, |e| e.exp()).await?;
//!
//! println!("Vault APY: {:.2}%", vault_apy.apy::<f64, _>(|v| v.to::<u128>() as f64 / 1e18) * 100.0);
//! println!("Fee: {:.2}%", vault_apy.fee * U256::from(100));
//! # Ok(())
//! # }
//! ```

use std::ops::{Add, Div, Mul, Sub};

use alloy::{
    primitives::{Address, FixedBytes, U256},
    providers::Provider,
    transports::TransportError,
};
use num_traits::{FromPrimitive, One, ToPrimitive};

use crate::hyperevm::{
    DynProvider,
    morpho::contracts::{
        IIrm,
        IMetaMorpho::{self, IMetaMorphoInstance},
        IMorpho::{self, IMorphoInstance},
        Market, MarketParams,
    },
};

pub mod contracts;

/// Morpho market identifier.
///
/// A 32-byte unique identifier for a Morpho Blue market.
pub type MarketId = FixedBytes<32>;

/// Annual Percentage Yield (APY) for a Morpho market.
///
/// Contains both borrow and supply APY rates for a lending market.
///
/// # Example
///
/// Query APY for a market: `client.apy(morpho_addr, market_id).await?`
/// Access borrow and supply APY via `apy.borrow` and `apy.supply` fields.
#[derive(Debug, Clone)]
pub struct PoolApy<T128> {
    /// Market parameters (loan token, collateral, oracle, IRM, LLTV)
    pub params: MarketParams,
    /// Current market state (supply, borrow, fees)
    pub market: Market,
    /// Borrow APY as a decimal (0.05 = 5%)
    pub borrow: T128,
    /// Supply APY as a decimal (0.03 = 3%)
    pub supply: T128,
}

/// MetaMorpho vault APY information.
///
/// A MetaMorpho vault aggregates multiple Morpho markets to optimize yields.
/// This struct contains all the information needed to calculate the vault's APY.
///
/// # Example
///
/// Query vault APY: `client.apy(vault_addr).await?`
/// Calculate effective APY after fees using `vault_apy.apy()` method.
/// Individual market data available in `vault_apy.components`.
#[derive(Debug, Clone)]
pub struct VaultApy<T128> {
    /// Individual markets that compose this vault
    pub components: Vec<VaultSupply<T128>>,
    /// Vault management fee (raw U256 value, divide by 1e18)
    pub fee: U256,
    /// Total assets deposited into the vault (raw U256 value)
    pub total_deposits: U256,
}

#[derive(Debug, Clone)]
pub struct VaultSupply<T128> {
    pub supplied_shares: U256,
    pub pool: PoolApy<T128>,
    /// Supply APY as U256 (scaled by 1e18, e.g., 0.05 * 1e18 = 5% APY)
    pub supply_apy: T128,
}

impl<T128> VaultApy<T128>
where
    T128: ToPrimitive,
{
    /// Calculates the effective vault APY after fees.
    ///
    /// This is a weighted average of all underlying market APYs, adjusted for
    /// the vault's management fee.
    ///
    /// The return value is scaled to 18 decimals. Which means, if the
    /// APY of a vault is 4.20% the string representation of your decimal
    /// implementation should be close to `0.042`.
    ///
    /// # Type Parameters
    ///
    /// - `T`: The numeric type to use for calculations (e.g., f64, Decimal, etc.)
    ///   Must support arithmetic operations and conversion from U256.
    /// - `F`: Conversion function from U256 to T
    ///
    /// # Arguments
    ///
    /// - `convert`: Function to convert U256 values to your numeric type
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hypersdk::hyperevm::morpho;
    /// use hypersdk::Address;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let client = morpho::MetaClient::mainnet().await?;
    /// let vault_addr: Address = "0x...".parse()?;
    /// let vault_apy = client.apy::<f64, _>(vault_addr, |value| value.exp()).await?;
    ///
    /// // Using f64
    /// let apy_f64 = vault_apy.apy(|u| u.to::<u128>() as f64);
    ///
    /// // Using a custom Decimal type (rust_decimal example)
    /// // let apy_decimal = vault_apy.apy(|u| Decimal::from_u128(u.to::<u128>()).unwrap());
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn apy<T256, F>(&self, convert: F) -> T256
    where
        T256: Add<T256, Output = T256>
            + Sub<T256, Output = T256>
            + Mul<T256, Output = T256>
            + Div<T256, Output = T256>
            + One
            + Copy,
        F: Fn(U256) -> T256,
    {
        let zero = convert(U256::ZERO);
        let wad = convert(U256::from(1_000_000_000_000_000_000u128));

        if self.total_deposits.is_zero() {
            return zero;
        }

        let total_deposits = convert(self.total_deposits);
        let fee = convert(self.fee);

        let fee_multiplier = (wad - fee) / wad;

        let gross_apy = self
            .components
            .iter()
            .filter_map(|component| {
                if component.pool.market.totalSupplyShares == 0 {
                    return None;
                }

                let supplied_shares = convert(component.supplied_shares);
                let total_supply_assets =
                    convert(U256::from(component.pool.market.totalSupplyAssets));
                let total_supply_shares =
                    convert(U256::from(component.pool.market.totalSupplyShares));

                // Convert shares to assets: shares * total_assets / total_shares = assets
                let supplied_assets = supplied_shares * total_supply_assets / total_supply_shares;
                let supply_apy = convert(U256::from(component.supply_apy.to_u128().unwrap()));
                Some(supplied_assets * supply_apy / total_deposits)
            })
            .fold(zero, |acc, x| acc + x);

        gross_apy * fee_multiplier / wad
    }

    /// Returns the number of markets in the vault.
    #[must_use]
    pub fn market_count(&self) -> usize {
        self.components.len()
    }
}

/// Client for Morpho Blue lending markets.
///
/// Provides methods for querying market information and calculating APYs.
///
/// # Example
///
/// ```no_run
/// use hypersdk::hyperevm::morpho;
/// use hypersdk::Address;
///
/// # async fn example() -> anyhow::Result<()> {
/// // Create a mainnet client
/// let client = morpho::Client::mainnet().await?;
///
/// // Query a market's APY
/// let morpho_addr: Address = "0x...".parse()?;
/// let market_id = [0u8; 32].into();
/// let apy = client.apy::<f64, _>(morpho_addr, market_id, |e| e.exp()).await?;
///
/// println!("Supply APY: {:.2}%", apy.supply * 100.0);
/// # Ok(())
/// # }
/// ```
pub struct Client<P>
where
    P: Provider,
{
    provider: P,
}

impl Client<DynProvider> {
    /// Creates a client for HyperEVM mainnet.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hypersdk::hyperevm::morpho;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let client = morpho::Client::mainnet().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn mainnet() -> Result<Self, TransportError> {
        let provider = DynProvider::new(super::mainnet().await?);
        Ok(Self::new(provider))
    }

    /// Creates a client with a custom RPC URL.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hypersdk::hyperevm::morpho;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let client = morpho::Client::mainnet_with_url("https://custom-rpc.example.com").await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn mainnet_with_url(url: &str) -> Result<Self, TransportError> {
        let provider = DynProvider::new(super::mainnet_with_url(url).await?);
        Ok(Self::new(provider))
    }
}

impl<P> Client<P>
where
    P: Provider + Clone,
{
    /// Creates a new Morpho client with a custom provider.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hypersdk::hyperevm::{self, morpho};
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let provider = hyperevm::mainnet().await?;
    /// let client = morpho::Client::new(provider);
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(provider: P) -> Self {
        Self { provider }
    }

    /// Returns a reference to the underlying provider.
    pub fn provider(&self) -> &P {
        &self.provider
    }

    /// Creates a Morpho contract instance at the given address.
    ///
    /// Use this to call Morpho contract methods directly.
    pub fn instance(&self, address: Address) -> IMorphoInstance<P> {
        IMorpho::new(address, self.provider.clone())
    }

    /// Calculates the APY for a specific Morpho market.
    ///
    /// This helper types require a type that can handle big decimal conversions
    /// for precision. Using a simple f64 might overflow, cause conversion errors
    /// or be unprecise enough.
    ///
    /// You can still use f64.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hypersdk::hyperevm::{DynProvider, morpho::{self, MetaClient}};
    /// use hypersdk::Address;
    ///
    /// async fn example(provider: DynProvider, contract: Address) -> anyhow::Result<()> {
    ///     let vault = MetaClient::new(provider)
    ///         .apy::<f64, _>(contract, |e| e.exp())
    ///         .await?;
    ///
    ///     println!(
    ///         "apy: {}%",
    ///         vault.apy(|v| v.to::<i128>() as f64 / 1e18) * 100.0
    ///     );
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn apy<T128, F>(
        &self,
        address: Address,
        market_id: MarketId,
        exp: F,
    ) -> anyhow::Result<PoolApy<T128>>
    where
        T128: FromPrimitive
            + Add<T128, Output = T128>
            + Sub<T128, Output = T128>
            + Mul<T128, Output = T128>
            + Div<T128, Output = T128>
            + One
            + Copy,
        F: FnOnce(T128) -> T128,
    {
        let morpho = IMorpho::new(address, self.provider.clone());
        let (params, market) = self
            .provider
            .multicall()
            .add(morpho.idToMarketParams(market_id))
            .add(morpho.market(market_id))
            .aggregate()
            .await?;
        self.apy_with(params, market, exp).await
    }

    /// Returns the APY of the market.
    pub async fn apy_with<T128, F>(
        &self,
        params: impl Into<MarketParams>,
        market: impl Into<Market>,
        exp: F,
    ) -> anyhow::Result<PoolApy<T128>>
    where
        T128: FromPrimitive
            + Sub<T128, Output = T128>
            + Mul<T128, Output = T128>
            + Div<T128, Output = T128>
            + One
            + Copy,
        F: FnOnce(T128) -> T128,
    {
        let params = params.into();
        let market = market.into();
        anyhow::ensure!(
            market.totalSupplyAssets > 0,
            "market has no assets supplied"
        );

        let irm = IIrm::new(params.irm, self.provider.clone());
        let rate = irm
            .borrowRateView(params.into(), market.into())
            .call()
            .await?;

        let error = || anyhow::anyhow!("unable to convert u128 into Float");

        let wad = T128::from_u128(1_000_000_000_000_000_000u128).ok_or_else(error)?;
        let seconds_in_a_year = T128::from_u128(31_536_000).ok_or_else(error)?;
        let one = T128::one();

        let fee = T128::from_u128(market.fee).ok_or_else(error)? / wad;
        let utilization = T128::from_u128(market.totalBorrowAssets).ok_or_else(error)?
            / T128::from_u128(market.totalSupplyAssets).ok_or_else(error)?;
        let rate = T128::from_u128(rate.to::<u128>()).ok_or_else(error)? / wad;
        let borrow_apy = (exp)(rate * seconds_in_a_year) - one;
        let supply_apy = borrow_apy * utilization * (one - fee);

        Ok(PoolApy {
            params,
            market,
            borrow: borrow_apy,
            supply: supply_apy,
        })
    }
}

/// MetaMorpho client
pub struct MetaClient<P>
where
    P: Provider,
{
    provider: P,
}

impl MetaClient<DynProvider> {
    /// Creates a client for mainnet.
    pub async fn mainnet() -> Result<Self, TransportError> {
        let provider = DynProvider::new(super::mainnet().await?);
        Ok(Self::new(provider))
    }

    /// Creates a client for mainnet.
    pub async fn mainnet_with_url(url: &str) -> Result<Self, TransportError> {
        let provider = DynProvider::new(super::mainnet_with_url(url).await?);
        Ok(Self::new(provider))
    }
}

impl<P> MetaClient<P>
where
    P: Provider + Clone,
{
    /// Create a uniswap client.
    pub fn new(provider: P) -> Self {
        Self { provider }
    }

    /// Returns the root provider.
    pub fn provider(&self) -> &P {
        &self.provider
    }

    /// Creates a MetaMorphoInstance.
    pub fn instance(&self, address: Address) -> IMetaMorphoInstance<P> {
        IMetaMorpho::new(address, self.provider.clone())
    }

    /// Returns the pool's APY.
    ///
    /// <https://github.com/morpho-org/metamorpho-v1.1/blob/main/src/MetaMorphoV1_1.sol#L796>
    pub async fn apy<T128, F>(&self, address: Address, exp: F) -> anyhow::Result<VaultApy<T128>>
    where
        T128: FromPrimitive
            + Add<T128, Output = T128>
            + Sub<T128, Output = T128>
            + Mul<T128, Output = T128>
            + Div<T128, Output = T128>
            + One
            + Copy,
        F: FnOnce(T128) -> T128 + Copy,
    {
        let error = || anyhow::anyhow!("unable to convert u128 into Float");
        let wad = T128::from_u128(1_000_000_000_000_000_000u128).ok_or_else(error)?;

        let meta_morpho = IMetaMorpho::new(address, self.provider.clone());
        let (fee, supply_queue_len, total_assets, morpho_addr) = self
            .provider
            .multicall()
            .add(meta_morpho.fee())
            .add(meta_morpho.supplyQueueLength())
            .add(meta_morpho.totalAssets())
            .add(meta_morpho.MORPHO())
            .aggregate()
            .await?;
        let supply_queue_len = supply_queue_len.to::<usize>();

        let morpho = IMorpho::new(morpho_addr, self.provider.clone());

        let mut apy = VaultApy {
            components: vec![],
            fee: U256::from(fee),
            total_deposits: total_assets,
        };
        for i in 0..supply_queue_len {
            // TODO: is there a way to aggregate this?
            let market_id = meta_morpho.supplyQueue(U256::from(i)).call().await?;

            let (config, params, market) = self
                .provider
                .multicall()
                .add(meta_morpho.config(market_id))
                .add(morpho.idToMarketParams(market_id))
                .add(morpho.market(market_id))
                .aggregate()
                .await?;

            if !config.enabled
                || params.irm.is_zero()
                || params.collateralToken.is_zero()
                || params.loanToken.is_zero()
            {
                // println!("{} has no IRM?", market_id);
                continue;
            }

            let position = morpho
                .position(market_id, *meta_morpho.address())
                .call()
                .await?;

            let pool = Client::new(self.provider.clone())
                .apy_with::<T128, F>(params, market, exp)
                .await?;

            let supply_apy = pool.supply * wad;

            apy.components.push(VaultSupply {
                supplied_shares: position.supplyShares,
                pool,
                supply_apy,
            });
        }

        Ok(apy)
    }
}