abstracting out the slippage formula

This commit is contained in:
2025-11-26 12:47:03 -04:00
parent 882e271040
commit 85a7b58d55

View File

@@ -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);