hylo-core 0.5.0

Core protocol data types, math, and utilities.
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
use anchor_lang::prelude::*;
use fix::prelude::*;

use crate::error::CoreError::{
  ExoCollateralToUsdc, ExoFromToken, ExoToToken, ExoUsdcToCollateral,
  LeverToStable, LstToToken, LstToUsdc, StableToLever, TokenToLst, UsdcToLst,
};
use crate::pyth::PriceRange;

/// Provides conversions between an LST and protocol tokens.
pub struct Conversion {
  pub usd_sol_price: PriceRange<N9>,
  pub lst_sol_price: UFix64<N9>,
}

impl Conversion {
  #[must_use]
  pub fn new(usd_sol_price: PriceRange<N9>, lst_sol_price: UFix64<N9>) -> Self {
    Conversion {
      usd_sol_price,
      lst_sol_price,
    }
  }

  /// Computes how much of a protocol token to emit for an input amount of SOL.
  ///   `LST * (SOL/LST) * (USD/SOL) / NAV`
  pub fn lst_to_token(
    &self,
    amount_lst: UFix64<N9>,
    token_nav: UFix64<N9>,
  ) -> Result<UFix64<N6>> {
    amount_lst
      .mul_div_floor(self.lst_sol_price, UFix64::one())
      .and_then(|sol| sol.mul_div_floor(self.usd_sol_price.lower, token_nav))
      .map(UFix64::convert)
      .ok_or(LstToToken.into())
  }

  /// Finds the conversion amount between a protocol tokens and an LST.
  ///   `TOKEN * NAV / ((USD/SOL) * (SOL/LST))`
  pub fn token_to_lst(
    &self,
    amount_token: UFix64<N6>,
    token_nav: UFix64<N9>,
  ) -> Result<UFix64<N9>> {
    amount_token
      .convert::<N9>()
      .mul_div_floor(token_nav, self.usd_sol_price.upper)
      .and_then(|sol| sol.mul_div_floor(UFix64::one(), self.lst_sol_price))
      .ok_or(TokenToLst.into())
  }
}

/// Conversions between the protocol's tokens.
pub struct SwapConversion {
  pub stablecoin_nav: UFix64<N9>,
  pub levercoin_nav: PriceRange<N9>,
}

impl SwapConversion {
  #[must_use]
  pub fn new(
    stablecoin_nav: UFix64<N9>,
    levercoin_nav: PriceRange<N9>,
  ) -> Self {
    SwapConversion {
      stablecoin_nav,
      levercoin_nav,
    }
  }

  pub fn stable_to_lever(
    &self,
    amount_stable: UFix64<N6>,
  ) -> Result<UFix64<N6>> {
    amount_stable
      .mul_div_floor(self.stablecoin_nav, UFix64::one())
      .and_then(|usd| {
        usd.mul_div_floor(UFix64::one(), self.levercoin_nav.upper)
      })
      .ok_or(StableToLever.into())
  }

  pub fn lever_to_stable(
    &self,
    amount_lever: UFix64<N6>,
  ) -> Result<UFix64<N6>> {
    amount_lever
      .mul_div_floor(self.levercoin_nav.lower, UFix64::one())
      .and_then(|usd| usd.mul_div_floor(UFix64::one(), self.stablecoin_nav))
      .ok_or(LeverToStable.into())
  }
}

/// Conversions between an exogenous collateral and protocol tokens.
pub struct ExoConversion {
  pub collateral_usd_price: PriceRange<N9>,
}

impl ExoConversion {
  /// Converts collateral amount to a protocol token amount.
  ///
  /// # Errors
  /// * Arithmetic failure
  pub fn exo_to_token(
    &self,
    amount: UFix64<N9>,
    token_nav: UFix64<N9>,
  ) -> Result<UFix64<N6>> {
    amount
      .mul_div_floor(self.collateral_usd_price.lower, token_nav)
      .and_then(UFix64::checked_convert::<N6>)
      .ok_or(ExoToToken.into())
  }

  /// Converts a protocol token amount to exogenous collateral.
  ///
  /// # Errors
  /// * Arithmetic failure
  pub fn token_to_exo(
    &self,
    amount: UFix64<N6>,
    token_nav: UFix64<N9>,
  ) -> Result<UFix64<N9>> {
    amount
      .checked_convert::<N9>()
      .and_then(|a| a.mul_div_floor(token_nav, self.collateral_usd_price.upper))
      .ok_or(ExoFromToken.into())
  }
}

/// Directional conversion between USDC and stablecoin amounts.
pub struct UsdcStablecoinConversion {
  pub usdc_usd_price: PriceRange<N9>,
}

impl UsdcStablecoinConversion {
  /// USDC deposit to stablecoin amount using lower bound.
  ///
  /// Used for USDC to stablecoin swaps and sell-side collateral swaps to
  /// compute virtual stablecoins to mint when USDC enters the vault.
  ///
  /// # Errors
  /// * Arithmetic overflow or precision conversion
  pub fn deposit_to_stablecoin(
    &self,
    usdc_amount: UFix64<N9>,
  ) -> Result<UFix64<N6>> {
    usdc_amount
      .mul_div_floor(self.usdc_usd_price.lower, UFix64::one())
      .and_then(UFix64::checked_convert)
      .ok_or(ExoToToken.into())
  }

  /// Stablecoin to USDC withdrawal amount using upper bound.
  /// Used on when user redeems stablecoin to USDC.
  ///
  /// # Errors
  /// * Arithmetic overflow or precision conversion
  pub fn stablecoin_to_withdrawal(
    &self,
    stablecoin_amount: UFix64<N6>,
  ) -> Result<UFix64<N9>> {
    stablecoin_amount
      .checked_convert::<N9>()
      .and_then(|a| a.mul_div_floor(UFix64::one(), self.usdc_usd_price.upper))
      .ok_or(ExoFromToken.into())
  }

  /// USDC withdrawal to stablecoin equivalent using upper bound.
  ///
  /// Used on buy-side collateral swaps to compute virtual stablecoins to burn
  /// when USDC leaves the vault.
  ///
  /// # Errors
  /// * Arithmetic overflow or precision conversion
  pub fn withdrawal_to_stablecoin(
    &self,
    usdc_amount: UFix64<N9>,
  ) -> Result<UFix64<N6>> {
    usdc_amount
      .mul_div_floor(self.usdc_usd_price.upper, UFix64::one())
      .and_then(UFix64::checked_convert)
      .ok_or(ExoToToken.into())
  }
}

/// Conversions between exogenous collateral and USDC via oracle prices.
pub struct ExoRebalanceConversion {
  pub collateral_rebalance_usd_price: UFix64<N9>,
  pub usdc_usd_price: PriceRange<N9>,
}

impl ExoRebalanceConversion {
  /// Converts exogenous collateral to USDC
  ///
  /// # Errors
  /// * Arithmetic failure
  pub fn collateral_to_usdc(
    &self,
    collateral_amount: UFix64<N9>,
  ) -> Result<UFix64<N9>> {
    collateral_amount
      .mul_div_floor(
        self.collateral_rebalance_usd_price,
        self.usdc_usd_price.upper,
      )
      .ok_or(ExoCollateralToUsdc.into())
  }

  /// Converts USDC to exogenous collateral
  ///
  /// # Errors
  /// * Arithmetic failure
  pub fn usdc_to_collateral(
    &self,
    usdc_amount: UFix64<N9>,
  ) -> Result<UFix64<N9>> {
    usdc_amount
      .mul_div_floor(
        self.usdc_usd_price.lower,
        self.collateral_rebalance_usd_price,
      )
      .ok_or(ExoUsdcToCollateral.into())
  }
}

/// Conversions between LST and USDC via SOL for rebalancing.
pub struct LstRebalanceConversion {
  pub lst_sol_price: UFix64<N9>,
  pub sol_rebalance_usd_price: UFix64<N9>,
  pub usdc_usd_price: PriceRange<N9>,
}

impl LstRebalanceConversion {
  /// Converts LST to USDC for sell-side rebalancing.
  ///
  /// # Errors
  /// * Arithmetic failure
  pub fn lst_to_usdc(&self, lst_amount: UFix64<N9>) -> Result<UFix64<N9>> {
    lst_amount
      .mul_div_floor(self.lst_sol_price, UFix64::one())
      .and_then(|sol| {
        sol.mul_div_floor(
          self.sol_rebalance_usd_price,
          self.usdc_usd_price.upper,
        )
      })
      .ok_or(LstToUsdc.into())
  }

  /// Converts USDC to LST for buy-side rebalancing.
  ///
  /// # Errors
  /// * Arithmetic failure
  pub fn usdc_to_lst(&self, usdc_amount: UFix64<N9>) -> Result<UFix64<N9>> {
    usdc_amount
      .mul_div_floor(self.usdc_usd_price.lower, self.sol_rebalance_usd_price)
      .and_then(|sol| sol.mul_div_floor(UFix64::one(), self.lst_sol_price))
      .ok_or(UsdcToLst.into())
  }
}

#[cfg(test)]
mod tests {
  use proptest::prelude::*;

  use super::*;
  use crate::eq_tolerance;
  use crate::util::proptest::*;

  proptest! {
    #[test]
    fn lst_to_stablecoin_roundtrip(
      state in protocol_state(()),
      lst_sol_price in lst_sol_price(),
      lst_amount in lst_amount(),
    ) {
      let usd_sol_price = PriceRange::one(state.usd_sol_price);
      let conversion = Conversion::new(usd_sol_price, lst_sol_price);
      let amount_token = conversion.lst_to_token(lst_amount, state.stablecoin_nav)?;
      let back_amount_lst = conversion.token_to_lst(amount_token, state.stablecoin_nav)?;
      // Checks converted values are within tolerance of 0.000001 LST
      prop_assert!(
        eq_tolerance!(lst_amount, back_amount_lst, N9, UFix64::new(1000))
      );
    }

    #[test]
    fn lst_to_levercoin_roundtrip(
      state in protocol_state(()),
      lst_sol_price in lst_sol_price(),
      lst_amount in lst_amount(),
    ) {
      let usd_sol_price = PriceRange::one(state.usd_sol_price);
      let conversion = Conversion::new(usd_sol_price, lst_sol_price);
      let amount_token = conversion.lst_to_token(lst_amount, state.levercoin_nav)?;
      let back_amount_lst = conversion.token_to_lst(amount_token, state.levercoin_nav)?;
      // Checks converted values are within tolerance of 0.0001 LST
      // Inherently lossier considering small levercoin NAVs
      prop_assert!(
        eq_tolerance!(lst_amount, back_amount_lst, N9, UFix64::new(100_000))
      );
    }

    #[test]
    fn stablecoin_to_lst_roundtrip(
      state in protocol_state(()),
      lst_sol_price in lst_sol_price(),
    ) {
      let usd_sol_price = PriceRange::one(state.usd_sol_price);
      let conversion = Conversion::new(usd_sol_price, lst_sol_price);
      let amount_lst = conversion.token_to_lst(state.stablecoin_amount, state.stablecoin_nav)?;
      let back_amount_token = conversion.lst_to_token(amount_lst, state.stablecoin_nav)?;
      // Checks converted values are within tolerance of $0.001
      prop_assert!(
        eq_tolerance!(state.stablecoin_amount, back_amount_token, N6, UFix64::new(1000))
      );
    }

    #[test]
    fn levercoin_to_lst_roundtrip(
      state in protocol_state(()),
      lst_sol_price in lst_sol_price(),
    ) {
      let usd_sol_price = PriceRange::one(state.usd_sol_price);
      let conversion = Conversion::new(usd_sol_price, lst_sol_price);
      let amount_lst = conversion.token_to_lst(state.levercoin_amount, state.levercoin_nav)?;
      let back_amount_levercoin = conversion.lst_to_token(amount_lst, state.levercoin_nav)?;
      // Checks converted values are within tolerance of $0.001
      prop_assert!(
        eq_tolerance!(state.levercoin_amount, back_amount_levercoin, N6, UFix64::new(1000))
      );
    }
  }

  #[test]
  fn amount_to_mint_lever() -> Result<()> {
    let usd_sol_price = PriceRange::one(UFix64::<N9>::new(171_030_000_000));
    let lst_sol = UFix64::<N9>::new(1_736_835_834);
    let conversion = Conversion::new(usd_sol_price, lst_sol);
    let amount_in = UFix64::<N9>::new(50_123_303_006);
    let nav = UFix64::<N9>::new(100_232_580_000);
    let out = conversion.lst_to_token(amount_in, nav)?;
    assert_eq!(UFix64::new(148_546_300), out);
    Ok(())
  }

  #[test]
  fn amount_to_mint_stable() -> Result<()> {
    let usd_sol_price = PriceRange::one(UFix64::<N9>::new(171_030_000_000));
    let lst_sol = UFix64::<N9>::new(1_736_835_834);
    let conversion = Conversion::new(usd_sol_price, lst_sol);
    let amount_in = UFix64::<N9>::new(568);
    let out = conversion.lst_to_token(amount_in, UFix64::one())?;
    assert_eq!(UFix64::new(168), out);
    Ok(())
  }

  #[test]
  fn amount_to_redeem_stable() -> Result<()> {
    let usd_sol_price = PriceRange::one(UFix64::<N9>::new(171_030_000_000));
    let lst_sol = UFix64::<N9>::new(1_110_462_847);
    let conversion = Conversion::new(usd_sol_price, lst_sol);
    let amount = UFix64::<N6>::new(9_937_412_179);
    let lst_out: UFix64<N9> = conversion.token_to_lst(amount, UFix64::one())?;
    assert_eq!(UFix64::new(52_323_522_668), lst_out);
    Ok(())
  }

  #[test]
  fn amount_to_redeem_lever() -> Result<()> {
    let usd_sol_price = PriceRange::one(UFix64::<N9>::new(171_030_000_000));
    let lst_sol = UFix64::<N9>::new(1_110_462_847);
    let conversion = Conversion::new(usd_sol_price, lst_sol);
    let nav = UFix64::<N9>::new(137_992_981_000);
    let amount = UFix64::<N6>::new(543_150_099);
    let lst_out: UFix64<N9> = conversion.token_to_lst(amount, nav)?;
    assert_eq!(UFix64::new(394_639_480_798), lst_out);
    Ok(())
  }

  proptest! {
    #[test]
    fn stable_lever_roundtrip(
      stablecoin_nav in stablecoin_nav(),
      levercoin_nav in levercoin_nav(),
      amount_stable in token_amount(),
    ) {
      let conversion = SwapConversion::new(stablecoin_nav, PriceRange::one(levercoin_nav));
      let amount_lever = conversion.stable_to_lever(amount_stable)?;
      let amount_stable_out = conversion.lever_to_stable(amount_lever)?;

      // Checks converted values are within tolerance of 0.01 USD
      prop_assert!(
        eq_tolerance!(amount_stable, amount_stable_out, N6, UFix64::new(10000))
      );
    }

    #[test]
    fn lever_stable_roundtrip(
      stablecoin_nav in stablecoin_nav(),
      levercoin_nav in levercoin_nav(),
      amount_lever in token_amount(),
    ) {
      let conversion = SwapConversion::new(stablecoin_nav, PriceRange::one(levercoin_nav));
      let amount_stable = conversion.lever_to_stable(amount_lever)?;
      let amount_lever_out = conversion.stable_to_lever(amount_stable)?;

      // Checks converted values are within tolerance of 0.01 USD
      prop_assert!(
        eq_tolerance!(amount_lever, amount_lever_out, N6, UFix64::new(10000))
      );
    }
  }

  const UNDERPEGGED_USDC: PriceRange<N9> = PriceRange {
    lower: UFix64::constant(997_000_000),
    upper: UFix64::constant(999_000_000),
  };

  const COLLATERAL_PRICE: UFix64<N9> = UFix64::constant(148_370_000_000);

  #[test]
  fn exo_rebalance_collateral_to_usdc() -> Result<()> {
    let conv = ExoRebalanceConversion {
      collateral_rebalance_usd_price: COLLATERAL_PRICE,
      usdc_usd_price: UNDERPEGGED_USDC,
    };
    let usdc = conv.collateral_to_usdc(UFix64::new(10_000_000_000))?;
    assert_eq!(usdc, UFix64::new(1_485_185_185_185));
    Ok(())
  }

  #[test]
  fn exo_rebalance_usdc_to_collateral() -> Result<()> {
    let conv = ExoRebalanceConversion {
      collateral_rebalance_usd_price: COLLATERAL_PRICE,
      usdc_usd_price: UNDERPEGGED_USDC,
    };
    let coll = conv.usdc_to_collateral(UFix64::new(1_500_000_000_000))?;
    assert_eq!(coll, UFix64::new(10_079_530_902));
    Ok(())
  }

  const LST_SOL: UFix64<N9> = UFix64::constant(1_136_000_000);
  const SOL_REBALANCE_USD: UFix64<N9> = UFix64::constant(171_030_000_000);

  #[test]
  fn lst_rebalance_lst_to_usdc() -> Result<()> {
    let conv = LstRebalanceConversion {
      lst_sol_price: LST_SOL,
      sol_rebalance_usd_price: SOL_REBALANCE_USD,
      usdc_usd_price: UNDERPEGGED_USDC,
    };
    let usdc = conv.lst_to_usdc(UFix64::new(10_000_000_000))?;
    assert_eq!(usdc, UFix64::new(1_944_845_645_645));
    Ok(())
  }

  #[test]
  fn lst_rebalance_usdc_to_lst() -> Result<()> {
    let conv = LstRebalanceConversion {
      lst_sol_price: LST_SOL,
      sol_rebalance_usd_price: SOL_REBALANCE_USD,
      usdc_usd_price: UNDERPEGGED_USDC,
    };
    let lst = conv.usdc_to_lst(UFix64::new(200_000_000_000))?;
    assert_eq!(lst, UFix64::new(1_026_300_467));
    Ok(())
  }
}