From db2105af7788661e9a75a1ae19dfdda95c6fa777 Mon Sep 17 00:00:00 2001 From: 0xh3rman <119309671+0xh3rman@users.noreply.github.com> Date: Sun, 24 Nov 2024 10:17:58 +0700 Subject: [PATCH] Make `compute_swap` function public (#535) * make compute_swap method public * refine comments, fix build warning --- rust-sdk/core/src/math/tick_array.rs | 4 ++-- rust-sdk/core/src/quote/swap.rs | 35 ++++++++++++++++++++++------ 2 files changed, 30 insertions(+), 9 deletions(-) diff --git a/rust-sdk/core/src/math/tick_array.rs b/rust-sdk/core/src/math/tick_array.rs index ff6548c87..2402d2cbb 100644 --- a/rust-sdk/core/src/math/tick_array.rs +++ b/rust-sdk/core/src/math/tick_array.rs @@ -10,8 +10,8 @@ use super::{ #[derive(Clone, Debug, PartialEq, Eq)] pub struct TickArraySequence { - tick_arrays: [Option; SIZE], - tick_spacing: u16, + pub tick_arrays: [Option; SIZE], + pub tick_spacing: u16, } impl TickArraySequence { diff --git a/rust-sdk/core/src/quote/swap.rs b/rust-sdk/core/src/quote/swap.rs index 55d0b4293..dc4a74d50 100644 --- a/rust-sdk/core/src/quote/swap.rs +++ b/rust-sdk/core/src/quote/swap.rs @@ -148,15 +148,34 @@ pub fn swap_quote_by_output_token( }) } -// Private functions - -struct SwapResult { - token_a: u64, - token_b: u64, - trade_fee: u64, +pub struct SwapResult { + pub token_a: u64, + pub token_b: u64, + pub trade_fee: u64, } -fn compute_swap( +/// Computes the amounts of tokens A and B based on the current Whirlpool 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. +/// - `whirlpool`: The current state of the Whirlpool 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( token_amount: u64, sqrt_price_limit: u128, whirlpool: WhirlpoolFacade, @@ -275,6 +294,8 @@ fn compute_swap( }) } +// Private functions + fn get_next_liquidity( current_liquidity: u128, next_tick: Option<&TickFacade>,