Skip to main content

dex_math/
utils.rs

1use crate::{state::SwapResult, RebalanceResult, MAX_PERCENTAGE};
2
3
4fn ceil_div(token_amount: u128, fee_numerator: u128, fee_denominator: u128) -> Option<u128> {
5    token_amount
6        .checked_mul(u128::from(fee_numerator))
7        .unwrap()
8        .checked_add(fee_denominator)?
9        .checked_sub(1)?
10        .checked_div(fee_denominator)
11}
12
13pub fn floor_div(token_amount: u128, fee_numerator: u128, fee_denominator: u128) -> Option<u128> {
14    Some(
15        token_amount
16            .checked_mul(fee_numerator)?
17            .checked_div(fee_denominator)?,
18    )
19}
20
21pub fn get_trade_fee(amount: u128, trade_fee_rate: u64) -> Option<u128> {
22    ceil_div(
23        amount,
24        u128::from(trade_fee_rate),
25        u128::from(MAX_PERCENTAGE),
26    )
27}
28
29pub fn get_protocol_fee(amount: u128, protocol_fee_rate: u64) -> Option<u128> {
30    floor_div(
31        amount,
32        u128::from(protocol_fee_rate),
33        u128::from(MAX_PERCENTAGE),
34    )
35}
36
37pub fn swap_base_input_without_fees(
38    source_amount: u128,
39    swap_source_amount: u128,
40    swap_destination_amount: u128,
41) -> u128 {
42    // (x + delta_x) * (y - delta_y) = x * y
43    // delta_y = (delta_x * y) / (x + delta_x)
44    let numerator = source_amount.checked_mul(swap_destination_amount).unwrap();
45    let denominator = swap_source_amount.checked_add(source_amount).unwrap();
46    let destination_amount_swapped = numerator.checked_div(denominator).unwrap();
47    destination_amount_swapped
48}
49
50
51/// This is guaranteed to work for all values such that:
52///  - 1 <= swap_source_amount * swap_destination_amount <= u128::MAX
53///  - 1 <= source_amount <= u64::MAX
54/// dev: invariant is increased due to ceil_div
55/// dev: because of ceil_div the destination_amount_swapped is rounded down
56pub fn swap(
57    source_amount: u128,
58    pool_source_amount: u128,
59    pool_destination_amount: u128,
60    trade_fee_rate: u64,
61    protocol_fee_rate: u64,
62) -> Option<SwapResult> {
63    let trade_fee = get_trade_fee(source_amount, trade_fee_rate).unwrap();
64    let protocol_fee = get_protocol_fee(trade_fee, protocol_fee_rate).unwrap();
65
66    let source_amount_post_fees = source_amount.checked_sub(trade_fee).unwrap();
67
68    let destination_amount_swapped = swap_base_input_without_fees(
69        source_amount_post_fees,
70        pool_source_amount,
71        pool_destination_amount,
72    );
73
74    Some(SwapResult {
75        from_amount: source_amount_post_fees as u64,
76        to_amount: destination_amount_swapped as u64,
77        trade_fee: trade_fee as u64,
78        protocol_fee: protocol_fee as u64,
79    })
80}
81
82
83pub fn rebalance_pool_ratio(
84    to_amount_swapped: u64,
85    current_source_amount: u64,
86    current_destination_amount: u64,
87    original_source_amount: u64,
88    original_destination_amount: u64,
89    ratio_change_tolerance_rate: u64,
90) -> Option<RebalanceResult> {
91    if to_amount_swapped >= current_destination_amount
92        || current_source_amount == 0
93        || current_destination_amount == 0
94    {
95        // Should never happen, but just in case
96        return Some(RebalanceResult {
97            from_to_lock: 0,
98            is_rate_tolerance_exceeded: true,
99        });
100    }
101
102    // Calculate the remaining destination amount after swap
103    let remaining_destination = current_destination_amount.checked_sub(to_amount_swapped)?;
104
105    let original_ratio = original_source_amount as f64 / original_destination_amount as f64;
106
107    // Calculate the exact floating-point value that would give us the perfect ratio
108    let exact_from_to_lock =
109        current_source_amount as f64 - (remaining_destination as f64 * original_ratio);
110
111    // Find the optimal integer from_to_lock by testing values around the exact value
112    let mut best_from_to_lock = 0u64;
113    let mut best_ratio_diff = f64::INFINITY;
114
115    // Test a range of values around the exact value
116    let start_val = (exact_from_to_lock - 1.0).max(0.0) as u64;
117    let end_val = (exact_from_to_lock + 1.0).min(current_source_amount as f64) as u64;
118
119    for test_from_to_lock in start_val..=end_val {
120        if test_from_to_lock > current_source_amount {
121            continue;
122        }
123
124        let new_source = current_source_amount.checked_sub(test_from_to_lock)?;
125        let new_ratio = new_source as f64 / remaining_destination as f64;
126        let ratio_diff = (new_ratio - original_ratio).abs();
127
128        if ratio_diff < best_ratio_diff && new_ratio != 0.0 {
129            best_ratio_diff = ratio_diff;
130            best_from_to_lock = test_from_to_lock;
131        }
132    }
133
134    let from_to_lock = best_from_to_lock;
135    let new_source_amount = current_source_amount.checked_sub(from_to_lock)?;
136    let new_ratio = new_source_amount as f64 / remaining_destination as f64;
137
138    // Calculate percentage change
139    let percentage_change = (new_ratio - original_ratio).abs() / original_ratio * 100.0;
140
141    let tolerance_percentage = (ratio_change_tolerance_rate as f64 / MAX_PERCENTAGE as f64) * 100.0;
142    let is_rate_tolerance_exceeded = percentage_change > tolerance_percentage;
143
144    Some(RebalanceResult {
145        from_to_lock,
146        is_rate_tolerance_exceeded,
147    })
148}
149
150/// Test helpers and tests for cp
151#[cfg(test)]
152pub mod tests {
153    use {
154        super::*,
155        proptest::prelude::*,
156        spl_math::{precise_number::PreciseNumber},
157    };
158
159    /// Calculates the total normalized value of the curve given the liquidity
160    /// parameters.
161    ///
162    /// The constant product implementation for this function gives the square root
163    /// of the Uniswap invariant.
164    pub fn normalized_value(
165        swap_token_a_amount: u128,
166        swap_token_b_amount: u128,
167    ) -> Option<PreciseNumber> {
168        let swap_token_a_amount = PreciseNumber::new(swap_token_a_amount)?;
169        let swap_token_b_amount = PreciseNumber::new(swap_token_b_amount)?;
170        swap_token_a_amount
171            .checked_mul(&swap_token_b_amount)?
172            .sqrt()
173    }
174
175    /// Test function checking that a swap never reduces the overall value of
176    /// the pool.
177    ///
178    /// Since curve calculations use unsigned integers, there is potential for
179    /// truncation at some point, meaning a potential for value to be lost in
180    /// either direction if too much is given to the swapper.
181    ///
182    /// This test guarantees that the relative change in value will be at most
183    /// 1 normalized token, and that the value will never decrease from a trade.
184    pub fn check_curve_value_from_inner_swap(
185        source_token_amount: u128,
186        swap_source_amount: u128,
187        swap_destination_amount: u128,
188        is_x_to_y: bool,
189    ) {
190        let destination_amount_swapped = swap_base_input_without_fees(
191            source_token_amount,
192            swap_source_amount,
193            swap_destination_amount,
194        );
195
196        let (swap_token_x_amount, swap_token_y_amount) = match is_x_to_y {
197            true => (swap_source_amount, swap_destination_amount),
198            false => (swap_destination_amount, swap_source_amount),
199        };
200        let previous_value = swap_token_x_amount
201            .checked_mul(swap_token_y_amount)
202            .unwrap();
203
204        let new_swap_source_amount = swap_source_amount.checked_add(source_token_amount).unwrap();
205        let new_swap_destination_amount = swap_destination_amount
206            .checked_sub(destination_amount_swapped)
207            .unwrap();
208
209        let (swap_token_x_amount, swap_token_y_amount) = match is_x_to_y {
210            true => (new_swap_source_amount, new_swap_destination_amount),
211            false => (new_swap_destination_amount, new_swap_source_amount),
212        };
213
214        let new_value = swap_token_x_amount
215            .checked_mul(swap_token_y_amount)
216            .unwrap();
217
218        assert!(new_value >= previous_value);
219    }
220
221    pub fn check_curve_value_from_swap(
222        source_token_amount: u128,
223        swap_source_amount: u128,
224        swap_destination_amount: u128,
225        trade_fee_rate: u64,
226        protocol_fee_rate: u64,
227        is_x_to_y: bool,
228    ) {
229        let swap_result = swap(
230            source_token_amount,
231            swap_source_amount,
232            swap_destination_amount,
233            trade_fee_rate,
234            protocol_fee_rate,
235        )
236        .unwrap();
237
238        // ensure trade fee do not truncate amount
239        assert_eq!(
240            u128::from(swap_result.from_amount)
241                .checked_add(u128::from(swap_result.trade_fee))
242                .unwrap(),
243            source_token_amount
244        );
245
246        // protocol fee is always less than trade fee
247        assert!(swap_result.trade_fee >= swap_result.protocol_fee);
248
249        let (swap_token_x_amount, swap_token_y_amount) = match is_x_to_y {
250            true => (swap_source_amount, swap_destination_amount),
251            false => (swap_destination_amount, swap_source_amount),
252        };
253
254        let previous_value = swap_token_x_amount
255            .checked_mul(swap_token_y_amount)
256            .unwrap();
257
258        let new_swap_source_amount = swap_source_amount
259            .checked_add(u128::from(swap_result.from_amount))
260            .unwrap();
261        let new_swap_destination_amount = swap_destination_amount
262            .checked_sub(u128::from(swap_result.to_amount))
263            .unwrap();
264
265        let (swap_token_x_amount, swap_token_y_amount) = match is_x_to_y {
266            true => (new_swap_source_amount, new_swap_destination_amount),
267            false => (new_swap_destination_amount, new_swap_source_amount),
268        };
269
270        let new_value = swap_token_x_amount
271            .checked_mul(swap_token_y_amount)
272            .unwrap();
273
274        assert!(new_value >= previous_value);
275    }
276
277    // /// Test function checking that a deposit never reduces the value of pool
278    // /// tokens.
279    // ///
280    // /// Since curve calculations use unsigned integers, there is potential for
281    // /// truncation at some point, meaning a potential for value to be lost if
282    // /// too much is given to the depositor.
283    // pub fn check_pool_value_from_deposit(
284    //     lp_token_amount: u128,
285    //     lp_token_supply: u128,
286    //     swap_token_x_amount: u128,
287    //     swap_token_y_amount: u128,
288    // ) {
289    //     let deposit_result = lp_tokens_to_trading_tokens(
290    //         lp_token_amount,
291    //         lp_token_supply,
292    //         swap_token_x_amount,
293    //         swap_token_y_amount,
294    //         RoundDirection::Ceiling,
295    //     )
296    //     .unwrap();
297    //     let new_swap_token_x_amount = swap_token_x_amount + deposit_result.token_x_amount;
298    //     let new_swap_token_y_amount = swap_token_y_amount + deposit_result.token_y_amount;
299    //     let new_lp_token_supply = lp_token_supply + lp_token_amount;
300
301    //     // the following inequality must hold:
302    //     // new_token_a / new_pool_token_supply >= token_a / pool_token_supply
303    //     // which reduces to:
304    //     // new_token_a * pool_token_supply >= token_a * new_pool_token_supply
305
306    //     // These numbers can be just slightly above u64 after the deposit, which
307    //     // means that their multiplication can be just above the range of u128.
308    //     // For ease of testing, we bump these up to U256.
309    //     let lp_token_supply = U256::from(lp_token_supply);
310    //     let new_lp_token_supply = U256::from(new_lp_token_supply);
311    //     let swap_token_x_amount = U256::from(swap_token_x_amount);
312    //     let new_swap_token_x_amount = U256::from(new_swap_token_x_amount);
313    //     let swap_token_y_amount = U256::from(swap_token_y_amount);
314    //     let new_swap_token_y_amount = U256::from(new_swap_token_y_amount);
315
316    //     assert!(
317    //         new_swap_token_x_amount * lp_token_supply >= swap_token_x_amount * new_lp_token_supply
318    //     );
319    //     assert!(
320    //         new_swap_token_y_amount * lp_token_supply >= swap_token_y_amount * new_lp_token_supply
321    //     );
322    // }
323
324    // /// Test function checking that a withdraw never reduces the value of pool
325    // /// tokens.
326    // ///
327    // /// Since curve calculations use unsigned integers, there is potential for
328    // /// truncation at some point, meaning a potential for value to be lost if
329    // /// too much is given to the depositor.
330    // pub fn check_pool_value_from_withdraw(
331    //     lp_token_amount: u128,
332    //     lp_token_supply: u128,
333    //     swap_token_x_amount: u128,
334    //     swap_token_y_amount: u128,
335    // ) {
336    //     let withdraw_result = lp_tokens_to_trading_tokens(
337    //         lp_token_amount,
338    //         lp_token_supply,
339    //         swap_token_x_amount,
340    //         swap_token_y_amount,
341    //         RoundDirection::Floor,
342    //     )
343    //     .unwrap();
344    //     let new_swap_token_x_amount = swap_token_x_amount - withdraw_result.token_x_amount;
345    //     let new_swap_token_y_amount = swap_token_y_amount - withdraw_result.token_y_amount;
346    //     let new_pool_token_supply = lp_token_supply - lp_token_amount;
347
348    //     let value = normalized_value(swap_token_x_amount, swap_token_y_amount).unwrap();
349    //     // since we can get rounding issues on the pool value which make it seem that
350    //     // the value per token has gone down, we bump it up by an epsilon of 1
351    //     // to cover all cases
352    //     let new_value = normalized_value(new_swap_token_x_amount, new_swap_token_y_amount).unwrap();
353
354    //     // the following inequality must hold:
355    //     // new_pool_value / new_pool_token_supply >= pool_value / pool_token_supply
356    //     // which can also be written:
357    //     // new_pool_value * pool_token_supply >= pool_value * new_pool_token_supply
358
359    //     let lp_token_supply = PreciseNumber::new(lp_token_supply).unwrap();
360    //     let new_lp_token_supply = PreciseNumber::new(new_pool_token_supply).unwrap();
361    //     assert!(new_value
362    //         .checked_mul(&lp_token_supply)
363    //         .unwrap()
364    //         .greater_than_or_equal(&value.checked_mul(&new_lp_token_supply).unwrap()));
365    // }
366
367    // prop_compose! {
368    //     pub fn total_and_intermediate(max_value: u64)(total in 1..max_value)
369    //                     (intermediate in 1..total, total in Just(total))
370    //                     -> (u64, u64) {
371    //        (total, intermediate)
372    //    }
373    // }
374
375    // fn check_pool_token_rate(
376    //     token_x: u128,
377    //     token_y: u128,
378    //     deposit: u128,
379    //     supply: u128,
380    //     expected_x: u128,
381    //     expected_y: u128,
382    // ) {
383    //     let results =
384    //         lp_tokens_to_trading_tokens(deposit, supply, token_x, token_y, RoundDirection::Ceiling)
385    //             .unwrap();
386    //     assert_eq!(results.token_x_amount, expected_x);
387    //     assert_eq!(results.token_y_amount, expected_y);
388    // }
389
390    // #[test]
391    // fn trading_token_conversion() {
392    //     check_pool_token_rate(2, 49, 5, 10, 1, 25);
393    //     check_pool_token_rate(100, 202, 5, 101, 5, 10);
394    //     check_pool_token_rate(5, 501, 2, 10, 1, 101);
395    // }
396
397    // #[test]
398    // fn fail_trading_token_conversion() {
399    //     let results = lp_tokens_to_trading_tokens(5, 10, u128::MAX, 0, RoundDirection::Floor);
400    //     assert!(results.is_none());
401    //     let results = lp_tokens_to_trading_tokens(5, 10, 0, u128::MAX, RoundDirection::Floor);
402    //     assert!(results.is_none());
403    // }
404
405    fn test_truncation(
406        source_amount: u128,
407        swap_source_amount: u128,
408        swap_destination_amount: u128,
409        expected_source_amount_swapped: u128,
410        expected_destination_amount_swapped: u128,
411    ) {
412        let invariant = swap_source_amount * swap_destination_amount;
413        let destination_amount_swapped = swap_base_input_without_fees(
414            source_amount,
415            swap_source_amount,
416            swap_destination_amount,
417        );
418        assert_eq!(source_amount, expected_source_amount_swapped);
419        assert_eq!(
420            destination_amount_swapped,
421            expected_destination_amount_swapped
422        );
423        let new_invariant = (swap_source_amount + source_amount)
424            * (swap_destination_amount - destination_amount_swapped);
425        assert!(new_invariant >= invariant);
426    }
427
428    #[test]
429    fn constant_product_swap_rounding() {
430        let tests: &[(u128, u128, u128, u128, u128)] = &[
431            // spot: 10 * 70b / ~4m = 174,999.99
432            (10, 4_000_000, 70_000_000_000, 10, 174_999),
433            // spot: 20 * 1 / 3.000 = 6.6667 (source can be 18 to get 6 dest.)
434            (20, 30_000 - 20, 10_000, 20, 6),
435            // spot: 19 * 1 / 2.999 = 6.3334 (source can be 18 to get 6 dest.)
436            (19, 30_000 - 20, 10_000, 19, 6),
437            // spot: 18 * 1 / 2.999 = 6.0001
438            (18, 30_000 - 20, 10_000, 18, 6),
439            // spot: 10 * 3 / 2.0010 = 14.99
440            (10, 20_000, 30_000, 10, 14),
441            // spot: 10 * 3 / 2.0001 = 14.999
442            (10, 20_000 - 9, 30_000, 10, 14),
443            // spot: 10 * 3 / 2.0000 = 15
444            (10, 20_000 - 10, 30_000, 10, 15),
445            // spot: 100 * 3 / 6.001 = 49.99 (source can be 99 to get 49 dest.)
446            (100, 60_000, 30_000, 100, 49),
447            // spot: 99 * 3 / 6.001 = 49.49
448            (99, 60_000, 30_000, 99, 49),
449            // spot: 98 * 3 / 6.001 = 48.99 (source can be 97 to get 48 dest.)
450            (98, 60_000, 30_000, 98, 48),
451        ];
452        for (
453            source_amount,
454            swap_source_amount,
455            swap_destination_amount,
456            expected_source_amount,
457            expected_destination_amount,
458        ) in tests.iter()
459        {
460            test_truncation(
461                *source_amount,
462                *swap_source_amount,
463                *swap_destination_amount,
464                *expected_source_amount,
465                *expected_destination_amount,
466            );
467        }
468    }
469
470    proptest! {
471        #[test]
472        fn curve_value_does_not_decrease_from_inner_swap(
473            source_token_amount in 1..u64::MAX,
474            swap_source_amount in 1..u64::MAX,
475            swap_destination_amount in 1..u64::MAX,
476        ) {
477
478            let is_x_to_y = true;
479            check_curve_value_from_inner_swap(
480                source_token_amount as u128,
481                swap_source_amount as u128,
482                swap_destination_amount as u128,
483                is_x_to_y
484            );
485        }
486    }
487
488    proptest! {
489        #[test]
490        fn curve_value_does_not_decrease_from_swap(
491            source_token_amount in 1..u64::MAX,
492            swap_source_amount in 1..u64::MAX,
493            swap_destination_amount in 1..u64::MAX,
494            trade_fee_rate in 1..(MAX_PERCENTAGE - 1),
495            protocol_fee_rate in 1..MAX_PERCENTAGE,
496        ) {
497
498            let is_x_to_y = true;
499            check_curve_value_from_swap(
500                source_token_amount as u128,
501                swap_source_amount as u128,
502                swap_destination_amount as u128,
503                trade_fee_rate,
504                protocol_fee_rate,
505                is_x_to_y
506            );
507        }
508    }
509
510    // proptest! {
511    //     #[test]
512    //     fn curve_value_does_not_decrease_from_deposit(
513    //         pool_token_amount in 1..u64::MAX,
514    //         pool_token_supply in 1..u64::MAX,
515    //         swap_token_a_amount in 1..u64::MAX,
516    //         swap_token_b_amount in 1..u64::MAX,
517    //     ) {
518    //         let pool_token_amount = pool_token_amount as u128;
519    //         let pool_token_supply = pool_token_supply as u128;
520    //         let swap_token_a_amount = swap_token_a_amount as u128;
521    //         let swap_token_b_amount = swap_token_b_amount as u128;
522    //         // Make sure we will get at least one trading token out for each
523    //         // side, otherwise the calculation fails
524    //         prop_assume!(pool_token_amount * swap_token_a_amount / pool_token_supply >= 1);
525    //         prop_assume!(pool_token_amount * swap_token_b_amount / pool_token_supply >= 1);
526    //         check_pool_value_from_deposit(
527    //             pool_token_amount,
528    //             pool_token_supply,
529    //             swap_token_a_amount,
530    //             swap_token_b_amount,
531    //         );
532    //     }
533    // }
534
535    // proptest! {
536    //     #[test]
537    //     fn curve_value_does_not_decrease_from_withdraw(
538    //         (pool_token_supply, pool_token_amount) in total_and_intermediate(u64::MAX),
539    //         swap_token_a_amount in 1..u64::MAX,
540    //         swap_token_b_amount in 1..u64::MAX,
541    //     ) {
542    //         let pool_token_amount = pool_token_amount as u128;
543    //         let pool_token_supply = pool_token_supply as u128;
544    //         let swap_token_a_amount = swap_token_a_amount as u128;
545    //         let swap_token_b_amount = swap_token_b_amount as u128;
546    //         // Make sure we will get at least one trading token out for each
547    //         // side, otherwise the calculation fails
548    //         prop_assume!(pool_token_amount * swap_token_a_amount / pool_token_supply >= 1);
549    //         prop_assume!(pool_token_amount * swap_token_b_amount / pool_token_supply >= 1);
550    //         check_pool_value_from_withdraw(
551    //             pool_token_amount,
552    //             pool_token_supply,
553    //             swap_token_a_amount,
554    //             swap_token_b_amount,
555    //         );
556    //     }
557    // }
558
559    // #[test]
560    // fn pool_always_maintains_minimum_tokens() {
561    //     // This test validates that the pool always maintains at least some tokens
562    //     // of both types, even when users lose tokens due to rounding in extreme ratios
563
564    //     let test_cases = vec![
565    //         (1_000u128, 1_000u128),                 // 1:1 ratio
566    //         (1_000u128, 2_000u128),                 // 1:2 ratio
567    //         (2_000u128, 1_000u128),                 // 2:1 ratio
568    //         (100u128, 10_000u128),                  // 1:100 ratio
569    //         (10_000u128, 100u128),                  // 100:1 ratio
570    //         (1u128, 1_000_000_000u128),             // 1:1,000,000,000 ratio
571    //         (1_000_000_000u128, 1u128),             // 1,000,000,000:1 ratio
572    //         (1u128, 1_000_000_000_000_000_000u128), // 1:10^18 ratio
573    //         (1_000_000_000_000_000_000u128, 1u128), // 10^18:1 ratio (reverse)
574    //         // just above MIN_LIQUIDITY
575    //         (101u128, 101u128),
576    //         (10u128, 1021u128),
577    //         (1u128, 10201u128),
578    //     ];
579
580    //     for (token_x_amount, token_y_amount) in test_cases {
581    //         println!(
582    //             "\n=== Testing ratio {}:{} ===",
583    //             token_x_amount, token_y_amount
584    //         );
585
586    //         let initial_liquidity = initialize_pool_liquidity(token_x_amount, token_y_amount);
587    //         println!(
588    //             "Pool starts with: {} X + {} Y (liquidity: {})",
589    //             token_x_amount, token_y_amount, initial_liquidity
590    //         );
591
592    //         // Test withdrawing almost all LP tokens
593    //         let withdraw_lp_amount = (initial_liquidity as u128)
594    //             .checked_sub(MIN_LIQUIDITY as u128)
595    //             .unwrap();
596
597    //         assert!(withdraw_lp_amount > 0, "Withdraw amount is 0, not allowed");
598
599    //         let withdrawal_result = lp_tokens_to_trading_tokens(
600    //             withdraw_lp_amount,
601    //             initial_liquidity as u128,
602    //             token_x_amount,
603    //             token_y_amount,
604    //             RoundDirection::Floor,
605    //         )
606    //         .unwrap();
607
608    //         let remaining_x = token_x_amount
609    //             .checked_sub(withdrawal_result.token_x_amount)
610    //             .unwrap();
611    //         let remaining_y = token_y_amount
612    //             .checked_sub(withdrawal_result.token_y_amount)
613    //             .unwrap();
614
615    //         println!("Withdrew: {} LP tokens", withdraw_lp_amount);
616    //         println!(
617    //             "User gets: {} X + {} Y",
618    //             withdrawal_result.token_x_amount, withdrawal_result.token_y_amount
619    //         );
620    //         println!("Pool keeps: {} X + {} Y", remaining_x, remaining_y);
621
622    //         // Validate that pool always maintains at least some tokens of both types
623    //         assert!(
624    //             remaining_x > 0,
625    //             "Pool should always maintain at least some X tokens. Got: {}",
626    //             remaining_x
627    //         );
628    //         assert!(
629    //             remaining_y > 0,
630    //             "Pool should always maintain at least some Y tokens. Got: {}",
631    //             remaining_y
632    //         );
633
634    //         // It's acceptable for users to receive 0 tokens of one type due to rounding
635    //         if withdrawal_result.token_x_amount == 0 {
636    //             println!("Note: User received 0 X tokens (acceptable due to rounding)");
637    //         }
638    //         if withdrawal_result.token_y_amount == 0 {
639    //             println!("Note: User received 0 Y tokens (acceptable due to rounding)");
640    //         }
641
642    //         println!(
643    //             "✓ Pool maintains minimum tokens: {} X + {} Y",
644    //             remaining_x, remaining_y
645    //         );
646    //     }
647    // }
648
649    // #[test]
650    // fn lp_calculation_around_100_lp_tokens() {
651    //     // This tests validates that submissions of ~100 lp will result
652    //     // in <=100 lp tokens, these calls would fail
653
654    //     let test_cases = vec![
655    //         (1u128, 100u128),
656    //         (100u128, 1u128),
657    //         (33u128, 33u128),
658    //         (1u128, 1u128),
659    //     ];
660
661    //     for (token_x_amount, token_y_amount) in test_cases {
662    //         let initial_liquidity = initialize_pool_liquidity(token_x_amount, token_y_amount);
663
664    //         assert!(initial_liquidity <= 100);
665    //     }
666    // }
667
668    // #[test]
669    // fn add_liquidity_preserves_ratio_and_constant_product() {
670    //     // This test verifies that add_liquidity equivalent call preserves the original x/y ratio
671    //     // and that the constant product K is preserved and always growing
672
673    //     let test_cases = vec![
674    //         (1_000u128, 1_000u128), // 1:1 ratio
675    //         (1_000u128, 2_000u128), // 1:2 ratio
676    //         (2_000u128, 1_000u128), // 2:1 ratio
677    //         (100u128, 10_000u128),  // 1:100 ratio
678    //         (10_000u128, 100u128),  // 100:1 ratio
679    //         (1u128, 1_000_000u128), // 1:1,000,000 ratio
680    //         (1_000_000u128, 1u128), // 1,000,000:1 ratio
681    //     ];
682
683    //     for (initial_x, initial_y) in test_cases {
684    //         println!(
685    //             "\n=== Testing add_liquidity ratio preservation {}:{} ===",
686    //             initial_x, initial_y
687    //         );
688
689    //         // Step 1: Initialize pool
690    //         let initial_liquidity = initialize_pool_liquidity(initial_x, initial_y);
691    //         let initial_k = initial_x * initial_y;
692    //         let initial_ratio = initial_x as f64 / initial_y as f64;
693
694    //         println!(
695    //             "Initial: {} X + {} Y (liquidity: {}, K: {}, ratio: {:.6})",
696    //             initial_x, initial_y, initial_liquidity, initial_k, initial_ratio
697    //         );
698
699    //         // Step 2: Simulate adding liquidity (equivalent to add_liquidity call)
700    //         // We'll add different amounts of LP tokens to test various scenarios
701    //         let add_lp_amounts = vec![
702    //             1u128, 2u128, 5u128, 10u128, 200u128, 500u128, 1000u128, 2000u128, 5000u128,
703    //             10000u128,
704    //         ];
705
706    //         for add_lp_amount in add_lp_amounts {
707    //             // Calculate required tokens using the same logic as add_liquidity
708    //             let results = lp_tokens_to_trading_tokens(
709    //                 add_lp_amount,
710    //                 initial_liquidity as u128,
711    //                 initial_x,
712    //                 initial_y,
713    //                 RoundDirection::Ceiling, // Same as add_liquidity
714    //             )
715    //             .unwrap();
716
717    //             if results.token_x_amount == 0 || results.token_y_amount == 0 {
718    //                 println!(
719    //                     "  ⚠️  This would trigger TooFewTokensSupplied error in add_liquidity"
720    //                 );
721    //                 continue;
722    //             }
723
724    //             let new_x = initial_x + results.token_x_amount;
725    //             let new_y = initial_y + results.token_y_amount;
726    //             let new_k = new_x * new_y;
727    //             let new_ratio = new_x as f64 / new_y as f64;
728
729    //             println!(
730    //                 "  Add {} LP -> {} X + {} Y (K: {}, ratio: {:.6})",
731    //                 add_lp_amount, results.token_x_amount, results.token_y_amount, new_k, new_ratio
732    //             );
733
734    //             // Verify that constant product K is preserved and growing
735    //             assert!(
736    //                 new_k >= initial_k,
737    //                 "Constant product K should be preserved and growing. Initial K: {}, New K: {}",
738    //                 initial_k,
739    //                 new_k
740    //             );
741    //         }
742    //     }
743    // }
744
745    #[test]
746    fn test_from_to_lock_transition_manually() {
747        // Test cases with different ratios and amounts - both small and large values
748        // Format: (to_amount_swapped, current_source_amount, current_destination_amount, original_source_amount, original_destination_amount, is_out_of_range, tolerance_rate)
749        let test_cases = vec![
750            (500u64, 100u64, 1000000u64, 100u64, 1000000u64, true, 100), // 1:1000 fails - 0.05..2% change - allowed 0.01%
751            (500u64, 100u64, 1000000u64, 100u64, 1000000u64, true, 499), // 1:1000 fails - 0.05..2% change - allowed 0.0499%
752            (500u64, 100u64, 1000000u64, 100u64, 1000000u64, true, 500), // 1:1000 fails - 0.05..2% change - allowed 0.05%
753            (500u64, 100u64, 1000000u64, 100u64, 1000000u64, false, 501), // 1:1000 passes - 0.05..2% change - allowed 0.05%
754            // real world
755            (
756                1980148883u64,
757                1_000_000u64,
758                2_000_000_000u64,
759                1_000_000u64,
760                2_000_000_000u64,
761                false,
762                100,
763            ), // 1:2000
764            (
765                1980148883u64,
766                1_000_000u64,
767                2_000_000_000u64,
768                1_000_000u64,
769                2_000_000_000u64,
770                true,
771                40,
772            ), // 1:2000
773            // real world with pending trades
774            (
775                10_000_000u64,
776                9_926u64,
777                19_851_117u64,
778                1_000_000u64,
779                2_000_000_000u64,
780                true,
781                40,
782            ), // 1:2000
783            // extreme cases
784            (49u64, 1u64, 100u64, 1u64, 100u64, false, 990000), // 1:1000 passes - 99% change - allowed 99%
785            // impossible cases
786            (100u64, 1u64, 100u64, 1u64, 100u64, true, 990000), // 1:1000 passes - 0.05% change - allowed 0.05%
787            (100u64, 0u64, 100u64, 1u64, 100u64, true, 1000000), // 1:1000 passes - 0.05% change - allowed 0.05%
788            (100u64, 100u64, 0u64, 1u64, 100u64, true, 1000000), // 1:1000 passes - 0.05% change - allowed 0.05%
789        ];
790
791        for (
792            to_amount_swapped,
793            current_source_amount,
794            current_destination_amount,
795            original_source_amount,
796            original_destination_amount,
797            is_out_of_range,
798            tolerance_rate,
799        ) in test_cases
800        {
801            println!("\n=== Testing from_to_lock accuracy for pool {}:{} with current {}:{} with swap {} ===",
802                original_source_amount, original_destination_amount, current_source_amount, current_destination_amount, to_amount_swapped);
803
804            // Use the rebalance_pool_ratio function to calculate from_to_lock
805            let rebalance_result = rebalance_pool_ratio(
806                to_amount_swapped,
807                current_source_amount,
808                current_destination_amount,
809                original_source_amount,
810                original_destination_amount,
811                tolerance_rate,
812            )
813            .unwrap();
814
815            println!("Rebalance result: {:?}", rebalance_result);
816
817            // The rebalance function should correctly identify if the ratio change is within tolerance
818            assert_eq!(
819                rebalance_result.is_rate_tolerance_exceeded, is_out_of_range,
820                "Rebalance should correctly identify ratio tolerance. Expected: {}, Got: {}",
821                is_out_of_range, rebalance_result.is_rate_tolerance_exceeded
822            );
823        }
824    }
825}