abstracting out the slippage formula
This commit is contained in:
@@ -11,6 +11,30 @@ import type { AvailableToken } from './usePartyPlanner';
|
|||||||
// Q96 constant for price calculations
|
// Q96 constant for price calculations
|
||||||
const Q96 = 1n << 96n;
|
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 {
|
export interface SwapAmountResult {
|
||||||
tokenAddress: `0x${string}`;
|
tokenAddress: `0x${string}`;
|
||||||
tokenSymbol: string;
|
tokenSymbol: string;
|
||||||
@@ -172,13 +196,10 @@ export function useSwapAmounts(
|
|||||||
}) as bigint;
|
}) as bigint;
|
||||||
|
|
||||||
// Convert Q64 format to decimal (price = priceValue / 2^64)
|
// 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
|
// Calculate slippage using the reusable function
|
||||||
const swapPrice = Number(swapOutputAmount) / ((Number(swapInputAmount)) - Number(inFee));
|
calculatedSlippage = calculateSlippage(marketPrice, swapOutputAmount, swapInputAmount, inFee);
|
||||||
// Calculate slippage: 1 - (actualPrice / marketPrice)
|
|
||||||
const slippage = 1 - (swapPrice / price);
|
|
||||||
calculatedSlippage = slippage * 100; // Convert to percentage
|
|
||||||
console.log('calculatedSlippage', calculatedSlippage)
|
console.log('calculatedSlippage', calculatedSlippage)
|
||||||
} catch (slippageErr) {
|
} catch (slippageErr) {
|
||||||
console.error(`Error calculating slippage for ${token.symbol}:`, slippageErr);
|
console.error(`Error calculating slippage for ${token.symbol}:`, slippageErr);
|
||||||
|
|||||||
Reference in New Issue
Block a user