@shogun-sdk/money-legos
Version:
Shogun Money Legos: clients and types for quotes, memes, prices, balances, fees, validations, etc.
67 lines (52 loc) • 1.85 kB
text/typescript
import { formatUnits } from 'viem';
import { QuoteTypes } from '../types/index.js';
export class HighSlippageValidationService {
constructor() {}
getInputUsdValue = (
weiAmount: bigint | undefined,
inputDecimals: number,
inputUsdPrice: number,
): number | undefined => {
if (weiAmount !== undefined) {
// turn the weiAmount into a normalized number
const amountNormalized = Number(formatUnits(BigInt(weiAmount), inputDecimals));
const inputValueUsd = amountNormalized * inputUsdPrice;
return inputValueUsd;
}
return undefined;
};
getExpectedSlippage = (
quotes: QuoteTypes,
inputValueUsd: number,
outputTokenData: {
decimals: number;
usdPrice: number;
},
): {
outputValueUsd: number;
expectedSlippage: number;
} => {
const outputAmount = quotes?.outputAmount;
// NEED TO CALCULATE OUTPUT VALUE USD
if (outputAmount?.value && BigInt(outputAmount?.value) > BigInt(0) && inputValueUsd > 0) {
const { decimals: outputTokenDecimals, usdPrice: outputTokenUsdPrice } = outputTokenData;
const outputAmountFormatted = formatUnits(BigInt(outputAmount?.value), outputTokenDecimals);
// TODO: this needs to be calculated using the output token usd price
const outputValueUsd = Number(outputAmountFormatted) * outputTokenUsdPrice;
const realSlippage = ((inputValueUsd - outputValueUsd) / inputValueUsd) * 100;
const expectedSlippage = Number(realSlippage.toFixed(2));
return {
outputValueUsd,
expectedSlippage,
};
}
return {
outputValueUsd: 0,
expectedSlippage: 0,
};
};
public isSlippageValid = (expectedSlippage: number): boolean => {
return expectedSlippage <= this.MAX_ALLOWED_OUTPUT_SLIPPAGE;
};
MAX_ALLOWED_OUTPUT_SLIPPAGE = 25;
}