defituna-core 3.6.1

DefiTuna core library
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
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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
#![allow(clippy::collapsible_else_if)]
#![allow(clippy::too_many_arguments)]

use crate::{calculate_tuna_protocol_fee, sqrt_price_x64_to_price_x64, COMPUTED_AMOUNT, HUNDRED_PERCENT, INVALID_ARGUMENTS};
use fixed::types::U64F64;
use fusionamm_core::{
    get_amount_a_from_liquidity, get_amount_b_from_liquidity, get_amounts_from_liquidity, get_liquidity_from_amount_a, get_liquidity_from_amount_b,
    get_liquidity_from_amounts, position_ratio_x64, tick_index_to_sqrt_price, try_apply_swap_fee, CoreError, ARITHMETIC_OVERFLOW, Q64_RESOLUTION,
};

#[cfg(feature = "wasm")]
use fusionamm_macros::wasm_expose;

#[derive(Debug, Copy, Clone, PartialEq)]
#[cfg_attr(feature = "wasm", wasm_expose)]
pub struct LiquidationPrices {
    pub lower: f64,
    pub upper: f64,
}

///
/// Calculates the liquidation prices inside the position's range.
///
/// t - liquidation threshold
/// Dx - debt x
/// Dy - debt y
/// Lx - leftovers x
/// Ly - leftovers y
/// √P = x - current price
/// √Pu = u - upper sqrt price
/// √Pl = l - lower sqrt price
/// L - liquidity
///
/// t = (Dx⋅P + Dy) / (Δx⋅P + Lx⋅P + Δy + Ly), where
///   Δx = L⋅(1/x - 1/u)
///   Δy = L⋅(x - l)
///
/// x1,2 = ...
///
/// # Parameters
/// - `lower_sqrt_price`: The lower square root price boundary.
/// - `upper_sqrt_price`: The upper square root price boundary.
/// - `liquidity`: The liquidity provided by the user.
/// - `leftovers_a`: The amount of leftovers A in the existing position.
/// - `leftovers_b`: The amount of leftovers B in the existing position*
/// - `debt_a`: The amount of tokens A borrowed.
/// - `debt_b`: The amount of tokens B borrowed.
/// - `liquidation_threshold`: The liquidation threshold of the liquidator.
///
/// # Returns
/// - `LiquidationPrices`: An object containing lower/upper liquidation prices.
fn compute_liquidation_prices_inside(
    lower_sqrt_price: u128,
    upper_sqrt_price: u128,
    liquidity: u128,
    leftovers_a: u64,
    leftovers_b: u64,
    debt_a: u64,
    debt_b: u64,
    liquidation_threshold: u32,
) -> Result<LiquidationPrices, CoreError> {
    let liquidation_threshold_f = liquidation_threshold as f64 / HUNDRED_PERCENT as f64;
    let liquidity_f = liquidity as f64;
    let lower_sqrt_price_f = lower_sqrt_price as f64 / Q64_RESOLUTION;
    let upper_sqrt_price_f = upper_sqrt_price as f64 / Q64_RESOLUTION;

    let a = debt_a as f64 + liquidation_threshold_f * (liquidity_f / upper_sqrt_price_f - leftovers_a as f64);
    let b = -2.0 * liquidation_threshold_f * liquidity_f;
    let c = debt_b as f64 + liquidation_threshold_f * (liquidity_f * lower_sqrt_price_f - leftovers_b as f64);
    let d = b * b - 4.0 * a * c;

    let mut lower_liquidation_sqrt_price = 0.0;
    let mut upper_liquidation_sqrt_price = 0.0;

    if d >= 0.0 && a > 0.0 {
        lower_liquidation_sqrt_price = (-b - d.sqrt()) / (2.0 * a);
        upper_liquidation_sqrt_price = (-b + d.sqrt()) / (2.0 * a);
        if lower_liquidation_sqrt_price < 0.0 || lower_liquidation_sqrt_price < lower_sqrt_price_f {
            lower_liquidation_sqrt_price = 0.0;
        }
        if upper_liquidation_sqrt_price < 0.0 || upper_liquidation_sqrt_price > upper_sqrt_price_f {
            upper_liquidation_sqrt_price = 0.0;
        }
    }

    Ok(LiquidationPrices {
        lower: lower_liquidation_sqrt_price * lower_liquidation_sqrt_price,
        upper: upper_liquidation_sqrt_price * upper_liquidation_sqrt_price,
    })
}

/// Calculates a liquidation price for the outside range (above OR under).
///
/// liquidation_threshold = total_debt / (total_balance + leftovers)
///
/// t - liquidation threshold
/// P - liquidation price
/// Dx - debt x
/// Dy - debt y
/// Lx - leftovers x
/// Ly - leftovers y
/// X - amount of x tokens
/// Y - amount of y tokens
///
/// Lower liquidation price:
/// t = (Dx + Dy / P) / (X + Lx + Ly/P)  =>  P = (Dy - t⋅Ly) / (t⋅(X+Lx) - Dx)
///
/// Upper liquidation price:
/// t = (Dx⋅P + Dy) / (Y + Lx⋅P + Ly)  =>  P = (t⋅(Y + Ly) - Dy) / (Dx - t⋅Lx)
///
/// # Parameters
/// - `amount_a`: The amount of tokens A at the boundary price.
/// - `amount_b`: The amount of tokens B at the boundary price.
/// - `leftovers_a`: The amount of leftovers A.
/// - `leftovers_b`: The amount of leftovers B.
/// - `debt_a`: The amount of tokens A borrowed.
/// - `debt_b`: The amount of tokens B borrowed.
/// - `liquidation_threshold`: - The liquidation threshold of the liquidator.
///
/// # Returns
/// The calculated liquidation price.
fn calculate_liquidation_outside(
    amount_a: u64,
    amount_b: u64,
    leftovers_a: u64,
    leftovers_b: u64,
    debt_a: u64,
    debt_b: u64,
    liquidation_threshold: u32,
) -> Result<f64, CoreError> {
    let liquidation_threshold_f = liquidation_threshold as f64 / HUNDRED_PERCENT as f64;

    if amount_a == 0 && amount_b == 0 {
        Ok(0.0)
    } else if amount_a > 0 && amount_b == 0 {
        // Lower liquidation price
        let numerator = debt_b as f64 - liquidation_threshold_f * leftovers_b as f64;
        let denominator = liquidation_threshold_f * (amount_a as f64 + leftovers_a as f64) - debt_a as f64;
        Ok(numerator / denominator)
    } else if amount_a == 0 && amount_b > 0 {
        // Upper liquidation price
        let numerator = liquidation_threshold_f * (amount_b as f64 + leftovers_b as f64) - debt_b as f64;
        let denominator = debt_a as f64 - liquidation_threshold_f * leftovers_a as f64;
        if denominator == 0.0 {
            return Ok(0.0);
        }
        Ok(numerator / denominator)
    } else {
        Err(INVALID_ARGUMENTS)
    }
}

/// Calculates the liquidation prices outside the position's range (above AND under).
///
/// # Parameters
/// - `lower_sqrt_price`: The lower square root price boundary.
/// - `upper_sqrt_price`: The upper square root price boundary.
/// - `liquidity`: The liquidity provided by the user.
/// - `leftovers_a`: The amount of leftovers A.
/// - `leftovers_b`: The amount of leftovers B.
/// - `debt_a`: The amount of tokens A borrowed.
/// - `debt_b`: The amount of tokens B borrowed.
/// - `liquidation_threshold`: The liquidation threshold of the liquidator.
///
/// # Returns
/// - `LiquidationPrices`: An object containing lower/upper liquidation prices.
fn compute_liquidation_prices_outside(
    lower_sqrt_price: u128,
    upper_sqrt_price: u128,
    liquidity: u128,
    leftovers_a: u64,
    leftovers_b: u64,
    debt_a: u64,
    debt_b: u64,
    liquidation_threshold: u32,
) -> Result<LiquidationPrices, CoreError> {
    let amount_a = get_amount_a_from_liquidity(liquidity, lower_sqrt_price, upper_sqrt_price, false).unwrap_or(u64::MAX);
    let amount_b = get_amount_b_from_liquidity(liquidity, lower_sqrt_price, upper_sqrt_price, false).unwrap_or(u64::MAX);

    let mut liquidation_price_for_a = calculate_liquidation_outside(amount_a, 0, leftovers_a, leftovers_b, debt_a, debt_b, liquidation_threshold)?;
    let mut liquidation_price_for_b = calculate_liquidation_outside(0, amount_b, leftovers_a, leftovers_b, debt_a, debt_b, liquidation_threshold)?;

    if liquidation_price_for_a < 0.0 || liquidation_price_for_a > (lower_sqrt_price as f64 / Q64_RESOLUTION).powf(2.0) {
        liquidation_price_for_a = 0.0;
    }
    if liquidation_price_for_b < 0.0 || liquidation_price_for_b < (upper_sqrt_price as f64 / Q64_RESOLUTION).powf(2.0) {
        liquidation_price_for_b = 0.0;
    }

    Ok(LiquidationPrices {
        lower: liquidation_price_for_a,
        upper: liquidation_price_for_b,
    })
}

/// Computes the liquidation prices for an existing position.
///
/// # Parameters
/// - `tick_lower_index`: The lower tick index of the position.
/// - `tick_upper_index`: The upper tick index of the position.
/// - `leftovers_a`: The amount of leftovers A in the position.
/// - `leftovers_a`: The amount of leftovers B in the position.
/// - `liquidity`: Liquidity of the position.
/// - `debt_a`: The amount of tokens A borrowed.
/// - `debt_b`: The amount of tokens B borrowed.
/// - `liquidation_threshold`: The liquidation threshold of the market.
///
/// # Returns
/// - `LiquidationPrices`: An object containing lower/upper liquidation prices.
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn get_lp_position_liquidation_prices(
    tick_lower_index: i32,
    tick_upper_index: i32,
    liquidity: u128,
    leftovers_a: u64,
    leftovers_b: u64,
    debt_a: u64,
    debt_b: u64,
    liquidation_threshold: u32,
) -> Result<LiquidationPrices, CoreError> {
    if tick_lower_index >= tick_upper_index {
        return Err("Incorrect position tick index order: the lower tick must be less then the upper tick.");
    }

    if liquidation_threshold >= HUNDRED_PERCENT {
        return Err("Incorrect liquidation_threshold value.");
    }

    let lower_sqrt_price = tick_index_to_sqrt_price(tick_lower_index);
    let upper_sqrt_price = tick_index_to_sqrt_price(tick_upper_index);

    let liquidation_price_inside = compute_liquidation_prices_inside(
        lower_sqrt_price,
        upper_sqrt_price,
        liquidity,
        leftovers_a,
        leftovers_b,
        debt_a,
        debt_b,
        liquidation_threshold,
    )?;

    let liquidation_price_outside = compute_liquidation_prices_outside(
        lower_sqrt_price,
        upper_sqrt_price,
        liquidity,
        leftovers_a,
        leftovers_b,
        debt_a,
        debt_b,
        liquidation_threshold,
    )?;

    let lower_liquidation_price = if liquidation_price_inside.lower > 0.0 {
        liquidation_price_inside.lower
    } else {
        liquidation_price_outside.lower
    };

    let upper_liquidation_price = if liquidation_price_inside.upper > 0.0 {
        liquidation_price_inside.upper
    } else {
        liquidation_price_outside.upper
    };

    Ok(LiquidationPrices {
        lower: lower_liquidation_price,
        upper: upper_liquidation_price,
    })
}

#[derive(Debug, Copy, Clone, PartialEq)]
#[cfg_attr(feature = "wasm", wasm_expose)]
pub struct IncreaseLpPositionQuoteArgs {
    /// Collateral in token A or COMPUTED_AMOUNT.
    pub collateral_a: u64,
    /// Collateral in token B or COMPUTED_AMOUNT.
    pub collateral_b: u64,
    /// Amount to borrow in token A. Must be set to COMPUTED_AMOUNT if collateral_a is COMPUTED_AMOUNT.
    pub borrow_a: u64,
    /// Amount to borrow in token B. Must be set to COMPUTED_AMOUNT if collateral_b is COMPUTED_AMOUNT.
    pub borrow_b: u64,
    /// Protocol fee rate from a market account represented as hundredths of a basis point (0.01% = 100).
    pub protocol_fee_rate: u16,
    /// Protocol fee rate from a market account represented as hundredths of a basis point (0.01% = 100).
    pub protocol_fee_rate_on_collateral: u16,
    /// The swap fee rate of a pool denominated in 1e6.
    pub swap_fee_rate: u16,
    /// Current sqrt price.
    pub sqrt_price: u128,
    /// Position lower tick index.
    pub tick_lower_index: i32,
    /// Position upper tick index.
    pub tick_upper_index: i32,
    /// The liquidation threshold of the market.
    pub liquidation_threshold: u32,
}

#[derive(Debug, Copy, Clone, PartialEq)]
#[cfg_attr(feature = "wasm", wasm_expose)]
pub struct IncreaseLpPositionQuoteResult {
    pub collateral_a: u64,
    pub collateral_b: u64,
    pub borrow_a: u64,
    pub borrow_b: u64,
    pub total_a: u64,
    pub total_b: u64,
    pub swap_input: u64,
    pub swap_output: u64,
    pub swap_a_to_b: bool,
    pub protocol_fee_a: u64,
    pub protocol_fee_b: u64,
    pub liquidity: u128,
    pub leverage: f64,
    pub liquidation_lower_price: f64,
    pub liquidation_upper_price: f64,
}

#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn get_increase_lp_position_quote(args: IncreaseLpPositionQuoteArgs) -> Result<IncreaseLpPositionQuoteResult, CoreError> {
    let mut collateral_a = args.collateral_a;
    let mut collateral_b = args.collateral_b;
    let mut borrow_a = args.borrow_a;
    let mut borrow_b = args.borrow_b;
    let sqrt_price = args.sqrt_price;

    if args.tick_lower_index >= args.tick_upper_index {
        return Err("Incorrect position tick index order: the lower tick must be less than the upper tick.");
    }

    if collateral_a == COMPUTED_AMOUNT && collateral_b == COMPUTED_AMOUNT {
        return Err("Both collateral amounts can't be set to COMPUTED_AMOUNT");
    }

    let lower_sqrt_price = tick_index_to_sqrt_price(args.tick_lower_index);
    let upper_sqrt_price = tick_index_to_sqrt_price(args.tick_upper_index);

    if collateral_a == COMPUTED_AMOUNT {
        if sqrt_price <= lower_sqrt_price {
            return Err("sqrtPrice must be greater than lower_sqrt_price if collateral A is computed.");
        } else if sqrt_price < upper_sqrt_price {
            let liquidity = get_liquidity_from_amount_b(collateral_b + borrow_b, lower_sqrt_price, sqrt_price)?;
            let amount_a = get_amount_a_from_liquidity(liquidity, sqrt_price, upper_sqrt_price, false)?;
            collateral_a = ((amount_a as u128 * collateral_b as u128) / (collateral_b as u128 + borrow_b as u128)) as u64;
            borrow_a = amount_a - collateral_a;
        } else {
            collateral_a = 0;
            borrow_a = 0;
        }
    } else if collateral_b == COMPUTED_AMOUNT {
        if sqrt_price <= lower_sqrt_price {
            collateral_b = 0;
            borrow_b = 0;
        } else if sqrt_price < upper_sqrt_price {
            let liquidity = get_liquidity_from_amount_a(collateral_a + borrow_a, sqrt_price, upper_sqrt_price)?;
            let amount_b = get_amount_b_from_liquidity(liquidity, lower_sqrt_price, sqrt_price, false)?;
            collateral_b = ((amount_b as u128 * collateral_a as u128) / (collateral_a as u128 + borrow_a as u128)) as u64;
            borrow_b = amount_b - collateral_b;
        } else {
            return Err("sqrtPrice must be less than upper_sqrt_price if collateral B is computed.");
        }
    }

    let protocol_fee_a = calculate_tuna_protocol_fee(collateral_a, borrow_a, args.protocol_fee_rate_on_collateral, args.protocol_fee_rate);
    let provided_a = collateral_a + borrow_a - protocol_fee_a;

    let protocol_fee_b = calculate_tuna_protocol_fee(collateral_b, borrow_b, args.protocol_fee_rate_on_collateral, args.protocol_fee_rate);
    let provided_b = collateral_b + borrow_b - protocol_fee_b;

    let mut swap_input = 0;
    let mut swap_output = 0;
    let mut swap_a_to_b = false;
    let mut total_a = provided_a;
    let mut total_b = provided_b;

    if args.collateral_a != COMPUTED_AMOUNT && args.collateral_b != COMPUTED_AMOUNT {
        let position_ratio = position_ratio_x64(sqrt_price.into(), args.tick_lower_index, args.tick_upper_index);
        let ratio_a = position_ratio.ratio_a as f64 / Q64_RESOLUTION;
        let ratio_b = position_ratio.ratio_b as f64 / Q64_RESOLUTION;

        let price = (sqrt_price as f64 / Q64_RESOLUTION).powf(2.0);

        // Estimated total position size.
        let mut total = (provided_a as f64 * price + provided_b as f64) as u64;
        total_a = (total as f64 * ratio_a / price) as u64;
        total_b = (total as f64 * ratio_b) as u64;

        let mut fee_a = 0;
        let mut fee_b = 0;

        if total_a < provided_a {
            swap_input = provided_a - total_a;
            fee_a = swap_input - try_apply_swap_fee(swap_input, args.swap_fee_rate)?;
            swap_output = ((swap_input - fee_a) as f64 * price) as u64;
            swap_a_to_b = true;
        } else if total_b < provided_b {
            swap_input = provided_b - total_b;
            fee_b = swap_input - try_apply_swap_fee(swap_input, args.swap_fee_rate)?;
            swap_output = ((swap_input - fee_b) as f64 / price) as u64;
            swap_a_to_b = false;
        }

        // Recompute totals with applied swap fee.
        total = ((provided_a - fee_a) as f64 * price) as u64 + provided_b - fee_b;
        total_a = ((total as f64 * ratio_a) / price) as u64;
        total_b = (total as f64 * ratio_b) as u64;
    }

    let liquidity = get_liquidity_from_amounts(sqrt_price, lower_sqrt_price, upper_sqrt_price, total_a, total_b)?;
    let liquidation_prices = get_lp_position_liquidation_prices(
        args.tick_lower_index,
        args.tick_upper_index,
        liquidity,
        0,
        0,
        borrow_a,
        borrow_b,
        args.liquidation_threshold,
    )?;

    let leverage = compute_leverage(total_a, total_b, borrow_a, borrow_b, sqrt_price)?;

    Ok(IncreaseLpPositionQuoteResult {
        collateral_a,
        collateral_b,
        borrow_a,
        borrow_b,
        total_a,
        total_b,
        swap_input,
        swap_output,
        swap_a_to_b,
        protocol_fee_a,
        protocol_fee_b,
        liquidity,
        leverage,
        liquidation_lower_price: liquidation_prices.lower,
        liquidation_upper_price: liquidation_prices.upper,
    })
}

#[derive(Debug, Copy, Clone, PartialEq)]
#[cfg_attr(feature = "wasm", wasm_expose)]
pub struct RepayLpPositionDebtQuoteArgs {
    /** The position liquidity */
    pub liquidity: u128,
    /** The current debt of a position in token A. */
    pub debt_a: u64,
    /** The current debt of a position in token B. */
    pub debt_b: u64,
    /** The leftovers of a position in token A. */
    pub leftovers_a: u64,
    /** The leftovers of a position in token B. */
    pub leftovers_b: u64,
    /** Position lower tick index. */
    pub tick_lower_index: i32,
    /** Position upper tick index. */
    pub tick_upper_index: i32,
    /** The amount of token A to repay. */
    pub repay_a: u64,
    /** The amount of token B to repay. */
    pub repay_b: u64,
    /** Current sqrt price. */
    pub sqrt_price: u128,
    /** The liquidation threshold of the market. */
    pub liquidation_threshold: u32,
}

#[derive(Debug, Copy, Clone, PartialEq)]
#[cfg_attr(feature = "wasm", wasm_expose)]
pub struct RepayLpPositionDebtQuoteResult {
    pub debt_a: u64,
    pub debt_b: u64,
    pub leverage: f64,
    pub liquidation_lower_price: f64,
    pub liquidation_upper_price: f64,
}

#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn get_repay_lp_position_debt_quote(args: RepayLpPositionDebtQuoteArgs) -> Result<RepayLpPositionDebtQuoteResult, CoreError> {
    let mut debt_a = args.debt_a;
    let mut debt_b = args.debt_b;
    let repay_a = args.repay_a;
    let repay_b = args.repay_b;

    if args.liquidity == 0 {
        return Err("Position liquidity can't be zero.");
    }

    if debt_a < repay_a {
        return Err("Position debt A is less than the repaid amount.");
    }

    if debt_b < repay_b {
        return Err("Position debt b is less than the repaid amount.");
    }

    debt_a -= repay_a;
    debt_b -= repay_b;

    let liquidation_prices = get_lp_position_liquidation_prices(
        args.tick_lower_index,
        args.tick_upper_index,
        args.liquidity,
        args.leftovers_a,
        args.leftovers_b,
        debt_a,
        debt_b,
        args.liquidation_threshold,
    )?;

    let lower_sqrt_price = tick_index_to_sqrt_price(args.tick_lower_index);
    let upper_sqrt_price = tick_index_to_sqrt_price(args.tick_upper_index);

    let total = get_amounts_from_liquidity(args.liquidity, args.sqrt_price, lower_sqrt_price, upper_sqrt_price, false)?;
    let leverage = compute_leverage(total.a + args.leftovers_a, total.b + args.leftovers_b, debt_a, debt_b, args.sqrt_price)?;

    Ok(RepayLpPositionDebtQuoteResult {
        debt_a,
        debt_b,
        leverage,
        liquidation_lower_price: liquidation_prices.lower,
        liquidation_upper_price: liquidation_prices.upper,
    })
}

#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn compute_leverage(total_a: u64, total_b: u64, debt_a: u64, debt_b: u64, sqrt_price: u128) -> Result<f64, CoreError> {
    let price = sqrt_price_x64_to_price_x64(sqrt_price)?;

    let total = U64F64::from(total_a)
        .checked_mul(price)
        .ok_or(ARITHMETIC_OVERFLOW)?
        .to_num::<u64>()
        .checked_add(total_b)
        .ok_or(ARITHMETIC_OVERFLOW)?;

    let debt = U64F64::from(debt_a)
        .checked_mul(price)
        .ok_or(ARITHMETIC_OVERFLOW)?
        .to_num::<u64>()
        .checked_add(debt_b)
        .ok_or(ARITHMETIC_OVERFLOW)?;

    // We assume that the leverage of an empty position is always 1.0x.
    if total == 0 {
        return Ok(1.0);
    }

    if debt >= total {
        return Err("The debt is greater than the total size");
    }

    let leverage = total as f64 / (total - debt) as f64;
    Ok(leverage)
}

#[cfg(all(test, not(feature = "wasm")))]
mod tests {
    use crate::{
        get_increase_lp_position_quote, get_lp_position_liquidation_prices, get_repay_lp_position_debt_quote, IncreaseLpPositionQuoteArgs,
        IncreaseLpPositionQuoteResult, LiquidationPrices, RepayLpPositionDebtQuoteArgs, COMPUTED_AMOUNT, HUNDRED_PERCENT,
    };
    use fusionamm_core::{
        get_liquidity_from_amount_b, price_to_sqrt_price, price_to_tick_index, tick_index_to_sqrt_price, MAX_TICK_INDEX, MIN_TICK_INDEX,
    };
    use once_cell::sync::Lazy;

    pub static TICK_LOWER_INDEX: Lazy<i32> = Lazy::new(|| price_to_tick_index(180.736, 6, 6));
    pub static TICK_UPPER_INDEX: Lazy<i32> = Lazy::new(|| price_to_tick_index(225.66, 6, 6));
    pub static SQRT_PRICE: Lazy<u128> = Lazy::new(|| price_to_sqrt_price(213.41, 6, 6));
    pub static LIQUIDITY: Lazy<u128> =
        Lazy::new(|| get_liquidity_from_amount_b(10000_000_000, tick_index_to_sqrt_price(*TICK_LOWER_INDEX), *SQRT_PRICE).unwrap());

    #[test]
    fn test_liquidation_price_outside_range_lower() {
        assert_eq!(
            get_lp_position_liquidation_prices(
                *TICK_LOWER_INDEX,
                *TICK_UPPER_INDEX,
                *LIQUIDITY,
                0,                          // leftovers_a
                0,                          // leftovers_b
                0,                          // debt_a
                9807_000_000,               // debt_b
                HUNDRED_PERCENT * 83 / 100  // liquidation_threshold
            ),
            Ok(LiquidationPrices {
                lower: 176.12815046153585,
                upper: 0.0
            })
        );
    }

    #[test]
    fn test_liquidation_price_outside_range_upper() {
        assert_eq!(
            get_lp_position_liquidation_prices(
                *TICK_LOWER_INDEX,
                *TICK_UPPER_INDEX,
                *LIQUIDITY,
                0,                          // leftovers_a
                0,                          // leftovers_b
                20_000_000,                 // debt_a
                0,                          // debt_b
                HUNDRED_PERCENT * 83 / 100  // liquidation_threshold
            ),
            Ok(LiquidationPrices {
                lower: 0.0,
                upper: 562.219410388
            })
        );
    }

    #[test]
    fn test_liquidation_price_outside_range_lower_and_upper() {
        assert_eq!(
            get_lp_position_liquidation_prices(
                *TICK_LOWER_INDEX,
                *TICK_UPPER_INDEX,
                *LIQUIDITY,
                0,                          // leftovers_a
                0,                          // leftovers_b
                10_000_000,                 // debt_a
                5000_000_000,               // debt_b
                HUNDRED_PERCENT * 83 / 100  // liquidation_threshold
            ),
            Ok(LiquidationPrices {
                lower: 109.45458168998225,
                upper: 624.4388207760001
            })
        );
    }

    #[test]
    fn test_liquidation_price_inside_range_lower() {
        assert_eq!(
            get_lp_position_liquidation_prices(
                *TICK_LOWER_INDEX,
                *TICK_UPPER_INDEX,
                *LIQUIDITY,
                0,                          // leftovers_a
                0,                          // leftovers_b
                0,                          // debt_a
                11000_000_000,              // debt_b
                HUNDRED_PERCENT * 83 / 100  // liquidation_threshold
            ),
            Ok(LiquidationPrices {
                lower: 204.60489065334323,
                upper: 0.0
            })
        );
    }

    #[test]
    fn test_liquidation_price_inside_range_upper() {
        assert_eq!(
            get_lp_position_liquidation_prices(
                *TICK_LOWER_INDEX,
                *TICK_UPPER_INDEX,
                *LIQUIDITY,
                0,                          // leftovers_a
                0,                          // leftovers_b
                51_000_000,                 // debt_a
                0,                          // debt_b
                HUNDRED_PERCENT * 83 / 100  // liquidation_threshold
            ),
            Ok(LiquidationPrices {
                lower: 0.0,
                upper: 220.16318077637644
            })
        );
    }

    #[test]
    fn test_liquidation_price_inside_range_lower_and_upper() {
        assert_eq!(
            get_lp_position_liquidation_prices(
                *TICK_LOWER_INDEX,
                *TICK_UPPER_INDEX,
                *LIQUIDITY,
                0,                          // leftovers_a
                0,                          // leftovers_b
                11_500_000,                 // debt_a
                8700_000_000,               // debt_b
                HUNDRED_PERCENT * 83 / 100  // liquidation_threshold
            ),
            Ok(LiquidationPrices {
                lower: 210.75514596082337,
                upper: 219.48595430071575
            })
        );
    }

    #[test]
    fn test_lp_increase_quote_collateral_a_and_b_provided() {
        assert_eq!(
            get_increase_lp_position_quote(IncreaseLpPositionQuoteArgs {
                collateral_a: 1000000,
                collateral_b: 1000000,
                borrow_a: 2000000,
                borrow_b: 2000000,
                tick_lower_index: price_to_tick_index(1.0, 1, 1),
                sqrt_price: price_to_sqrt_price(2.0, 1, 1),
                tick_upper_index: price_to_tick_index(4.0, 1, 1),
                protocol_fee_rate: (HUNDRED_PERCENT / 100) as u16,
                protocol_fee_rate_on_collateral: (HUNDRED_PERCENT / 100) as u16,
                swap_fee_rate: 10000, // 1%
                liquidation_threshold: HUNDRED_PERCENT * 83 / 100,
            }),
            Ok(IncreaseLpPositionQuoteResult {
                collateral_a: 1000000,
                collateral_b: 1000000,
                borrow_a: 2000000,
                borrow_b: 2000000,
                total_a: 2223701,
                total_b: 4447744,
                swap_input: 742586,
                swap_output: 1470320,
                swap_a_to_b: true,
                protocol_fee_a: 30000,
                protocol_fee_b: 30000,
                liquidity: 10737803,
                leverage: 3.0724343435529677,
                liquidation_lower_price: 0.8143170288470588,
                liquidation_upper_price: 3.4020457909456225,
            })
        );
    }

    #[test]
    fn test_lp_increase_quote_collateral_a_provided() {
        assert_eq!(
            get_increase_lp_position_quote(IncreaseLpPositionQuoteArgs {
                collateral_a: 10000000,
                collateral_b: 0,
                borrow_a: 0,
                borrow_b: 0,
                tick_lower_index: price_to_tick_index(0.25, 6, 9),
                sqrt_price: price_to_sqrt_price(0.5, 6, 9),
                tick_upper_index: price_to_tick_index(1.0, 6, 9),
                protocol_fee_rate: (HUNDRED_PERCENT / 100) as u16,
                protocol_fee_rate_on_collateral: (HUNDRED_PERCENT / 100) as u16,
                swap_fee_rate: 10000, // 1%
                liquidation_threshold: HUNDRED_PERCENT * 83 / 100,
            }),
            Ok(IncreaseLpPositionQuoteResult {
                collateral_a: 10000000,
                collateral_b: 0,
                borrow_a: 0,
                borrow_b: 0,
                total_a: 4925137,
                total_b: 2462680451,
                swap_input: 4950113,
                swap_output: 2450305500,
                swap_a_to_b: true,
                protocol_fee_a: 100000,
                protocol_fee_b: 0,
                liquidity: 376005629,
                leverage: 1.0,
                liquidation_lower_price: 0.0,
                liquidation_upper_price: 0.0,
            })
        );
    }

    #[test]
    fn test_lp_increase_quote_collateral_a_provided_b_computed() {
        assert_eq!(
            get_increase_lp_position_quote(IncreaseLpPositionQuoteArgs {
                collateral_a: 10000000,
                collateral_b: COMPUTED_AMOUNT,
                borrow_a: 2000000,
                borrow_b: COMPUTED_AMOUNT,
                tick_lower_index: price_to_tick_index(1.0, 1, 1),
                sqrt_price: price_to_sqrt_price(3.0, 1, 1),
                tick_upper_index: price_to_tick_index(4.0, 1, 1),
                protocol_fee_rate: 0,
                protocol_fee_rate_on_collateral: 0,
                swap_fee_rate: 0,
                liquidation_threshold: HUNDRED_PERCENT * 83 / 100,
            }),
            Ok(IncreaseLpPositionQuoteResult {
                collateral_a: 10000000,
                collateral_b: 94660495,
                borrow_a: 2000000,
                borrow_b: 18932100,
                total_a: 12000000,
                total_b: 113592595,
                swap_input: 0,
                swap_output: 0,
                swap_a_to_b: false,
                protocol_fee_a: 0,
                protocol_fee_b: 0,
                liquidity: 155170370,
                leverage: 1.2,
                liquidation_lower_price: 0.30342990360419136,
                liquidation_upper_price: 54.925553349999994
            })
        );
    }

    #[test]
    fn test_lp_increase_quote_collateral_a_provided_b_computed_no_leverage() {
        assert_eq!(
            get_increase_lp_position_quote(IncreaseLpPositionQuoteArgs {
                collateral_a: 30000000000,
                collateral_b: COMPUTED_AMOUNT,
                borrow_a: 0,
                borrow_b: 0,
                tick_lower_index: price_to_tick_index(1.0, 1, 1),
                sqrt_price: price_to_sqrt_price(3.0, 1, 1),
                tick_upper_index: price_to_tick_index(4.0, 1, 1),
                protocol_fee_rate: 0,
                protocol_fee_rate_on_collateral: 0,
                swap_fee_rate: 0,
                liquidation_threshold: HUNDRED_PERCENT * 83 / 100,
            }),
            Ok(IncreaseLpPositionQuoteResult {
                collateral_a: 30000000000,
                collateral_b: 283981489799,
                borrow_a: 0,
                borrow_b: 0,
                total_a: 30000000000,
                total_b: 283981489799,
                swap_input: 0,
                swap_output: 0,
                swap_a_to_b: false,
                protocol_fee_a: 0,
                protocol_fee_b: 0,
                liquidity: 387925929269,
                leverage: 1.0,
                liquidation_lower_price: 0.0,
                liquidation_upper_price: 0.0
            })
        );
    }

    #[test]
    fn test_lp_increase_quote_collateral_a_computed_b_provided() {
        assert_eq!(
            get_increase_lp_position_quote(IncreaseLpPositionQuoteArgs {
                collateral_a: COMPUTED_AMOUNT,
                collateral_b: 1000000,
                borrow_a: COMPUTED_AMOUNT,
                borrow_b: 2000000,
                tick_lower_index: price_to_tick_index(1.0, 1, 1),
                sqrt_price: price_to_sqrt_price(3.0, 1, 1),
                tick_upper_index: price_to_tick_index(4.0, 1, 1),
                protocol_fee_rate: 0,
                protocol_fee_rate_on_collateral: 0,
                swap_fee_rate: 0,
                liquidation_threshold: HUNDRED_PERCENT * 83 / 100,
            }),
            Ok(IncreaseLpPositionQuoteResult {
                collateral_a: 105640,
                collateral_b: 1000000,
                borrow_a: 211282,
                borrow_b: 2000000,
                total_a: 316922,
                total_b: 3000000,
                swap_input: 0,
                swap_output: 0,
                swap_a_to_b: false,
                protocol_fee_a: 0,
                protocol_fee_b: 0,
                liquidity: 4098075,
                leverage: 3.000003796737843,
                liquidation_lower_price: 1.4306915613018771,
                liquidation_upper_price: 6.63182675287057
            })
        );
    }

    #[test]
    fn test_lp_increase_quote_collateral_a_computed_b_provided_no_leverage() {
        assert_eq!(
            get_increase_lp_position_quote(IncreaseLpPositionQuoteArgs {
                collateral_a: COMPUTED_AMOUNT,
                collateral_b: 30000000000,
                borrow_a: 0,
                borrow_b: 0,
                tick_lower_index: price_to_tick_index(1.0, 1, 1),
                sqrt_price: price_to_sqrt_price(3.0, 1, 1),
                tick_upper_index: price_to_tick_index(4.0, 1, 1),
                protocol_fee_rate: 0,
                protocol_fee_rate_on_collateral: 0,
                swap_fee_rate: 0,
                liquidation_threshold: HUNDRED_PERCENT * 83 / 100,
            }),
            Ok(IncreaseLpPositionQuoteResult {
                collateral_a: 3169220644,
                collateral_b: 30000000000,
                borrow_a: 0,
                borrow_b: 0,
                total_a: 3169220644,
                total_b: 30000000000,
                swap_input: 0,
                swap_output: 0,
                swap_a_to_b: false,
                protocol_fee_a: 0,
                protocol_fee_b: 0,
                liquidity: 40980762112,
                leverage: 1.0,
                liquidation_lower_price: 0.0,
                liquidation_upper_price: 0.0
            })
        );
    }

    #[test]
    fn test_lp_increase_quote_collateral_a_computed_b_provided_no_leverage_full_range() {
        assert_eq!(
            get_increase_lp_position_quote(IncreaseLpPositionQuoteArgs {
                collateral_a: COMPUTED_AMOUNT,
                collateral_b: 30000000000,
                borrow_a: 0,
                borrow_b: 0,
                tick_lower_index: MIN_TICK_INDEX,
                sqrt_price: price_to_sqrt_price(3.0, 1, 1),
                tick_upper_index: MAX_TICK_INDEX,
                protocol_fee_rate: 0,
                protocol_fee_rate_on_collateral: 0,
                swap_fee_rate: 0,
                liquidation_threshold: HUNDRED_PERCENT * 83 / 100,
            }),
            Ok(IncreaseLpPositionQuoteResult {
                collateral_a: 9999999997,
                collateral_b: 30000000000,
                borrow_a: 0,
                borrow_b: 0,
                total_a: 9999999997,
                total_b: 30000000000,
                swap_input: 0,
                swap_output: 0,
                swap_a_to_b: false,
                protocol_fee_a: 0,
                protocol_fee_b: 0,
                liquidity: 17320508077,
                leverage: 1.0,
                liquidation_lower_price: 0.0,
                liquidation_upper_price: 0.0
            })
        );
    }

    #[test]
    fn test_lp_increase_quote_one_sided_collateral_a_provided_b_computed() {
        assert_eq!(
            get_increase_lp_position_quote(IncreaseLpPositionQuoteArgs {
                collateral_a: 10000000,
                collateral_b: COMPUTED_AMOUNT,
                borrow_a: 2000000,
                borrow_b: COMPUTED_AMOUNT,
                tick_lower_index: price_to_tick_index(1.0, 1, 1),
                sqrt_price: price_to_sqrt_price(0.5, 1, 1),
                tick_upper_index: price_to_tick_index(4.0, 1, 1),
                protocol_fee_rate: 0,
                protocol_fee_rate_on_collateral: 0,
                swap_fee_rate: 0,
                liquidation_threshold: HUNDRED_PERCENT * 83 / 100,
            }),
            Ok(IncreaseLpPositionQuoteResult {
                collateral_a: 10000000,
                collateral_b: 0,
                borrow_a: 2000000,
                borrow_b: 0,
                total_a: 12000000,
                total_b: 0,
                swap_input: 0,
                swap_output: 0,
                swap_a_to_b: false,
                protocol_fee_a: 0,
                protocol_fee_b: 0,
                liquidity: 24000764,
                leverage: 1.2,
                liquidation_lower_price: 0.0,
                liquidation_upper_price: 9.959682525
            })
        );
    }

    #[test]
    fn test_lp_increase_quote_one_sided_collateral_a_computed_b_provided() {
        assert_eq!(
            get_increase_lp_position_quote(IncreaseLpPositionQuoteArgs {
                collateral_a: COMPUTED_AMOUNT,
                collateral_b: 1000000,
                borrow_a: COMPUTED_AMOUNT,
                borrow_b: 2000000,
                tick_lower_index: price_to_tick_index(1.0, 1, 1),
                sqrt_price: price_to_sqrt_price(5.0, 1, 1),
                tick_upper_index: price_to_tick_index(4.0, 1, 1),
                protocol_fee_rate: 0,
                protocol_fee_rate_on_collateral: 0,
                swap_fee_rate: 0,
                liquidation_threshold: HUNDRED_PERCENT * 83 / 100,
            }),
            Ok(IncreaseLpPositionQuoteResult {
                collateral_a: 0,
                collateral_b: 1000000,
                borrow_a: 0,
                borrow_b: 2000000,
                total_a: 0,
                total_b: 3000000,
                swap_input: 0,
                swap_output: 0,
                swap_a_to_b: false,
                protocol_fee_a: 0,
                protocol_fee_b: 0,
                liquidity: 3000191,
                leverage: 3.0,
                liquidation_lower_price: 1.8840617719481452,
                liquidation_upper_price: 0.0
            })
        );
    }

    #[test]
    fn test_lp_increase_quote_verify_liquidation_prices() {
        let quote = get_increase_lp_position_quote(IncreaseLpPositionQuoteArgs {
            collateral_a: 0,
            collateral_b: 1000_000_000,
            borrow_a: 3_000_000,
            borrow_b: 100_000_000,
            tick_lower_index: price_to_tick_index(180.736, 6, 6),
            sqrt_price: price_to_sqrt_price(213.41, 6, 6),
            tick_upper_index: price_to_tick_index(225.66, 6, 6),
            protocol_fee_rate: 500,
            protocol_fee_rate_on_collateral: 500,
            swap_fee_rate: 40,
            liquidation_threshold: HUNDRED_PERCENT * 83 / 100,
        })
        .unwrap();

        assert_eq!(quote.liquidation_lower_price, 23.805241869982023);
        assert_eq!(quote.liquidation_upper_price, 451.38033819333333);
    }

    #[test]
    fn test_repay_debt_quote() {
        let quote = get_repay_lp_position_debt_quote(RepayLpPositionDebtQuoteArgs {
            repay_a: 1_000_000,
            repay_b: 30_000_000,
            liquidity: 1109671058,
            debt_a: 3_000_000,
            debt_b: 100_000_000,
            leftovers_a: 2,
            leftovers_b: 15,
            tick_lower_index: price_to_tick_index(180.736, 6, 6),
            sqrt_price: price_to_sqrt_price(213.41, 6, 6),
            tick_upper_index: price_to_tick_index(225.66, 6, 6),
            liquidation_threshold: HUNDRED_PERCENT * 83 / 100,
        })
        .unwrap();

        assert_eq!(quote.debt_a, 2_000_000);
        assert_eq!(quote.debt_b, 70_000_000);
        assert_eq!(quote.liquidation_lower_price, 13.459576327110664);
        assert_eq!(quote.liquidation_upper_price, 692.0710879340029);
    }
}