@qso-soft/shared
Version:
Shared library for QSO-soft
73 lines • 3.26 kB
JavaScript
import { AMOUNT_IS_TOO_LOW_ERROR } from '../../constants';
import { addNumberPercentage, getRandomNumber } from '../utils';
import { decimalToInt, intToDecimal } from './wei-converter';
const calculatePercentAmount = (balance, percent) => (balance * percent) / 100;
export function calculateAmount({ balance, minAndMaxAmount, usePercentBalance, isBigInt, decimals, }) {
let amount = getRandomNumber(minAndMaxAmount);
if (usePercentBalance) {
const percentValue = getRandomNumber(minAndMaxAmount, true);
if (percentValue === 100) {
return balance;
}
if (isBigInt) {
const intBalance = decimalToInt({ amount: balance, decimals });
amount = calculatePercentAmount(intBalance, percentValue);
}
else {
amount = calculatePercentAmount(balance, percentValue);
}
}
if (isBigInt) {
return intToDecimal({ amount, decimals });
}
return amount;
}
export const getExpectedBalance = (expectedBalance) => {
const currentExpectedBalance = !!expectedBalance && getRandomNumber(expectedBalance);
const isTopUpByExpectedBalance = !!currentExpectedBalance && currentExpectedBalance > 0;
if (!currentExpectedBalance) {
return {
currentExpectedBalance: 0,
isTopUpByExpectedBalance,
};
}
return {
currentExpectedBalance,
isTopUpByExpectedBalance,
};
};
export const getTopUpOptions = async ({ isTopUpByExpectedBalance, currentExpectedBalance, tokenToWithdraw, client, amount, minAndMaxAmount, network, percentToAdd, minNativeBalance = 0, fee = 0, }) => {
let currentAmount = 0;
const { int: nativeBalance } = await client.getNativeBalance();
if (isTopUpByExpectedBalance) {
if (currentExpectedBalance <= nativeBalance) {
const successMessage = `Native balance of ${tokenToWithdraw}=${nativeBalance} in ${network} already more than or equals ${currentExpectedBalance}`;
return {
isDone: true,
successMessage,
};
}
currentAmount = calculateAmountWithFee(currentExpectedBalance - nativeBalance, fee, percentToAdd);
}
else {
currentAmount = calculateAmountWithFee(amount || getRandomNumber(minAndMaxAmount), fee, percentToAdd);
if (currentAmount + nativeBalance < minNativeBalance) {
throw new Error(AMOUNT_IS_TOO_LOW_ERROR);
}
if (nativeBalance >= minNativeBalance && minNativeBalance !== 0) {
const successMessage = `Native balance of ${tokenToWithdraw}=${nativeBalance} in ${network} already more than or equals ${minNativeBalance}`;
return {
isDone: true,
successMessage,
};
}
}
const shouldTopUp = isTopUpByExpectedBalance
? nativeBalance < currentExpectedBalance
: nativeBalance < minNativeBalance || minNativeBalance === 0;
return { currentAmount, shouldTopUp, prevNativeBalance: nativeBalance };
};
export const calculateAmountWithFee = (amount, fee, percentToAdd = 0) => {
return +addNumberPercentage(amount + fee, percentToAdd).toFixed(5);
};
//# sourceMappingURL=calc-percent-or-amount.js.map