All files / app/pages/stacking/direct-stacking direct-stacking.tsx

0% Statements 0/68
0% Branches 0/23
0% Functions 0/12
0% Lines 0/61

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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180                                                                                                                                                                                                                                                                                                                                                                       
import { StackingFormContainer } from '../components/stacking-form-container';
import { StackingFormInfoPanel } from '../components/stacking-form-info-panel';
import { StackingGuideCard } from '../components/stacking-guide-card';
import { StackingLayout } from '../components/stacking-layout';
import { ChooseBtcAddressField } from './components/choose-btc-address';
import { ChooseCycleField } from './components/choose-cycles';
import { ChooseDirectStackingAmountField } from './components/choose-direct-stacking-amount';
import { ConfirmAndStackStep } from './components/confirm-and-stack';
import { DirectStackingInfoCard } from './components/direct-stacking-info-card';
import { DirectStackingIntro } from './components/direct-stacking-intro';
import { STACKING_CONTRACT_CALL_TX_BYTES } from '@constants/index';
import routes from '@constants/routes.json';
import { useBackButton } from '@hooks/use-back-url';
import { useBalance } from '@hooks/use-balance';
import { useCalculateFee } from '@hooks/use-calculate-fee';
import { StackingModal } from '@modals/stacking/stacking-modal';
import { RootState } from '@store/index';
import { selectWalletType } from '@store/keys';
import {
  selectEstimatedStackingDuration,
  selectNextCycleInfo,
  selectPoxInfo,
} from '@store/stacking';
import { selectActiveNodeApi } from '@store/stacks-node';
import { validateDecimalPrecision } from '@utils/form/validate-decimals';
import { stxToMicroStx, toHumanReadableStx } from '@utils/unit-convert';
import { btcAddressSchema } from '@utils/validators/btc-address-validator';
import { stxAmountSchema } from '@utils/validators/stx-amount-validator';
import { BigNumber } from 'bignumber.js';
import { Form, Formik } from 'formik';
import React, { FC, useState } from 'react';
import { useSelector } from 'react-redux';
import * as yup from 'yup';
 
enum StackingStep {
  ChooseAmount = 'Choose an amount',
  ChooseCycles = 'Choose your duration',
  ChooseBtcAddress = 'Add your Bitcoin address',
}
 
const cyclesWithDefault = (numCycles: null | undefined | number) => numCycles ?? 1;
 
interface DirectStackingForm {
  amount: string;
  btcAddress: string;
  cycles: number;
}
 
const initialDirectStackingFormValues: DirectStackingForm = {
  amount: '',
  btcAddress: '',
  cycles: 1,
};
 
export const DirectStacking: FC = () => {
  useBackButton(routes.CHOOSE_STACKING_METHOD);
  const { availableBalance, availableBalanceValidator } = useBalance();
  const [modalOpen, setModalOpen] = useState(false);
  const [formValues, setFormValues] = useState<null | DirectStackingForm>(null);
 
  const { stackingCycleDuration, nextCycleInfo, poxInfo } = useSelector((state: RootState) => ({
    walletType: selectWalletType(state),
    activeNode: selectActiveNodeApi(state),
    stackingCycleDuration: selectEstimatedStackingDuration(cyclesWithDefault(formValues?.cycles))(
      state
    ),
    nextCycleInfo: selectNextCycleInfo(state),
    poxInfo: selectPoxInfo(state),
  }));
 
  const calcFee = useCalculateFee();
  const directStackingTxFee = calcFee(STACKING_CONTRACT_CALL_TX_BYTES);
 
  Iif (nextCycleInfo === null || poxInfo === null) return null;
 
  const validationSchema = yup.object().shape({
    amount: stxAmountSchema()
      .test(availableBalanceValidator())
      .test('test-precision', 'You cannot stack with a precision of less than 1 STX', value => {
        // If `undefined`, throws `required` error
        Iif (value === undefined) return true;
        return validateDecimalPrecision(0)(value);
      })
      .test({
        name: 'test-fee-margin',
        message: 'You must stack less than your entire balance to allow for the transaction fee',
        test: value => {
          Iif (value === null || value === undefined) return false;
          const uStxInput = stxToMicroStx(value);
          return !uStxInput.isGreaterThan(availableBalance.minus(directStackingTxFee));
        },
      })
      .test({
        name: 'test-min-utx',
        message: `You must stack with at least ${toHumanReadableStx(
          poxInfo.paddedMinimumStackingAmountMicroStx
        )} `,
        test: value => {
          Iif (value === null || value === undefined) return false;
          const uStxInput = stxToMicroStx(value);
          return new BigNumber(poxInfo.paddedMinimumStackingAmountMicroStx).isLessThanOrEqualTo(
            uStxInput
          );
        },
      }),
    cycles: yup.number().defined(),
    btcAddress: btcAddressSchema(),
  });
 
  const openStackingTxSigningModal = (formValues: DirectStackingForm) => {
    setFormValues({ ...formValues, amount: stxToMicroStx(formValues.amount).toString() });
    setModalOpen(true);
  };
 
  const stackingIntro = (
    <DirectStackingIntro
      timeUntilNextCycle={nextCycleInfo.formattedTimeToNextCycle}
      estimatedStackingMinimum={String(poxInfo.min_amount_ustx)}
    />
  );
 
  return (
    <>
      {modalOpen && formValues && (
        <StackingModal
          onClose={() => setModalOpen(false)}
          amountToStack={new BigNumber(formValues.amount)}
          numCycles={cyclesWithDefault(formValues.cycles)}
          poxAddress={formValues.btcAddress}
          fee={directStackingTxFee}
        />
      )}
      <Formik
        initialValues={initialDirectStackingFormValues}
        onSubmit={values => openStackingTxSigningModal(values)}
        validationSchema={validationSchema}
      >
        {({ values }) => {
          return (
            <StackingLayout
              intro={stackingIntro}
              stackingInfoPanel={
                <StackingFormInfoPanel>
                  <DirectStackingInfoCard
                    cycles={cyclesWithDefault(values.cycles)}
                    amount={values.amount}
                    btcAddress={values.btcAddress}
                    startDate={nextCycleInfo.nextCycleStartingAt}
                    blocksPerCycle={poxInfo.reward_cycle_length}
                    duration={stackingCycleDuration}
                    fee={directStackingTxFee}
                  />
                  <StackingGuideCard mt="loose" />
                </StackingFormInfoPanel>
              }
              stackingForm={
                <Form>
                  <StackingFormContainer>
                    <ChooseDirectStackingAmountField
                      title={StackingStep.ChooseAmount}
                      minimumAmountToStack={poxInfo.paddedMinimumStackingAmountMicroStx}
                    />
                    <ChooseCycleField cycles={cyclesWithDefault(values.cycles)} />
                    <ChooseBtcAddressField />
                    <ConfirmAndStackStep
                      estimatedDuration={stackingCycleDuration}
                      timeUntilNextCycle={nextCycleInfo.formattedTimeToNextCycle}
                      onConfirmAndLock={() => setModalOpen(true)}
                    />
                  </StackingFormContainer>
                </Form>
              }
            />
          );
        }}
      </Formik>
    </>
  );
};