Skip to content

Commit

Permalink
feat: subtract pending fees from available balance in stx send form
Browse files Browse the repository at this point in the history
  • Loading branch information
alter-eggo committed Apr 12, 2023
1 parent 31acf9b commit a894886
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 5 deletions.
5 changes: 5 additions & 0 deletions src/app/common/money/format-money.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,8 @@ export function i18nFormatCurrency(quantity: Money, locale = 'en-US') {
export function formatDustUsdAmounts(value: string) {
return value.endsWith('0.00') ? '<' + thinSpace + value.replace('0.00', '0.01') : value;
}

export function subtractMoney(xAmount: Money, yAmount: Money) {
if (xAmount.symbol !== yAmount.symbol) throw new Error('Cannot subtract different currencies');
return xAmount.amount.minus(yAmount.amount);
}
11 changes: 7 additions & 4 deletions src/app/common/validation/forms/amount-validators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import * as yup from 'yup';
import { Money } from '@shared/models/money.model';
import { isNumber } from '@shared/utils';

import { subtractMoney } from '@app/common/money/format-money';
import {
btcToSat,
microStxToStx,
Expand Down Expand Up @@ -79,19 +80,21 @@ export function stxAmountValidator() {
.concat(stxAmountPrecisionValidator(formatPrecisionError()));
}

export function stxAvailableBalanceValidator(availableBalance: Money) {
export function stxAvailableBalanceValidator(availableBalance: Money, pendingTxsBalance: Money) {
return yup
.number()
.typeError(formatErrorWithSymbol('STX', FormErrorMessages.MustBeNumber))
.test({
message: formatInsufficientBalanceError(availableBalance, sum =>
microStxToStx(sum.amount).toString()
microStxToStx(subtractMoney(sum, pendingTxsBalance)).toString()
),
test(value: unknown) {
const fee = stxToMicroStx(this.parent.fee);
if (!availableBalance || !isNumber(value)) return false;
const availableBalanceLessFee = availableBalance.amount.minus(fee);
return availableBalanceLessFee.isGreaterThanOrEqualTo(stxToMicroStx(value));
const availableBalanceLessAll = subtractMoney(availableBalance, pendingTxsBalance).minus(
fee
);
return availableBalanceLessAll.isGreaterThanOrEqualTo(stxToMicroStx(value));
},
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,9 @@ export function useStxSendForm() {
stxFees,

validationSchema: yup.object({
amount: stxAmountValidator().concat(stxAvailableBalanceValidator(availableStxBalance)),
amount: stxAmountValidator().concat(
stxAvailableBalanceValidator(availableStxBalance, pendingTxsBalance)
),
fee: stxFeeValidator(availableStxBalance),
recipient,
memo,
Expand Down

0 comments on commit a894886

Please sign in to comment.