From 85a7b58d5528a50b189a524724839abd893f9eab Mon Sep 17 00:00:00 2001 From: surbhi Date: Wed, 26 Nov 2025 12:47:03 -0400 Subject: [PATCH] abstracting out the slippage formula --- src/hooks/usePartyPool.ts | 33 +++++++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/src/hooks/usePartyPool.ts b/src/hooks/usePartyPool.ts index 1781fe0..9e56906 100644 --- a/src/hooks/usePartyPool.ts +++ b/src/hooks/usePartyPool.ts @@ -11,6 +11,30 @@ import type { AvailableToken } from './usePartyPlanner'; // Q96 constant for price calculations const Q96 = 1n << 96n; +/** + * Calculate slippage percentage based on market price and actual swap execution price + * @param marketPrice The current market price from the pool (in Q64 format, already converted to decimal) + * @param swapOutputAmount The output amount from the swap + * @param swapInputAmount The input amount for the swap + * @param swapFee The fee charged for the swap + * @returns Slippage as a percentage (e.g., 5.5 means 5.5%) + */ +export function calculateSlippage( + marketPrice: number, + swapOutputAmount: bigint, + swapInputAmount: bigint, + swapFee: bigint +): number { + // Calculate actual swap price with decimal correction + const swapPrice = Number(swapOutputAmount) / (Number(swapInputAmount) - Number(swapFee)); + + // Calculate slippage: 1 - (actualPrice / marketPrice) + const slippage = 1 - (swapPrice / marketPrice); + + // Convert to percentage + return slippage * 100; +} + export interface SwapAmountResult { tokenAddress: `0x${string}`; tokenSymbol: string; @@ -172,13 +196,10 @@ export function useSwapAmounts( }) as bigint; // Convert Q64 format to decimal (price = priceValue / 2^64) - const price = Number(priceInt128) / 2 ** 64; + const marketPrice = Number(priceInt128) / 2 ** 64; - // Calculate actual swap price with decimal correction - const swapPrice = Number(swapOutputAmount) / ((Number(swapInputAmount)) - Number(inFee)); - // Calculate slippage: 1 - (actualPrice / marketPrice) - const slippage = 1 - (swapPrice / price); - calculatedSlippage = slippage * 100; // Convert to percentage + // Calculate slippage using the reusable function + calculatedSlippage = calculateSlippage(marketPrice, swapOutputAmount, swapInputAmount, inFee); console.log('calculatedSlippage', calculatedSlippage) } catch (slippageErr) { console.error(`Error calculating slippage for ${token.symbol}:`, slippageErr);