UNPKG

@shogun-sdk/money-legos

Version:

Shogun Money Legos: clients and types for quotes, memes, prices, balances, fees, validations, etc.

30 lines 1.5 kB
export const SLIPPAGE_ERROR_OUTPUT_MSG = 'Could not calculate optimal slippage'; export const getSuggestedSlippage = (quote, errorData) => { // Extract the actual amount from the error data (0x + 64 characters after the error code) const index = errorData .slice(10) // Skip error code (0xff5f293c) .split('') .findIndex((char) => char !== '0'); // Find first non-zero character const actualAmountHex = errorData.slice(10 + (index === -1 ? 0 : index)); // Return everything after zeros if (!actualAmountHex) { throw Error(SLIPPAGE_ERROR_OUTPUT_MSG); } try { const actualAmount = BigInt(`0x${actualAmountHex}`); const expectedAmount = BigInt(quote.routes[0]?.amountOut?.value ?? '0'); if (actualAmount >= expectedAmount) { throw new Error(SLIPPAGE_ERROR_OUTPUT_MSG); } // Calculate the perfect slippage percentage with 2 decimal precision const perfectSlippage = Number((BigInt('10000') * (expectedAmount - actualAmount)) / expectedAmount) / 100; // Add 0.5% safety margin and round to 2 decimals const suggestedSlippage = Math.ceil((perfectSlippage + 0.5) * 100) / 100; // Return minimum 0.5% slippage return Math.min(Math.max(suggestedSlippage, 0.5), 100); } catch (error) { console.error('Error parsing slippage error data:', error); throw new Error(SLIPPAGE_ERROR_OUTPUT_MSG); } }; //# sourceMappingURL=slippage.js.map