All files / app/hooks use-balance.ts

0% Statements 0/29
0% Branches 0/8
0% Functions 0/5
0% Lines 0/27

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46                                                                                           
import { useMempool } from './use-mempool';
import { selectAvailableBalance, selectLockedBalance, selectTotalBalance } from '@store/address';
import { selectAddress } from '@store/keys';
import { sumTxsTotalSpentByAddress } from '@utils/tx-utils';
import { stxBalanceValidator } from '@utils/validators/stx-balance-validator';
import BigNumber from 'bignumber.js';
import { useCallback, useMemo } from 'react';
import { useSelector } from 'react-redux';
 
export function useBalance() {
  const { outboundMempoolTxs } = useMempool();
  const address = useSelector(selectAddress);
  const availableBalanceValue = useSelector(selectAvailableBalance);
  const totalBalanceValue = useSelector(selectTotalBalance);
  const lockedBalanceValue = useSelector(selectLockedBalance);
 
  const sumTotal = useMemo(
    () => sumTxsTotalSpentByAddress(outboundMempoolTxs, address || ''),
    [outboundMempoolTxs, address]
  );
 
  const totalBalance = useMemo(() => {
    const balance = new BigNumber(totalBalanceValue || 0).minus(sumTotal);
    Iif (balance.isLessThan(0)) return new BigNumber(0);
    return balance;
  }, [totalBalanceValue, sumTotal]);
 
  const availableBalance = useMemo(() => {
    const balance = new BigNumber(availableBalanceValue || 0).minus(sumTotal);
    Iif (balance.isLessThan(0)) return new BigNumber(0);
    return balance;
  }, [availableBalanceValue, sumTotal]);
 
  const availableBalanceValidator = useCallback(
    () => stxBalanceValidator(availableBalance),
    [availableBalance]
  );
 
  return {
    availableBalance,
    availableBalanceValidator,
    totalBalance,
    lockedBalance: lockedBalanceValue,
  };
}