UNPKG

@shogun-sdk/money-legos

Version:

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

73 lines (64 loc) 1.91 kB
import { formatUnits } from 'viem'; import type { ICollectedFees } from '../services/FeeService.js'; import type { QuoteTypes } from '../types/index.js'; import { compareAddresses } from './address.js'; import { NATIVE_TOKEN, SOL_NATIVE } from '../config/addresses.js'; import { MIN_NATIVE_TOKEN_BALANCE } from './rpc.js'; interface IMaxCalculateParams { balance: bigint | undefined; tokenAddress: string; chainId: number; decimals: number; fees?: ICollectedFees | undefined | null; quote?: QuoteTypes; } export const getMaxAmount = ({ balance, tokenAddress, chainId, decimals, fees, quote, }: IMaxCalculateParams): { maxAmount: string | null; needRecalculateMaxValue: boolean } => { if (!balance || !decimals || Number.isNaN(Number(balance))) { return { maxAmount: null, needRecalculateMaxValue: false, }; } const isNative = compareAddresses(tokenAddress, NATIVE_TOKEN.ETH) || compareAddresses(tokenAddress, SOL_NATIVE); if (isNative) { let txCost = BigInt(0); if (quote) { txCost = fees?.estimatedFees || BigInt(0); if (txCost > balance) { return { maxAmount: formatUnits(balance, decimals), needRecalculateMaxValue: true, }; } else { return { maxAmount: formatUnits(balance - txCost, decimals), needRecalculateMaxValue: false, }; } } else { txCost = (isNative ? MIN_NATIVE_TOKEN_BALANCE[chainId] : BigInt(0)) ?? BigInt(0); if (balance < (txCost ?? 0)) { return { maxAmount: formatUnits(balance, decimals), needRecalculateMaxValue: true, }; } } return { maxAmount: formatUnits(balance - txCost, decimals), needRecalculateMaxValue: true, }; } else { return { maxAmount: formatUnits(balance, decimals), needRecalculateMaxValue: false, }; } };