All files / app/pages/stacking/delegated-stacking pooled-stacking.tsx

0% Statements 0/58
0% Branches 0/21
0% Functions 0/10
0% Lines 0/50

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 181                                                                                                                                                                                                                                                                                                                                                                         
/* eslint-disable @typescript-eslint/no-unsafe-argument */
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 { ChoosePoolStxAddressField } from './components/choose-pool-stx-address';
import { ChoosePoolingAmountField } from './components/choose-pooling-amount';
import { ChoosePoolingDurationField } from './components/choose-pooling-duration';
import { ConfirmAndPoolAction } from './components/confirm-and-pool';
import { PoolingInfoCard } from './components/delegated-stacking-info-card';
import { PooledStackingIntro } from './components/pooled-stacking-intro';
import {
  UI_IMPOSED_MAX_STACKING_AMOUNT_USTX,
  MIN_DELEGATED_STACKING_AMOUNT_USTX,
} from '@constants/index';
import routes from '@constants/routes.json';
import { useBackButton } from '@hooks/use-back-url';
import { DelegatedStackingModal } from '@modals/delegated-stacking/delegated-stacking-modal';
import { RootState } from '@store/index';
import { selectAddress } from '@store/keys';
import { selectNextCycleInfo, selectPoxInfo } from '@store/stacking';
import { calculateUntilBurnHeightBlockFromCycles } from '@utils/calculate-burn-height';
import { stxToMicroStx, toHumanReadableStx } from '@utils/unit-convert';
import { stxPrincipalSchema } from '@utils/validators/stx-address-validator';
import { stxAmountSchema } from '@utils/validators/stx-amount-validator';
import { BigNumber } from 'bignumber.js';
import { Form, Formik } from 'formik';
import React, { FC, useState, useCallback } from 'react';
import { useSelector } from 'react-redux';
import * as yup from 'yup';
 
type Nullable<T> = { [K in keyof T]: T[K] | null };
 
interface PoolingFormIndefiniteValues<N> {
  delegationType: 'indefinite';
  amount: N;
  stxAddress: string;
}
interface PoolingFormLimitedValues<N> {
  delegationType: 'limited';
  amount: N;
  stxAddress: string;
  cycles: number;
}
type AbstractPoolingFormValues<N> = PoolingFormIndefiniteValues<N> | PoolingFormLimitedValues<N>;
 
type EditingFormValues = AbstractPoolingFormValues<string | number>;
type CompletedFormValues = AbstractPoolingFormValues<BigNumber>;
 
const initialPoolingFormValues: Nullable<EditingFormValues> = {
  amount: '',
  stxAddress: '',
  delegationType: null,
  cycles: 1,
};
 
export const StackingDelegation: FC = () => {
  useBackButton(routes.CHOOSE_STACKING_METHOD);
 
  const [modalOpen, setModalOpen] = useState(false);
  const [formValues, setFormValues] = useState<null | CompletedFormValues>(null);
 
  const { poxInfo, address, nextCycleInfo } = useSelector((state: RootState) => ({
    poxInfo: selectPoxInfo(state),
    address: selectAddress(state),
    nextCycleInfo: selectNextCycleInfo(state),
  }));
 
  const cyclesToUntilBurnBlockHeight = useCallback(
    (cycles: number | null) => {
      Iif (!poxInfo) throw new Error('`poxInfo` not defined');
      Iif (!cycles) return;
      return calculateUntilBurnHeightBlockFromCycles({
        cycles,
        rewardCycleLength: poxInfo.reward_cycle_length,
        currentCycleId: poxInfo.reward_cycle_id,
        genesisBurnBlockHeight: poxInfo.first_burnchain_block_height,
      });
    },
    [poxInfo]
  );
 
  const validationSchema = yup.object().shape({
    stxAddress: stxPrincipalSchema().test({
      name: 'cannot-pool-to-yourself',
      message: 'Cannot pool to your own STX address',
      test(value: any) {
        Iif (value === null || value === undefined) return false;
        return value !== address;
      },
    }),
    amount: stxAmountSchema()
      .test({
        name: 'test-min-allowed-delegated-stacking',
        message: `You must delegate at least ${toHumanReadableStx(
          MIN_DELEGATED_STACKING_AMOUNT_USTX
        )}`,
        test(value: any) {
          Iif (value === null || value === undefined) return false;
          const enteredAmount = stxToMicroStx(value);
          return enteredAmount.isGreaterThanOrEqualTo(MIN_DELEGATED_STACKING_AMOUNT_USTX);
        },
      })
      .test({
        name: 'test-max-allowed-delegated-stacking',
        message: `You cannot delegate more than ${toHumanReadableStx(
          UI_IMPOSED_MAX_STACKING_AMOUNT_USTX
        )}`,
        test(value: any) {
          Iif (value === null || value === undefined) return false;
          const enteredAmount = stxToMicroStx(value);
          return enteredAmount.isLessThanOrEqualTo(UI_IMPOSED_MAX_STACKING_AMOUNT_USTX);
        },
      }),
    delegationType: yup.string().typeError(`Make sure to choose a duration you'd like to pool for`),
  });
 
  function handleSubmit(values: EditingFormValues) {
    setFormValues({ ...values, amount: stxToMicroStx(values.amount) });
    setModalOpen(true);
  }
 
  Iif (nextCycleInfo === null) return null;
 
  return (
    <>
      {modalOpen && formValues && (
        <DelegatedStackingModal
          delegateeStxAddress={formValues.stxAddress}
          amountToStack={formValues.amount}
          burnHeight={
            formValues.delegationType === 'limited'
              ? cyclesToUntilBurnBlockHeight(formValues.cycles)
              : undefined
          }
          onClose={() => setModalOpen(false)}
        />
      )}
      <Formik
        initialValues={initialPoolingFormValues as EditingFormValues}
        onSubmit={handleSubmit}
        validationSchema={validationSchema}
      >
        {({ submitForm, values }) => (
          <StackingLayout
            intro={
              <PooledStackingIntro timeUntilNextCycle={nextCycleInfo.formattedTimeToNextCycle} />
            }
            stackingInfoPanel={
              <StackingFormInfoPanel>
                <PoolingInfoCard
                  poolStxAddress={values.stxAddress}
                  amount={values.amount}
                  durationInCycles={values.delegationType === 'limited' ? values.cycles : null}
                  delegationType={values.delegationType}
                  burnHeight={
                    values.delegationType === 'limited'
                      ? cyclesToUntilBurnBlockHeight(values.cycles)
                      : undefined
                  }
                />
                <StackingGuideCard mt="loose" />
              </StackingFormInfoPanel>
            }
            stackingForm={
              <Form>
                <StackingFormContainer>
                  <ChoosePoolStxAddressField />
                  <ChoosePoolingAmountField />
                  <ChoosePoolingDurationField />
                  <ConfirmAndPoolAction onConfirmAndPool={() => submitForm()} />
                </StackingFormContainer>
              </Form>
            }
          />
        )}
      </Formik>
    </>
  );
};