fusionamm-core 1.0.34

FusionAMM core rust package.
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
use crate::{
    get_limit_order_output_amount, sqrt_price_to_tick_index, tick_index_to_sqrt_price, try_apply_swap_fee, try_apply_transfer_fee,
    try_get_amount_delta_a, try_get_amount_delta_b, try_get_max_amount_with_slippage_tolerance, try_get_min_amount_with_slippage_tolerance,
    try_get_next_sqrt_price_from_a, try_get_next_sqrt_price_from_b, try_mul_div, try_reverse_apply_swap_fee, try_reverse_apply_transfer_fee,
    CoreError, ExactInSwapQuote, ExactOutSwapQuote, FusionPoolFacade, TickArraySequence, TickArrays, TickFacade, TransferFee, AMOUNT_EXCEEDS_MAX_U64,
    ARITHMETIC_OVERFLOW, FEE_RATE_DENOMINATOR, INVALID_SQRT_PRICE_LIMIT_DIRECTION, MAX_SQRT_PRICE, MIN_SQRT_PRICE, SQRT_PRICE_LIMIT_OUT_OF_BOUNDS,
    ZERO_TRADABLE_AMOUNT,
};

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

/// Computes the exact input or output amount for a swap transaction.
///
/// # Arguments
/// - `token_in`: The input token amount.
/// - `specified_token_a`: If `true`, the input token is token A. Otherwise, it is token B.
/// - `slippage_tolerance`: The slippage tolerance in basis points.
/// - `fusion_pool`: The fusion_pool state.
/// - `tick_arrays`: The tick arrays needed for the swap.
/// - `transfer_fee_a`: The transfer fee for token A.
/// - `transfer_fee_b`: The transfer fee for token B.
///
/// # Returns
/// The exact input or output amount for the swap transaction.
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn swap_quote_by_input_token(
    token_in: u64,
    specified_token_a: bool,
    slippage_tolerance_bps: u16,
    fusion_pool: FusionPoolFacade,
    tick_arrays: TickArrays,
    transfer_fee_a: Option<TransferFee>,
    transfer_fee_b: Option<TransferFee>,
) -> Result<ExactInSwapQuote, CoreError> {
    let (transfer_fee_in, transfer_fee_out) = if specified_token_a {
        (transfer_fee_a, transfer_fee_b)
    } else {
        (transfer_fee_b, transfer_fee_a)
    };
    let token_in_after_fee = try_apply_transfer_fee(token_in.into(), transfer_fee_in.unwrap_or_default())?;

    let tick_sequence = TickArraySequence::new(tick_arrays.into(), fusion_pool.tick_spacing)?;

    let swap_result = compute_swap(token_in_after_fee.into(), 0, fusion_pool, tick_sequence, specified_token_a, true, 0)?;

    let (token_in_after_fees, token_est_out_before_fee) = if specified_token_a {
        (swap_result.token_a, swap_result.token_b)
    } else {
        (swap_result.token_b, swap_result.token_a)
    };

    let token_in = try_reverse_apply_transfer_fee(token_in_after_fees, transfer_fee_in.unwrap_or_default())?;

    let token_est_out = try_apply_transfer_fee(token_est_out_before_fee, transfer_fee_out.unwrap_or_default())?;

    let token_min_out = try_get_min_amount_with_slippage_tolerance(token_est_out, slippage_tolerance_bps)?;

    Ok(ExactInSwapQuote {
        token_in,
        token_est_out,
        token_min_out,
        trade_fee: swap_result.fee_amount,
    })
}

/// Computes the exact input or output amount for a swap transaction.
///
/// # Arguments
/// - `token_out`: The output token amount.
/// - `specified_token_a`: If `true`, the output token is token A. Otherwise, it is token B.
/// - `slippage_tolerance`: The slippage tolerance in basis points.
/// - `fusion_pool`: The fusion_pool state.
/// - `tick_arrays`: The tick arrays needed for the swap.
/// - `transfer_fee_a`: The transfer fee for token A.
/// - `transfer_fee_b`: The transfer fee for token B.
///
/// # Returns
/// The exact input or output amount for the swap transaction.
#[cfg_attr(feature = "wasm", wasm_expose)]
pub fn swap_quote_by_output_token(
    token_out: u64,
    specified_token_a: bool,
    slippage_tolerance_bps: u16,
    fusion_pool: FusionPoolFacade,
    tick_arrays: TickArrays,
    transfer_fee_a: Option<TransferFee>,
    transfer_fee_b: Option<TransferFee>,
) -> Result<ExactOutSwapQuote, CoreError> {
    let (transfer_fee_in, transfer_fee_out) = if specified_token_a {
        (transfer_fee_b, transfer_fee_a)
    } else {
        (transfer_fee_a, transfer_fee_b)
    };
    let token_out_before_fee = try_reverse_apply_transfer_fee(token_out, transfer_fee_out.unwrap_or_default())?;

    let tick_sequence = TickArraySequence::new(tick_arrays.into(), fusion_pool.tick_spacing)?;

    let swap_result = compute_swap(token_out_before_fee.into(), 0, fusion_pool, tick_sequence, !specified_token_a, false, 0)?;

    let (token_out_before_fee, token_est_in_after_fee) = if specified_token_a {
        (swap_result.token_a, swap_result.token_b)
    } else {
        (swap_result.token_b, swap_result.token_a)
    };

    let token_out = try_apply_transfer_fee(token_out_before_fee, transfer_fee_out.unwrap_or_default())?;

    let token_est_in = try_reverse_apply_transfer_fee(token_est_in_after_fee, transfer_fee_in.unwrap_or_default())?;

    let token_max_in = try_get_max_amount_with_slippage_tolerance(token_est_in, slippage_tolerance_bps)?;

    Ok(ExactOutSwapQuote {
        token_out,
        token_est_in,
        token_max_in,
        trade_fee: swap_result.fee_amount,
    })
}

pub struct SwapResult {
    pub token_a: u64,
    pub token_b: u64,
    pub fee_amount: u64,
}

/// Computes the amounts of tokens A and B based on the current FusionPool state and tick sequence.
///
/// # Arguments
/// - `token_amount`: The input or output amount specified for the swap. Must be non-zero.
/// - `sqrt_price_limit`: The price limit for the swap represented as a square root.
///    If set to `0`, it defaults to the minimum or maximum sqrt price based on the direction of the swap.
/// - `fusion_pool`: The current state of the FusionPool AMM, including liquidity, price, and tick information.
/// - `tick_sequence`: A sequence of ticks used to determine price levels during the swap process.
/// - `a_to_b`: Indicates the direction of the swap:
///    - `true`: Swap from token A to token B.
///    - `false`: Swap from token B to token A.
/// - `specified_input`: Determines if the input amount is specified:
///    - `true`: `token_amount` represents the input amount.
///    - `false`: `token_amount` represents the output amount.
/// - `_timestamp`: A placeholder for future full swap logic, currently ignored.
///
/// # Returns
/// A `Result` containing a `SwapResult` struct if the swap is successful, or an `ErrorCode` if the computation fails.
/// # Notes
/// - This function doesn't take into account slippage tolerance.
/// - This function doesn't take into account transfer fee extension.
pub fn compute_swap<const SIZE: usize>(
    token_amount: u64,
    sqrt_price_limit: u128,
    fusion_pool: FusionPoolFacade,
    tick_sequence: TickArraySequence<SIZE>,
    a_to_b: bool,
    specified_input: bool,
    _timestamp: u64, // currently ignored but needed for full swap logic
) -> Result<SwapResult, CoreError> {
    let sqrt_price_limit = if sqrt_price_limit == 0 {
        if a_to_b {
            MIN_SQRT_PRICE
        } else {
            MAX_SQRT_PRICE
        }
    } else {
        sqrt_price_limit
    };

    if !(MIN_SQRT_PRICE..=MAX_SQRT_PRICE).contains(&sqrt_price_limit) {
        return Err(SQRT_PRICE_LIMIT_OUT_OF_BOUNDS);
    }

    if a_to_b && sqrt_price_limit > fusion_pool.sqrt_price || !a_to_b && sqrt_price_limit < fusion_pool.sqrt_price {
        return Err(INVALID_SQRT_PRICE_LIMIT_DIRECTION);
    }

    if token_amount == 0 {
        return Err(ZERO_TRADABLE_AMOUNT);
    }

    let mut amount_remaining = token_amount;
    let mut amount_calculated = 0u64;
    let mut current_sqrt_price = fusion_pool.sqrt_price;
    let mut current_tick_index = fusion_pool.tick_current_index;
    let mut current_liquidity = fusion_pool.liquidity;
    let mut fee_amount = 0;

    while amount_remaining > 0 && sqrt_price_limit != current_sqrt_price {
        let (next_tick, next_tick_index) = if a_to_b {
            tick_sequence.prev_initialized_tick(current_tick_index)?
        } else {
            tick_sequence.next_initialized_tick(current_tick_index)?
        };
        let next_tick_sqrt_price: u128 = tick_index_to_sqrt_price(next_tick_index.into()).into();
        let target_sqrt_price = if a_to_b {
            next_tick_sqrt_price.max(sqrt_price_limit)
        } else {
            next_tick_sqrt_price.min(sqrt_price_limit)
        };

        let step_quote = compute_swap_step(
            amount_remaining,
            fusion_pool.fee_rate,
            current_liquidity,
            current_sqrt_price,
            target_sqrt_price,
            a_to_b,
            specified_input,
        )?;

        fee_amount += step_quote.fee_amount;

        if specified_input {
            amount_remaining = amount_remaining
                .checked_sub(step_quote.amount_in)
                .ok_or(ARITHMETIC_OVERFLOW)?
                .checked_sub(step_quote.fee_amount)
                .ok_or(ARITHMETIC_OVERFLOW)?;
            amount_calculated = amount_calculated.checked_add(step_quote.amount_out).ok_or(ARITHMETIC_OVERFLOW)?;
        } else {
            amount_remaining = amount_remaining.checked_sub(step_quote.amount_out).ok_or(ARITHMETIC_OVERFLOW)?;
            amount_calculated = amount_calculated
                .checked_add(step_quote.amount_in)
                .ok_or(ARITHMETIC_OVERFLOW)?
                .checked_add(step_quote.fee_amount)
                .ok_or(ARITHMETIC_OVERFLOW)?;
        }

        if step_quote.next_sqrt_price == next_tick_sqrt_price {
            let limit_swap_computation =
                fill_limit_orders(next_tick, next_tick_sqrt_price, a_to_b, specified_input, amount_remaining, fusion_pool.fee_rate)?;

            fee_amount += limit_swap_computation.fee_amount;

            if specified_input {
                amount_remaining = amount_remaining
                    .checked_sub(limit_swap_computation.amount_in)
                    .ok_or(ARITHMETIC_OVERFLOW)?
                    .checked_sub(limit_swap_computation.fee_amount)
                    .ok_or(ARITHMETIC_OVERFLOW)?;
                amount_calculated = amount_calculated
                    .checked_add(limit_swap_computation.amount_out)
                    .ok_or(ARITHMETIC_OVERFLOW)?;
            } else {
                amount_remaining = amount_remaining
                    .checked_sub(limit_swap_computation.amount_out)
                    .ok_or(ARITHMETIC_OVERFLOW)?;
                amount_calculated = amount_calculated
                    .checked_add(limit_swap_computation.amount_in)
                    .ok_or(ARITHMETIC_OVERFLOW)?
                    .checked_add(limit_swap_computation.fee_amount)
                    .ok_or(ARITHMETIC_OVERFLOW)?;
            };

            current_liquidity = get_next_liquidity(current_liquidity, next_tick, a_to_b);
            current_tick_index = if a_to_b { next_tick_index - 1 } else { next_tick_index }
        } else if step_quote.next_sqrt_price != current_sqrt_price {
            current_tick_index = sqrt_price_to_tick_index(step_quote.next_sqrt_price.into()).into();
        }

        current_sqrt_price = step_quote.next_sqrt_price;
    }

    let swapped_amount = token_amount - amount_remaining;

    let token_a = if a_to_b == specified_input { swapped_amount } else { amount_calculated };
    let token_b = if a_to_b == specified_input { amount_calculated } else { swapped_amount };

    Ok(SwapResult {
        token_a,
        token_b,
        fee_amount,
    })
}

pub(crate) fn get_next_liquidity(current_liquidity: u128, next_tick: Option<&TickFacade>, a_to_b: bool) -> u128 {
    let liquidity_net = next_tick.map(|tick| tick.liquidity_net).unwrap_or(0);
    let liquidity_net_unsigned = liquidity_net.unsigned_abs();
    if a_to_b {
        if liquidity_net < 0 {
            current_liquidity + liquidity_net_unsigned
        } else {
            current_liquidity - liquidity_net_unsigned
        }
    } else if liquidity_net < 0 {
        current_liquidity - liquidity_net_unsigned
    } else {
        current_liquidity + liquidity_net_unsigned
    }
}

// Private functions

#[derive(PartialEq, Debug, Default)]
pub struct LimitSwapComputation {
    pub amount_in: u64,
    pub fee_amount: u64,
    pub amount_out: u64,
}

fn fill_limit_orders(
    tick: Option<&TickFacade>,
    sqrt_price: u128,
    a_to_b: bool,
    amount_specified_is_input: bool,
    amount_remaining: u64,
    fee_rate: u16,
) -> Result<LimitSwapComputation, CoreError> {
    let mut result = LimitSwapComputation::default();

    if let Some(tick) = tick {
        let part_filled_orders_remaining_input = tick.open_orders_input + tick.part_filled_orders_remaining_input;

        if amount_specified_is_input {
            // Total possible swap input.
            result.amount_in = get_limit_order_output_amount(part_filled_orders_remaining_input, !a_to_b, sqrt_price, false)?;
            // The total amount of the limit order input token that can be swapped.
            result.amount_out = part_filled_orders_remaining_input;
            // Swap fee in input token.
            result.fee_amount = try_mul_div(result.amount_in, fee_rate as u128, FEE_RATE_DENOMINATOR as u128 - fee_rate as u128, true)?;

            // Not enough input remaining amount to fill all limit orders of the tick.
            if amount_remaining < result.amount_in + result.fee_amount {
                let total_available_amount_in = result.amount_in;

                // Swap fee in input token.
                result.fee_amount = try_mul_div(amount_remaining, fee_rate as u128, FEE_RATE_DENOMINATOR as u128, true)?;

                // Total possible swap input minus fee amount.
                result.amount_in = amount_remaining - result.fee_amount;

                // Swap output
                result.amount_out =
                    try_mul_div(part_filled_orders_remaining_input, result.amount_in as u128, total_available_amount_in as u128, false)?;
            }
        } else {
            // The total amount of the limit order input token that can be swapped.
            result.amount_out = part_filled_orders_remaining_input.min(amount_remaining);
            // Swap input
            result.amount_in = get_limit_order_output_amount(result.amount_out, !a_to_b, sqrt_price, true)?;
            result.fee_amount = try_mul_div(result.amount_in, fee_rate as u128, FEE_RATE_DENOMINATOR as u128 - fee_rate as u128, true)?;
        }
    }

    Ok(result)
}

struct SwapStepQuote {
    amount_in: u64,
    amount_out: u64,
    next_sqrt_price: u128,
    fee_amount: u64,
}

fn compute_swap_step(
    amount_remaining: u64,
    fee_rate: u16,
    current_liquidity: u128,
    current_sqrt_price: u128,
    target_sqrt_price: u128,
    a_to_b: bool,
    specified_input: bool,
) -> Result<SwapStepQuote, CoreError> {
    // Any error that is not AMOUNT_EXCEEDS_MAX_U64 is not recoverable
    let initial_amount_fixed_delta = try_get_amount_fixed_delta(current_sqrt_price, target_sqrt_price, current_liquidity, a_to_b, specified_input);
    let is_initial_amount_fixed_overflow = initial_amount_fixed_delta == Err(AMOUNT_EXCEEDS_MAX_U64);

    let amount_calculated = if specified_input {
        try_apply_swap_fee(amount_remaining.into(), fee_rate)?
    } else {
        amount_remaining
    };

    let next_sqrt_price = if !is_initial_amount_fixed_overflow && initial_amount_fixed_delta? <= amount_calculated {
        target_sqrt_price
    } else {
        try_get_next_sqrt_price(current_sqrt_price, current_liquidity, amount_calculated, a_to_b, specified_input)?
    };

    let is_max_swap = next_sqrt_price == target_sqrt_price;

    let amount_unfixed_delta = try_get_amount_unfixed_delta(current_sqrt_price, next_sqrt_price, current_liquidity, a_to_b, specified_input)?;

    // If the swap is not at the max, we need to readjust the amount of the fixed token we are using
    let amount_fixed_delta = if !is_max_swap || is_initial_amount_fixed_overflow {
        try_get_amount_fixed_delta(current_sqrt_price, next_sqrt_price, current_liquidity, a_to_b, specified_input)?
    } else {
        initial_amount_fixed_delta?
    };

    let (amount_in, mut amount_out) = if specified_input {
        (amount_fixed_delta, amount_unfixed_delta)
    } else {
        (amount_unfixed_delta, amount_fixed_delta)
    };

    // Cap output amount if using output
    if !specified_input && amount_out > amount_remaining {
        amount_out = amount_remaining;
    }

    let fee_amount = if specified_input && !is_max_swap {
        amount_remaining - amount_in
    } else {
        let pre_fee_amount = try_reverse_apply_swap_fee(amount_in.into(), fee_rate)?;
        pre_fee_amount - amount_in
    };

    Ok(SwapStepQuote {
        amount_in,
        amount_out,
        next_sqrt_price,
        fee_amount,
    })
}

fn try_get_amount_fixed_delta(
    current_sqrt_price: u128,
    target_sqrt_price: u128,
    current_liquidity: u128,
    a_to_b: bool,
    specified_input: bool,
) -> Result<u64, CoreError> {
    if a_to_b == specified_input {
        try_get_amount_delta_a(current_sqrt_price.into(), target_sqrt_price.into(), current_liquidity.into(), specified_input)
    } else {
        try_get_amount_delta_b(current_sqrt_price.into(), target_sqrt_price.into(), current_liquidity.into(), specified_input)
    }
}

fn try_get_amount_unfixed_delta(
    current_sqrt_price: u128,
    target_sqrt_price: u128,
    current_liquidity: u128,
    a_to_b: bool,
    specified_input: bool,
) -> Result<u64, CoreError> {
    if specified_input == a_to_b {
        try_get_amount_delta_b(current_sqrt_price.into(), target_sqrt_price.into(), current_liquidity.into(), !specified_input)
    } else {
        try_get_amount_delta_a(current_sqrt_price.into(), target_sqrt_price.into(), current_liquidity.into(), !specified_input)
    }
}

fn try_get_next_sqrt_price(
    current_sqrt_price: u128,
    current_liquidity: u128,
    amount_calculated: u64,
    a_to_b: bool,
    specified_input: bool,
) -> Result<u128, CoreError> {
    if specified_input == a_to_b {
        try_get_next_sqrt_price_from_a(current_sqrt_price.into(), current_liquidity.into(), amount_calculated.into(), specified_input)
            .map(|x| x.into())
    } else {
        try_get_next_sqrt_price_from_b(current_sqrt_price.into(), current_liquidity.into(), amount_calculated.into(), specified_input)
            .map(|x| x.into())
    }
}

#[cfg(all(test, not(feature = "wasm")))]
mod tests {
    use crate::{TickArrayFacade, INVALID_TICK_ARRAY_SEQUENCE, TICK_ARRAY_SIZE};

    use super::*;

    fn test_fusion_pool(sqrt_price: u128, sufficient_liq: bool) -> FusionPoolFacade {
        let tick_current_index = sqrt_price_to_tick_index(sqrt_price);
        let liquidity = if sufficient_liq { 100000000 } else { 265000 };
        FusionPoolFacade {
            tick_current_index,
            fee_rate: 3000,
            liquidity,
            sqrt_price,
            tick_spacing: 2,
            ..FusionPoolFacade::default()
        }
    }

    fn test_fusion_pool_with_zero_liquidity(sqrt_price: u128) -> FusionPoolFacade {
        let tick_current_index = sqrt_price_to_tick_index(sqrt_price);
        FusionPoolFacade {
            tick_current_index,
            fee_rate: 10000,
            order_protocol_fee_rate: 10000,
            protocol_fee_rate: 1000,
            liquidity: 0,
            sqrt_price,
            tick_spacing: 2,
            ..FusionPoolFacade::default()
        }
    }

    fn test_tick(liquidity_net: i128, limit_amount: u64) -> TickFacade {
        TickFacade {
            initialized: true,
            liquidity_net,
            part_filled_orders_input: limit_amount,
            part_filled_orders_remaining_input: limit_amount,
            ..TickFacade::default()
        }
    }

    fn test_tick_array(start_tick_index: i32) -> TickArrayFacade {
        let liquidity_net = if start_tick_index < 0 { 1000 } else { -1000 };
        TickArrayFacade {
            start_tick_index,
            ticks: [test_tick(liquidity_net, 0); TICK_ARRAY_SIZE],
        }
    }

    fn test_tick_array_with_orders(start_tick_index: i32) -> TickArrayFacade {
        TickArrayFacade {
            start_tick_index,
            ticks: [test_tick(0, 10000); TICK_ARRAY_SIZE],
        }
    }

    fn test_tick_arrays() -> TickArrays {
        [
            test_tick_array(0),
            test_tick_array(176),
            test_tick_array(352),
            test_tick_array(-176),
            test_tick_array(-352),
        ]
        .into()
    }

    fn test_tick_arrays_with_orders() -> TickArrays {
        [
            test_tick_array_with_orders(0),
            test_tick_array_with_orders(176),
            test_tick_array_with_orders(352),
            test_tick_array_with_orders(-176),
            test_tick_array_with_orders(-352),
        ]
        .into()
    }

    #[test]
    fn test_exact_in_a_to_b_simple() {
        let result = swap_quote_by_input_token(1000, true, 1000, test_fusion_pool(1 << 64, true), test_tick_arrays(), None, None).unwrap();
        assert_eq!(result.token_in, 1000);
        assert_eq!(result.token_est_out, 996);
        assert_eq!(result.token_min_out, 896);
        assert_eq!(result.trade_fee, 3);
    }

    #[test]
    fn test_exact_in_a_to_b() {
        let result = swap_quote_by_input_token(1000, true, 1000, test_fusion_pool(1 << 64, false), test_tick_arrays(), None, None).unwrap();
        assert_eq!(result.token_in, 1000);
        assert_eq!(result.token_est_out, 920);
        assert_eq!(result.token_min_out, 828);
        assert_eq!(result.trade_fee, 38);
    }

    #[test]
    fn test_exact_in_b_to_a_simple() {
        let result = swap_quote_by_input_token(1000, false, 1000, test_fusion_pool(1 << 64, true), test_tick_arrays(), None, None).unwrap();
        assert_eq!(result.token_in, 1000);
        assert_eq!(result.token_est_out, 996);
        assert_eq!(result.token_min_out, 896);
        assert_eq!(result.trade_fee, 3);
    }

    #[test]
    fn test_exact_in_b_to_a() {
        let result = swap_quote_by_input_token(1000, false, 1000, test_fusion_pool(1 << 64, false), test_tick_arrays(), None, None).unwrap();
        assert_eq!(result.token_in, 1000);
        assert_eq!(result.token_est_out, 918);
        assert_eq!(result.token_min_out, 826);
        assert_eq!(result.trade_fee, 39);
    }

    #[test]
    fn test_exact_out_a_to_b_simple() {
        let result = swap_quote_by_output_token(1000, false, 1000, test_fusion_pool(1 << 64, true), test_tick_arrays(), None, None).unwrap();
        assert_eq!(result.token_out, 1000);
        assert_eq!(result.token_est_in, 1005);
        assert_eq!(result.token_max_in, 1106);
        assert_eq!(result.trade_fee, 4);
    }

    #[test]
    fn test_exact_out_a_to_b() {
        let result = swap_quote_by_output_token(1000, false, 1000, test_fusion_pool(1 << 64, false), test_tick_arrays(), None, None).unwrap();
        assert_eq!(result.token_out, 1000);
        assert_eq!(result.token_est_in, 1088);
        assert_eq!(result.token_max_in, 1197);
        assert_eq!(result.trade_fee, 42);
    }

    #[test]
    fn test_exact_out_b_to_a_simple() {
        let result = swap_quote_by_output_token(1000, true, 1000, test_fusion_pool(1 << 64, true), test_tick_arrays(), None, None).unwrap();
        assert_eq!(result.token_out, 1000);
        assert_eq!(result.token_est_in, 1005);
        assert_eq!(result.token_max_in, 1106);
        assert_eq!(result.trade_fee, 4);
    }

    #[test]
    fn test_exact_out_b_to_a() {
        let result = swap_quote_by_output_token(1000, true, 1000, test_fusion_pool(1 << 64, false), test_tick_arrays(), None, None).unwrap();
        assert_eq!(result.token_out, 1000);
        assert_eq!(result.token_est_in, 1088);
        assert_eq!(result.token_max_in, 1197);
        assert_eq!(result.trade_fee, 42);
    }

    #[test]
    /// The test is equal to swap_manager::swap_with_limit_orders_tests::test_for_swap_quote_zero_liquidity_a_to_b_exact_in() in FusionAMM program.
    fn test_exact_in_a_to_b_with_orders() {
        let result =
            swap_quote_by_input_token(85000, true, 1000, test_fusion_pool_with_zero_liquidity(1 << 64), test_tick_arrays_with_orders(), None, None)
                .unwrap();
        assert_eq!(result.token_in, 85000);
        assert_eq!(result.token_est_out, 84079);
        assert_eq!(result.token_min_out, 75671);
        assert_eq!(result.trade_fee, 858);
    }

    #[test]
    /// The test is equal to swap_manager::swap_with_limit_orders_tests::test_for_swap_quote_zero_liquidity_a_to_b_exact_out() in FusionAMM program.
    fn test_exact_out_a_to_b_with_orders() {
        let result =
            swap_quote_by_output_token(85000, false, 1000, test_fusion_pool_with_zero_liquidity(1 << 64), test_tick_arrays_with_orders(), None, None)
                .unwrap();
        assert_eq!(result.token_out, 85000);
        assert_eq!(result.token_est_in, 85939);
        assert_eq!(result.token_max_in, 94533);
        assert_eq!(result.trade_fee, 867);
    }

    #[test]
    /// The test is equal to swap_manager::swap_with_limit_orders_tests::test_for_swap_quote_zero_liquidity_b_to_a_exact_in() in FusionAMM program.
    fn test_exact_in_b_to_a_with_orders() {
        let result =
            swap_quote_by_input_token(85000, false, 1000, test_fusion_pool_with_zero_liquidity(1 << 64), test_tick_arrays_with_orders(), None, None)
                .unwrap();
        assert_eq!(result.token_in, 85000);
        assert_eq!(result.token_est_out, 84062);
        assert_eq!(result.token_min_out, 75655);
        assert_eq!(result.trade_fee, 858);
    }

    #[test]
    /// The test is equal to swap_manager::swap_with_limit_orders_tests::test_for_swap_quote_zero_liquidity_b_to_a_exact_out() in FusionAMM program.
    fn test_exact_out_b_to_a_with_orders() {
        let result =
            swap_quote_by_output_token(85000, true, 1000, test_fusion_pool_with_zero_liquidity(1 << 64), test_tick_arrays_with_orders(), None, None)
                .unwrap();
        assert_eq!(result.token_out, 85000);
        assert_eq!(result.token_est_in, 85957);
        assert_eq!(result.token_max_in, 94553);
        assert_eq!(result.trade_fee, 867);
    }

    #[test]
    fn test_swap_quote_throws_if_tick_array_sequence_holds_insufficient_liquidity() {
        let result_3428 = swap_quote_by_input_token(3428, true, 0, test_fusion_pool(1 << 64, false), test_tick_arrays(), None, None).unwrap();
        let result_3429 = swap_quote_by_input_token(3429, true, 0, test_fusion_pool(1 << 64, false), test_tick_arrays(), None, None);
        assert_eq!(result_3428.token_in, 3428);
        assert!(matches!(result_3429, Err(INVALID_TICK_ARRAY_SEQUENCE)));
    }
}