hylo-core 2.7.3

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
use fix::prelude::*;

use super::controller::FeeExtract;
use super::interp::FixInterp;
use crate::collateral_ratio::CollateralRatio;
use crate::error::CoreError;

/// Downconvert CR from `N9` unsigned to `N5` signed for curve lookup.
///
/// # Errors
/// * `CollateralRatioConversion` on `i64` overflow.
pub fn narrow_cr(cr: UFix64<N9>) -> Result<IFix64<N5>, CoreError> {
  cr.convert::<N5>()
    .narrow::<i64>()
    .ok_or(CoreError::CollateralRatioConversion)
}

/// Reads a CR out of curve coordinates. Inverse of [`narrow_cr`].
///
/// # Errors
/// * `CollateralRatioConversion` on a negative CR.
pub fn cr_from_curve(cr: IFix64<N5>) -> Result<UFix64<N9>, CoreError> {
  cr.narrow::<u64>()
    .map(UFix64::convert::<N9>)
    .ok_or(CoreError::CollateralRatioConversion)
}

/// Interpolated fee curve controller.
/// Implementors define boundary behavior via `fee_inner`.
pub trait InterpolatedFeeController<const RES: usize> {
  /// Returns a reference to the underlying interpolator.
  fn curve(&self) -> &FixInterp<RES, N5>;

  /// Compute fee for collateral ratio from underlying curve.
  ///
  /// # Errors
  /// * Domain or arithmetic errors
  fn fee_inner(&self, cr: IFix64<N5>) -> Result<IFix64<N5>, CoreError>;

  /// Slope of the fee curve at the given collateral ratio.
  /// Zero on the flat regions outside the curve domain.
  ///
  /// # Errors
  /// * Domain or arithmetic errors
  fn fee_slope(&self, cr: IFix64<N5>) -> Result<IFix64<N5>, CoreError>;

  /// Fee rate for a collateral ratio from the underlying curve.
  ///
  /// # Errors
  /// * Domain or fee conversion
  fn fee_rate(&self, cr: CollateralRatio) -> Result<UFix64<N5>, CoreError> {
    self
      .fee_inner(cr.fee_curve_x())?
      .narrow()
      .ok_or(CoreError::InterpFeeConversion)
  }

  /// Applies the interpolated fee to an input amount.
  ///
  /// # Errors
  /// * Domain or fee extraction arithmetic
  fn apply_fee<InExp>(
    &self,
    cr: CollateralRatio,
    amount_in: UFix64<InExp>,
  ) -> Result<FeeExtract<InExp>, CoreError> {
    FeeExtract::new(self.fee_rate(cr)?, amount_in)
  }
}

#[derive(Clone)]
pub struct InterpolatedMintFees {
  curve: FixInterp<21, N5>,
}

impl InterpolatedMintFees {
  #[must_use]
  pub fn new(curve: FixInterp<21, N5>) -> InterpolatedMintFees {
    InterpolatedMintFees { curve }
  }
}

impl InterpolatedFeeController<21> for InterpolatedMintFees {
  fn curve(&self) -> &FixInterp<21, N5> {
    &self.curve
  }

  fn fee_inner(&self, cr: IFix64<N5>) -> Result<IFix64<N5>, CoreError> {
    let interp = self.curve();
    if cr < interp.x_min() {
      Err(CoreError::NoValidStablecoinMintFee)
    } else {
      interp.saturating_interpolate(cr)
    }
  }

  fn fee_slope(&self, cr: IFix64<N5>) -> Result<IFix64<N5>, CoreError> {
    let interp = self.curve();
    if cr < interp.x_min() {
      Err(CoreError::NoValidStablecoinMintFee)
    } else if cr > interp.x_max() || interp.is_saturated(cr)? {
      Ok(IFix64::zero())
    } else {
      interp.derivative(cr)
    }
  }
}

#[derive(Clone)]
pub struct InterpolatedRedeemFees {
  curve: FixInterp<11, N5>,
}

impl InterpolatedRedeemFees {
  #[must_use]
  pub fn new(curve: FixInterp<11, N5>) -> InterpolatedRedeemFees {
    InterpolatedRedeemFees { curve }
  }

  /// Fee rate at `cr`, saturating at `y_max`.
  ///
  /// # Errors
  /// * Interpolation or fee conversion
  #[cfg(feature = "offchain")]
  pub fn saturating_fee_rate(
    &self,
    cr: CollateralRatio,
  ) -> Result<UFix64<N5>, CoreError> {
    self
      .fee_inner(cr.fee_curve_x().min(self.curve.x_max()))?
      .narrow()
      .ok_or(CoreError::InterpFeeConversion)
  }
}

impl InterpolatedFeeController<11> for InterpolatedRedeemFees {
  fn curve(&self) -> &FixInterp<11, N5> {
    &self.curve
  }

  fn fee_inner(&self, cr: IFix64<N5>) -> Result<IFix64<N5>, CoreError> {
    let interp = self.curve();
    if cr < interp.x_min() {
      Ok(interp.y_min())
    } else if cr > interp.x_max() {
      Err(CoreError::NoValidStablecoinRedeemFee)
    } else {
      interp.interpolate(cr)
    }
  }

  fn fee_slope(&self, cr: IFix64<N5>) -> Result<IFix64<N5>, CoreError> {
    let interp = self.curve();
    if cr > interp.x_max() {
      Err(CoreError::NoValidStablecoinRedeemFee)
    } else if cr < interp.x_min() || interp.is_saturated(cr)? {
      Ok(IFix64::zero())
    } else {
      interp.derivative(cr)
    }
  }
}

#[cfg(test)]
mod tests {
  use anyhow::Result;
  use fix::typenum::Integer;
  use proptest::prelude::*;
  use proptest::test_runner::TestCaseResult;

  use super::*;
  use crate::collateral_ratio::CR;
  use crate::error::CoreError;
  use crate::fees::curves::{MINT_FEE_INV, REDEEM_FEE_LN};
  use crate::util::proptest::*;

  fn collateral_ratio() -> BoxedStrategy<CollateralRatio> {
    (0u64..4_000_000_000u64)
      .prop_map(|bits| CR::Finite(UFix64::new(bits)))
      .boxed()
  }

  fn redeem_domain_collateral_ratio() -> BoxedStrategy<CollateralRatio> {
    (0u64..=1_500_000_000u64)
      .prop_map(|bits| CR::Finite(UFix64::new(bits)))
      .boxed()
  }

  fn mint_fees() -> InterpolatedMintFees {
    let curve = FixInterp::from_points_unchecked(*MINT_FEE_INV);
    InterpolatedMintFees::new(curve)
  }

  fn redeem_fees() -> InterpolatedRedeemFees {
    let curve = FixInterp::from_points_unchecked(*REDEEM_FEE_LN);
    InterpolatedRedeemFees::new(curve)
  }

  fn assert_conservation<Exp: Integer>(
    extract: &FeeExtract<Exp>,
    amount: UFix64<Exp>,
    cr: CollateralRatio,
  ) -> TestCaseResult {
    prop_assert_eq!(
      extract
        .fees_extracted
        .checked_add(&extract.amount_remaining),
      Some(amount),
      "Fee conservation violated at CR {:?}",
      cr,
    );
    Ok(())
  }

  fn assert_mint_fee<Exp: Integer>(
    cr: CollateralRatio,
    amount: UFix64<Exp>,
  ) -> TestCaseResult {
    let fees = mint_fees();
    let cr_n5 = cr.fee_curve_x();
    match fees.apply_fee(cr, amount) {
      Ok(extract) => assert_conservation(&extract, amount, cr),
      Err(e) => {
        prop_assert!(
          cr_n5 < fees.curve().x_min()
            && e == CoreError::NoValidStablecoinMintFee,
          "Mint fee rejected in-domain CR {:?}: {}",
          cr,
          e,
        );
        Ok(())
      }
    }
  }

  fn assert_redeem_fee<Exp: Integer>(
    cr: CollateralRatio,
    amount: UFix64<Exp>,
  ) -> TestCaseResult {
    let fees = redeem_fees();
    let cr_n5 = cr.fee_curve_x();
    match fees.apply_fee(cr, amount) {
      Ok(extract) => assert_conservation(&extract, amount, cr),
      Err(e) => {
        prop_assert!(
          cr_n5 > fees.curve().x_max()
            && e == CoreError::NoValidStablecoinRedeemFee,
          "Redeem fee rejected in-domain CR {:?}: {}",
          cr,
          e,
        );
        Ok(())
      }
    }
  }

  #[test]
  fn redeem_fee_rejected_above_curve_domain() {
    let fees = redeem_fees();
    let cr = IFix64::<N5>::constant(150_001);
    assert_eq!(
      fees.fee_inner(cr).err(),
      Some(CoreError::NoValidStablecoinRedeemFee)
    );
    assert_eq!(
      fees.fee_slope(cr).err(),
      Some(CoreError::NoValidStablecoinRedeemFee)
    );
  }

  #[test]
  fn redeem_fee_maximal_at_domain_edge() -> Result<()> {
    let fees = redeem_fees();
    let cr = IFix64::<N5>::constant(150_000);
    assert_eq!(fees.fee_inner(cr)?, fees.curve().y_max());
    Ok(())
  }

  #[cfg(feature = "offchain")]
  #[test]
  fn saturating_fee_rate_equals_strict_inside_domain() -> Result<()> {
    let fees = redeem_fees();
    let cr = CR::Finite(UFix64::new(1_300_000_000));
    assert_eq!(fees.saturating_fee_rate(cr)?, fees.fee_rate(cr)?);
    Ok(())
  }

  #[cfg(feature = "offchain")]
  #[test]
  fn saturating_fee_rate_holds_edge_above_domain() -> Result<()> {
    let fees = redeem_fees();
    let edge = fees.fee_rate(CR::Finite(UFix64::new(1_500_000_000)))?;
    let above = CR::Finite(UFix64::new(3_000_000_000));
    assert_eq!(
      fees.fee_rate(above).err(),
      Some(CoreError::NoValidStablecoinRedeemFee)
    );
    assert_eq!(fees.saturating_fee_rate(above)?, edge);
    assert_eq!(fees.saturating_fee_rate(CR::Infinite)?, edge);
    Ok(())
  }

  #[test]
  fn mint_slope_zero_where_fee_pinned() -> Result<()> {
    let fees = mint_fees();
    let pinned = IFix64::<N5>::constant(150_001);
    assert_eq!(fees.fee_inner(pinned)?, fees.curve().y_min());
    assert_eq!(fees.fee_slope(pinned)?, IFix64::zero());
    let interior = IFix64::<N5>::constant(150_500);
    assert!(fees.fee_slope(interior)? < IFix64::zero());
    Ok(())
  }

  proptest! {
    #[test]
    fn mint_apply_fee_lst(
      cr in collateral_ratio(),
      amount in lst_amount(),
    ) {
      assert_mint_fee(cr, amount)?;
    }

    #[test]
    fn mint_apply_fee_token(
      cr in collateral_ratio(),
      amount in token_amount(),
    ) {
      assert_mint_fee(cr, amount)?;
    }

    #[test]
    fn redeem_apply_fee_lst(
      cr in collateral_ratio(),
      amount in lst_amount(),
    ) {
      assert_redeem_fee(cr, amount)?;
    }

    #[test]
    fn redeem_apply_fee_token(
      cr in collateral_ratio(),
      amount in token_amount(),
    ) {
      assert_redeem_fee(cr, amount)?;
    }

    #[test]
    fn mint_fee_decreases_with_cr(
      cr_a in collateral_ratio(),
      cr_b in collateral_ratio(),
      amount in lst_amount(),
    ) {
      let (cr_high, cr_low) = if cr_a > cr_b {
        (cr_a, cr_b)
      } else {
        (cr_b, cr_a)
      };
      prop_assume!(cr_high > cr_low);

      let fees = mint_fees();
      if let (Ok(high), Ok(low)) = (
        fees.apply_fee(cr_high, amount),
        fees.apply_fee(cr_low, amount),
      ) {
        prop_assert!(
          high.fees_extracted <= low.fees_extracted,
          "fee({cr_high:?}) = {:?} > fee({cr_low:?}) = {:?}",
          high.fees_extracted, low.fees_extracted,
        );
      } else {
        Err(TestCaseError::reject("CR below threshold"))?;
      }
    }

    #[test]
    fn redeem_fee_increases_with_cr(
      cr_a in redeem_domain_collateral_ratio(),
      cr_b in redeem_domain_collateral_ratio(),
      amount in lst_amount(),
    ) {
      let (cr_high, cr_low) = if cr_a > cr_b {
        (cr_a, cr_b)
      } else {
        (cr_b, cr_a)
      };
      prop_assume!(cr_high > cr_low);

      let fees = redeem_fees();
      if let (Ok(high), Ok(low)) = (
        fees.apply_fee(cr_high, amount),
        fees.apply_fee(cr_low, amount),
      ) {
        prop_assert!(
          high.fees_extracted >= low.fees_extracted,
          "fee({cr_high:?}) = {:?} < fee({cr_low:?}) = {:?}",
          high.fees_extracted, low.fees_extracted,
        );
      } else {
        Err(TestCaseError::reject("CR above redeem curve domain"))?;
      }
    }
  }
}