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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
use ethers::types::{I256, U256};
use eyre::{eyre, Result};
use fixedpointmath::{fixed, FixedPoint};

use crate::calculate_effective_share_reserves;

pub trait YieldSpace {
    /// The effective share reserves.
    fn ze(&self) -> Result<FixedPoint<U256>> {
        calculate_effective_share_reserves(self.z(), self.zeta())
    }

    /// The share reserves.
    fn z(&self) -> FixedPoint<U256>;

    /// The share adjustment.
    fn zeta(&self) -> I256;

    /// The bond reserves.
    fn y(&self) -> FixedPoint<U256>;

    /// The share price.
    fn c(&self) -> FixedPoint<U256>;

    /// The initial vault share price.
    fn mu(&self) -> FixedPoint<U256>;

    /// The YieldSpace time parameter.
    fn t(&self) -> FixedPoint<U256>;

    // The current spot price ignoring slippage.
    fn calculate_spot_price(&self) -> Result<FixedPoint<U256>> {
        if self.y() <= fixed!(0) {
            return Err(eyre!("expected y={} > 0", self.y()));
        }
        ((self.mu() * self.ze()?) / self.y()).pow(self.t())
    }

    /// Calculates the amount of bonds a user will receive from the pool by
    /// providing a specified amount of shares. We underestimate the amount of
    /// bonds out to prevent sandwiches.
    fn calculate_bonds_out_given_shares_in_down(
        &self,
        dz: FixedPoint<U256>,
    ) -> Result<FixedPoint<U256>> {
        // NOTE: We round k up to make the rhs of the equation larger.
        //
        // k = (c / µ) * (µ * ze)^(1 - t) + y^(1 - t)
        let k = self.k_up()?;

        // NOTE: We round z down to make the rhs of the equation larger.
        //
        // (µ * (ze + dz))^(1 - t)
        let mut ze = (self.mu() * (self.ze()? + dz)).pow(fixed!(1e18) - self.t())?;
        // (c / µ) * (µ * (ze + dz))^(1 - t)
        ze = self.c().mul_div_down(ze, self.mu());

        // NOTE: We round _y up to make the rhs of the equation larger.
        //
        // k - (c / µ) * (µ * (ze + dz))^(1 - t))^(1 / (1 - t)))
        if k < ze {
            return Err(eyre!("expected k={} >= ze={}", k, ze));
        }
        let mut y = k - ze;
        if y >= fixed!(1e18) {
            // Rounding up the exponent results in a larger result.
            y = y.pow(fixed!(1e18).div_up(fixed!(1e18) - self.t()))?;
        } else {
            // Rounding down the exponent results in a larger result.
            y = y.pow(fixed!(1e18) / (fixed!(1e18) - self.t()))?;
        }

        // Δy = y - (k - (c / µ) * (µ * (z + dz))^(1 - t))^(1 / (1 - t)))
        if self.y() < y {
            return Err(eyre!("expected y={} >= delta_y={}", self.y(), y));
        }
        Ok(self.y() - y)
    }

    /// Calculates the amount of shares a user must provide the pool to receive
    /// a specified amount of bonds. We overestimate the amount of shares in.
    fn calculate_shares_in_given_bonds_out_up(
        &self,
        dy: FixedPoint<U256>,
    ) -> Result<FixedPoint<U256>> {
        // NOTE: We round k up to make the lhs of the equation larger.
        //
        // k = (c / µ) * (µ * z)^(1 - t) + y^(1 - t)
        let k = self.k_up()?;

        // (y - dy)^(1 - t)
        if self.y() < dy {
            return Err(eyre!(
                "calculate_shares_in_given_bonds_out_up: y = {} < {} = dy",
                self.y(),
                dy,
            ));
        }
        let y = (self.y() - dy).pow(fixed!(1e18) - self.t())?;

        // NOTE: We round _z up to make the lhs of the equation larger.
        //
        // ((k - (y - dy)^(1 - t) ) / (c / µ))^(1 / (1 - t))
        if k < y {
            return Err(eyre!(
                "calculate_shares_in_given_bonds_out_up: k = {} < {} = y",
                k,
                y,
            ));
        }
        let mut _z = (k - y).mul_div_up(self.mu(), self.c());
        if _z >= fixed!(1e18) {
            // Rounding up the exponent results in a larger result.
            _z = _z.pow(fixed!(1e18).div_up(fixed!(1e18) - self.t()))?;
        } else {
            // Rounding down the exponent results in a larger result.
            _z = _z.pow(fixed!(1e18) / (fixed!(1e18) - self.t()))?;
        }
        // ((k - (y - dy)^(1 - t) ) / (c / µ))^(1 / (1 - t))) / µ
        _z = _z.div_up(self.mu());

        // Δz = (((k - (y - dy)^(1 - t) ) / (c / µ))^(1 / (1 - t))) / µ - ze
        if _z < self.ze()? {
            return Err(eyre!(
                "calculate_shares_in_given_bonds_out_up: _z = {} < {} = ze",
                _z,
                self.ze()?,
            ));
        }
        Ok(_z - self.ze()?)
    }

    /// Calculates the amount of shares a user must provide the pool to receive
    /// a specified amount of bonds. We underestimate the amount of shares in.
    fn calculate_shares_in_given_bonds_out_down(
        &self,
        dy: FixedPoint<U256>,
    ) -> Result<FixedPoint<U256>> {
        // NOTE: We round k down to make the lhs of the equation smaller.
        //
        // k = (c / µ) * (µ * ze)^(1 - t) + y^(1 - t)
        let k = self.k_down()?;

        // (y - dy)^(1 - t)
        let y = (self.y() - dy).pow(fixed!(1e18) - self.t())?;

        // NOTE: We round _ze down to make the lhs of the equation smaller.
        //
        // ((k - (y - dy)^(1 - t) ) / (c / µ))^(1 / (1 - t))
        let mut ze = (k - y).mul_div_down(self.mu(), self.c());
        if ze >= fixed!(1e18) {
            // Rounding down the exponent results in a smaller result.
            ze = ze.pow(fixed!(1e18) / (fixed!(1e18) - self.t()))?;
        } else {
            // Rounding up the exponent results in a smaller result.
            ze = ze.pow(fixed!(1e18).div_up(fixed!(1e18) - self.t()))?;
        }
        // ((k - (y - dy)^(1 - t) ) / (c / µ))^(1 / (1 - t))) / µ
        ze /= self.mu();

        // Δz = (((k - (y - dy)^(1 - t) ) / (c / µ))^(1 / (1 - t))) / µ - ze
        Ok(ze - self.ze()?)
    }

    /// Calculates the amount of shares a user will receive from the pool by
    /// providing a specified amount of bonds. This function reverts if an
    /// integer overflow or underflow occurs. We underestimate the amount of
    /// shares out.
    fn calculate_shares_out_given_bonds_in_down(
        &self,
        dy: FixedPoint<U256>,
    ) -> Result<FixedPoint<U256>> {
        // NOTE: We round k up to make the rhs of the equation larger.
        //
        // k = (c / µ) * (µ * ze)^(1 - t) + y^(1 - t)
        let k = self.k_up()?;

        // (y + dy)^(1 - t)
        let y = (self.y() + dy).pow(fixed!(1e18) - self.t())?;

        // If k is less than y, we return with a failure flag.
        if k < y {
            return Err(eyre!(
                "calculate_shares_out_given_bonds_in_down: k = {} < {} = y",
                k,
                y
            ));
        }

        // NOTE: We round _ze up to make the rhs of the equation larger.
        //
        // ((k - (y + dy)^(1 - t)) / (c / µ))^(1 / (1 - t)))
        let mut ze = (k - y).mul_div_up(self.mu(), self.c());
        if ze >= fixed!(1e18) {
            // Rounding the exponent up results in a larger outcome.
            ze = ze.pow(fixed!(1e18).div_up(fixed!(1e18) - self.t()))?;
        } else {
            // Rounding the exponent down results in a larger outcome.
            ze = ze.pow(fixed!(1e18) / (fixed!(1e18) - self.t()))?;
        }
        // ((k - (y + dy)^(1 - t) ) / (c / µ))^(1 / (1 - t))) / µ
        ze = ze.div_up(self.mu());

        // Δz = ze - ((k - (y + dy)^(1 - t) ) / (c / µ))^(1 / (1 - t)) / µ
        if self.ze()? > ze {
            Ok(self.ze()? - ze)
        } else {
            Ok(fixed!(0))
        }
    }

    /// Calculates the share payment required to purchase the maximum
    /// amount of bonds from the pool.
    fn calculate_max_buy_shares_in(&self) -> Result<FixedPoint<U256>> {
        // We solve for the maximum buy using the constraint that the pool's
        // spot price can never exceed 1. We do this by noting that a spot price
        // of 1, ((mu * ze) / y) ** tau = 1, implies that mu * ze = y. This
        // simplifies YieldSpace to:
        //
        // k = ((c / mu) + 1) * (mu * ze') ** (1 - tau),
        //
        // This gives us the maximum share reserves of:
        //
        // ze' = (1 / mu) * (k / ((c / mu) + 1)) ** (1 / (1 - tau)).
        let k = self.k_down()?;
        let mut optimal_ze = k.div_down(self.c().div_up(self.mu()) + fixed!(1e18));
        if optimal_ze >= fixed!(1e18) {
            // Rounding the exponent up results in a larger outcome.
            optimal_ze = optimal_ze.pow(fixed!(1e18).div_down(fixed!(1e18) - self.t()))?;
        } else {
            // Rounding the exponent down results in a larger outcome.
            optimal_ze = optimal_ze.pow(fixed!(1e18) / (fixed!(1e18) - self.t()))?;
        }
        optimal_ze = optimal_ze.div_down(self.mu());

        // The optimal trade size is given by dz = ze' - ze. If the calculation
        // underflows, we return a failure flag.
        if optimal_ze >= self.ze()? {
            Ok(optimal_ze - self.ze()?)
        } else {
            Err(eyre!(
                "calculate_max_buy_shares_in: optimal_ze = {} < {} = ze",
                optimal_ze,
                self.ze()?,
            ))
        }
    }

    /// Calculates the maximum amount of bonds that can be purchased with the
    /// specified reserves. We round so that the max buy amount is
    /// underestimated.
    fn calculate_max_buy_bonds_out(&self) -> Result<FixedPoint<U256>> {
        // We solve for the maximum buy using the constraint that the pool's
        // spot price can never exceed 1. We do this by noting that a spot price
        // of 1, (mu * ze) / y ** tau = 1, implies that mu * ze = y. This
        // simplifies YieldSpace to k = ((c / mu) + 1) * y' ** (1 - tau), and
        // gives us the maximum bond reserves of
        // y' = (k / ((c / mu) + 1)) ** (1 / (1 - tau)) and the maximum share
        // reserves of ze' = y/mu.
        let k = self.k_up()?;
        let mut optimal_y = k.div_up(self.c() / self.mu() + fixed!(1e18));
        if optimal_y >= fixed!(1e18) {
            // Rounding the exponent up results in a larger outcome.
            optimal_y = optimal_y.pow(fixed!(1e18).div_up(fixed!(1e18) - self.t()))?;
        } else {
            // Rounding the exponent down results in a larger outcome.
            optimal_y = optimal_y.pow(fixed!(1e18) / (fixed!(1e18) - self.t()))?;
        }

        // The optimal trade size is given by dy = y - y'. If the calculation
        // underflows, we return a failure flag.
        if self.y() >= optimal_y {
            Ok(self.y() - optimal_y)
        } else {
            Err(eyre!(
                "calculate_max_buy_bonds_out: y = {} < {} = optimal_y",
                self.y(),
                optimal_y,
            ))
        }
    }

    /// Calculates the maximum amount of bonds that can be sold with the
    /// specified reserves. We round so that the max sell amount is
    /// underestimated.
    fn calculate_max_sell_bonds_in(&self, mut z_min: FixedPoint<U256>) -> Result<FixedPoint<U256>> {
        // If the share adjustment is negative, the minimum share reserves is
        // given by `z_min - zeta`, which ensures that the share reserves never
        // fall below the minimum share reserves. Otherwise, the minimum share
        // reserves is just zMin.
        if self.zeta() < I256::zero() {
            z_min += FixedPoint::try_from(-self.zeta())?;
        }

        // We solve for the maximum sell using the constraint that the pool's
        // share reserves can never fall below the minimum share reserves zMin.
        // Substituting z = zMin simplifies YieldSpace to
        // k = (c / mu) * (mu * (zMin)) ** (1 - tau) + y' ** (1 - tau), and
        // gives us the maximum bond reserves of
        // y' = (k - (c / mu) * (mu * (zMin)) ** (1 - tau)) ** (1 / (1 - tau)).
        let k = self.k_down()?;
        let mut optimal_y = k - self.c().mul_div_up(
            self.mu().mul_up(z_min).pow(fixed!(1e18) - self.t())?,
            self.mu(),
        );
        if optimal_y >= fixed!(1e18) {
            // Rounding the exponent down results in a smaller outcome.
            optimal_y = optimal_y.pow(fixed!(1e18) / (fixed!(1e18) - self.t()))?;
        } else {
            // Rounding the exponent up results in a smaller outcome.
            optimal_y = optimal_y.pow(fixed!(1e18).div_up(fixed!(1e18) - self.t()))?;
        }

        // The optimal trade size is given by dy = y' - y. If this subtraction
        // will underflow, we return a failure flag.
        if optimal_y >= self.y() {
            Ok(optimal_y - self.y())
        } else {
            Err(eyre!(
                "calculate_max_sell_bonds_in: optimal_y = {} < {} = y",
                optimal_y,
                self.y(),
            ))
        }
    }

    /// Calculates the YieldSpace invariant k. This invariant is given by:
    ///
    /// k = (c / µ) * (µ * ze)^(1 - t) + y^(1 - t)
    ///
    /// This variant of the calculation overestimates the result.
    fn k_up(&self) -> Result<FixedPoint<U256>> {
        Ok(self.c().mul_div_up(
            (self.mu().mul_up(self.ze()?)).pow(fixed!(1e18) - self.t())?,
            self.mu(),
        ) + self.y().pow(fixed!(1e18) - self.t())?)
    }

    /// Calculates the YieldSpace invariant k. This invariant is given by:
    ///
    /// k = (c / µ) * (µ * ze)^(1 - t) + y^(1 - t)
    ///
    /// This variant of the calculation underestimates the result.
    fn k_down(&self) -> Result<FixedPoint<U256>> {
        Ok(self.c().mul_div_down(
            (self.mu() * self.ze()?).pow(fixed!(1e18) - self.t())?,
            self.mu(),
        ) + self.y().pow(fixed!(1e18) - self.t())?)
    }
}

#[cfg(test)]
mod tests {
    use std::panic;

    use hyperdrive_test_utils::{chain::TestChain, constants::FAST_FUZZ_RUNS};
    use rand::{thread_rng, Rng};

    use super::*;
    use crate::State;

    #[tokio::test]
    async fn fuzz_calculate_bonds_out_given_shares_in() -> Result<()> {
        let chain = TestChain::new().await?;

        // Fuzz the rust and solidity implementations against each other.
        let mut rng = thread_rng();
        for _ in 0..*FAST_FUZZ_RUNS {
            let state = rng.gen::<State>();
            let in_ = rng.gen::<FixedPoint<U256>>();
            // We need to catch panics because of overflows.
            let actual =
                panic::catch_unwind(|| state.calculate_bonds_out_given_shares_in_down(in_));
            match chain
                .mock_yield_space_math()
                .calculate_bonds_out_given_shares_in_down(
                    state.ze()?.into(),
                    state.y().into(),
                    in_.into(),
                    (fixed!(1e18) - state.t()).into(),
                    state.c().into(),
                    state.mu().into(),
                )
                .call()
                .await
            {
                Ok(expected) => assert_eq!(actual.unwrap().unwrap(), FixedPoint::from(expected)),
                Err(_) => assert!(actual.is_err() || actual.unwrap().is_err()),
            }
        }

        Ok(())
    }

    #[tokio::test]
    async fn fuzz_calculate_shares_in_given_bonds_out_up() -> Result<()> {
        let chain = TestChain::new().await?;

        // Fuzz the rust and solidity implementations against each other.
        let mut rng = thread_rng();
        for _ in 0..*FAST_FUZZ_RUNS {
            let state = rng.gen::<State>();
            let in_ = rng.gen::<FixedPoint<U256>>();
            let actual = state.calculate_shares_in_given_bonds_out_up(in_);
            match chain
                .mock_yield_space_math()
                .calculate_shares_in_given_bonds_out_up(
                    state.ze()?.into(),
                    state.y().into(),
                    in_.into(),
                    (fixed!(1e18) - state.t()).into(),
                    state.c().into(),
                    state.mu().into(),
                )
                .call()
                .await
            {
                Ok(expected) => {
                    assert_eq!(actual.unwrap(), FixedPoint::from(expected));
                }
                Err(_) => assert!(actual.is_err()),
            }
        }

        Ok(())
    }

    #[tokio::test]
    async fn fuzz_calculate_shares_in_given_bonds_out_down() -> Result<()> {
        let chain = TestChain::new().await?;

        // Fuzz the rust and solidity implementations against each other.
        let mut rng = thread_rng();
        for _ in 0..*FAST_FUZZ_RUNS {
            let state = rng.gen::<State>();
            let out = rng.gen::<FixedPoint<U256>>();
            let actual =
                panic::catch_unwind(|| state.calculate_shares_in_given_bonds_out_down(out));
            match chain
                .mock_yield_space_math()
                .calculate_shares_in_given_bonds_out_down(
                    state.ze()?.into(),
                    state.y().into(),
                    out.into(),
                    (fixed!(1e18) - state.t()).into(),
                    state.c().into(),
                    state.mu().into(),
                )
                .call()
                .await
            {
                Ok(expected) => {
                    assert_eq!(actual.unwrap().unwrap(), FixedPoint::from(expected));
                }
                Err(_) => assert!(actual.is_err() || actual.unwrap().is_err()),
            }
        }

        Ok(())
    }

    #[tokio::test]
    async fn fuzz_calculate_shares_out_given_bonds_in_down() -> Result<()> {
        let chain = TestChain::new().await?;

        // Fuzz the rust and solidity implementations against each other.
        let mut rng = thread_rng();
        for _ in 0..*FAST_FUZZ_RUNS {
            let state = rng.gen::<State>();
            let in_ = rng.gen::<FixedPoint<U256>>();
            let actual = state.calculate_shares_out_given_bonds_in_down(in_);
            match chain
                .mock_yield_space_math()
                .calculate_shares_out_given_bonds_in_down_safe(
                    state.ze()?.into(),
                    state.y().into(),
                    in_.into(),
                    (fixed!(1e18) - state.t()).into(),
                    state.c().into(),
                    state.mu().into(),
                )
                .call()
                .await
            {
                Ok((expected_out, expected_status)) => {
                    assert_eq!(actual.is_ok(), expected_status);
                    assert_eq!(actual.unwrap_or(fixed!(0)), FixedPoint::from(expected_out));
                }
                Err(_) => assert!(actual.is_err()),
            }
        }

        Ok(())
    }

    #[tokio::test]
    async fn fuzz_calculate_max_buy_shares_in() -> Result<()> {
        let chain = TestChain::new().await?;

        // Fuzz the rust and solidity implementations against each other.
        let mut rng = thread_rng();
        for _ in 0..*FAST_FUZZ_RUNS {
            let state = rng.gen::<State>();
            let actual = state.calculate_max_buy_shares_in();
            match chain
                .mock_yield_space_math()
                .calculate_max_buy_shares_in_safe(
                    state.ze()?.into(),
                    state.y().into(),
                    (fixed!(1e18) - state.t()).into(),
                    state.c().into(),
                    state.mu().into(),
                )
                .call()
                .await
            {
                Ok((expected_out, expected_status)) => {
                    assert_eq!(actual.is_ok(), expected_status);
                    assert_eq!(actual.unwrap_or(fixed!(0)), FixedPoint::from(expected_out));
                }
                Err(_) => assert!(actual.is_err()),
            }
        }

        Ok(())
    }

    #[tokio::test]
    async fn fuzz_calculate_max_buy_bounds_out() -> Result<()> {
        let chain = TestChain::new().await?;

        // Fuzz the rust and solidity implementations against each other.
        let mut rng = thread_rng();
        for _ in 0..*FAST_FUZZ_RUNS {
            let state = rng.gen::<State>();
            let actual = state.calculate_max_buy_bonds_out();
            match chain
                .mock_yield_space_math()
                .calculate_max_buy_bonds_out_safe(
                    state.ze()?.into(),
                    state.y().into(),
                    (fixed!(1e18) - state.t()).into(),
                    state.c().into(),
                    state.mu().into(),
                )
                .call()
                .await
            {
                Ok((expected_out, expected_status)) => {
                    assert_eq!(actual.is_ok(), expected_status);
                    assert_eq!(actual.unwrap_or(fixed!(0)), FixedPoint::from(expected_out));
                }
                Err(_) => assert!(actual.is_err()),
            }
        }

        Ok(())
    }

    #[tokio::test]
    async fn fuzz_calculate_max_sell_bonds_in() -> Result<()> {
        let chain = TestChain::new().await?;

        // Fuzz the rust and solidity implementations against each other.
        let mut rng = thread_rng();
        for _ in 0..*FAST_FUZZ_RUNS {
            let state = rng.gen::<State>();
            let z_min = rng.gen::<FixedPoint<U256>>();
            let actual = panic::catch_unwind(|| state.calculate_max_sell_bonds_in(z_min));
            match chain
                .mock_yield_space_math()
                .calculate_max_sell_bonds_in_safe(
                    state.z().into(),
                    state.zeta(),
                    state.y().into(),
                    z_min.into(),
                    (fixed!(1e18) - state.t()).into(),
                    state.c().into(),
                    state.mu().into(),
                )
                .call()
                .await
            {
                Ok((expected_out, expected_status)) => {
                    let actual = actual.unwrap();
                    assert_eq!(actual.is_ok(), expected_status);
                    assert_eq!(actual.unwrap_or(fixed!(0)), FixedPoint::from(expected_out));
                }
                Err(e) => assert!(actual.is_err() || actual.unwrap().is_err()),
            }
        }

        Ok(())
    }

    #[tokio::test]
    async fn fuzz_k_down() -> Result<()> {
        let chain = TestChain::new().await?;

        // Fuzz the rust and solidity implementations against each other.
        let mut rng = thread_rng();
        for _ in 0..*FAST_FUZZ_RUNS {
            let state = rng.gen::<State>();
            let actual = state.k_down();
            match chain
                .mock_yield_space_math()
                .k_down(
                    state.ze()?.into(),
                    state.y().into(),
                    (fixed!(1e18) - state.t()).into(),
                    state.c().into(),
                    state.mu().into(),
                )
                .call()
                .await
            {
                Ok(expected) => assert_eq!(actual.unwrap(), FixedPoint::from(expected)),
                Err(_) => assert!(actual.is_err()),
            }
        }

        Ok(())
    }

    #[tokio::test]
    async fn fuzz_k_up() -> Result<()> {
        let chain = TestChain::new().await?;

        // Fuzz the rust and solidity implementations against each other.
        let mut rng = thread_rng();
        for _ in 0..*FAST_FUZZ_RUNS {
            let state = rng.gen::<State>();
            let actual = state.k_up();
            match chain
                .mock_yield_space_math()
                .k_up(
                    state.ze()?.into(),
                    state.y().into(),
                    (fixed!(1e18) - state.t()).into(),
                    state.c().into(),
                    state.mu().into(),
                )
                .call()
                .await
            {
                Ok(expected) => assert_eq!(actual.unwrap(), FixedPoint::from(expected)),
                Err(_) => assert!(actual.is_err()),
            }
        }

        Ok(())
    }
}