All files / app/store/stacking stacking.reducer.ts

0% Statements 0/111
0% Branches 0/31
0% Functions 0/26
0% Lines 0/98

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 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
import { RootState } from '..';
import {
  fetchStackingInfo,
  fetchCoreDetails,
  fetchBlockTimeInfo,
  fetchStackerInfo,
  activeStackingTx,
  removeStackingTx,
  fetchAccountBalanceLocked,
} from './stacking.actions';
import { NETWORK } from '@constants/index';
import { createSlice, PayloadAction, createSelector } from '@reduxjs/toolkit';
import { StackerInfo as StackerInfoFromClient } from '@stacks/stacking';
import {
  CoreNodePoxResponse,
  CoreNodeInfoResponse,
  NetworkBlockTimesResponse,
} from '@stacks/stacks-blockchain-api-types';
import { selectAddressBalance } from '@store/address';
import { selectIsStackingCallPending } from '@store/pending-transaction';
import { stxToMicroStx } from '@utils/unit-convert';
import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';
import relativeTime from 'dayjs/plugin/relativeTime';
 
dayjs.extend(duration);
dayjs.extend(relativeTime);
 
export enum StackingStatus {
  NotStacking = 'NotStacking',
  StackedPreCycle = 'StackedPreCycle',
  StackedActive = 'StackedActive',
  FinishedStacking = 'FinishedStacking',
}
 
export interface StackerInfoFail {
  error: string;
}
 
type StackerInfo = StackerInfoFromClient | StackerInfoFail;
 
export interface StackingState {
  initialRequestsComplete: Record<
    'poxInfo' | 'coreNodeInfo' | 'blockTimeInfo' | 'stackerInfo' | 'accountBalanceLocked',
    boolean
  >;
  errors: Record<
    'poxInfo' | 'coreNodeInfo' | 'blockTimeInfo' | 'stackerInfo' | 'accountBalanceLocked',
    boolean
  >;
  contractCallTx: string | null;
  poxInfo: CoreNodePoxResponse | null;
  coreNodeInfo: CoreNodeInfoResponse | null;
  blockTimeInfo: NetworkBlockTimesResponse | null;
  stackerInfo: {
    stacked: true;
    details: {
      first_reward_cycle: number;
      lock_period: number;
      unlock_height: number;
      pox_address: {
        version: Uint8Array;
        hashbytes: Uint8Array;
      };
    };
  } | null;
  accountBalanceLocked: bigint | null;
}
 
const initialState: StackingState = {
  initialRequestsComplete: {
    poxInfo: false,
    coreNodeInfo: false,
    blockTimeInfo: false,
    stackerInfo: false,
    accountBalanceLocked: false,
  },
  errors: {
    poxInfo: false,
    coreNodeInfo: false,
    blockTimeInfo: false,
    stackerInfo: false,
    accountBalanceLocked: false,
  },
  contractCallTx: null,
  poxInfo: null,
  coreNodeInfo: null,
  blockTimeInfo: null,
  stackerInfo: null,
  accountBalanceLocked: null,
};
 
export const stackingSlice = createSlice({
  name: 'stacking',
  initialState,
  reducers: {},
  extraReducers: {
    [fetchAccountBalanceLocked.fulfilled.toString()]: (state, action: PayloadAction<bigint>) => {
      state.initialRequestsComplete.accountBalanceLocked = true;
      state.errors.accountBalanceLocked = false;
      state.accountBalanceLocked = action.payload;
    },
    [fetchAccountBalanceLocked.rejected.toString()]: state => {
      Iif (!state.initialRequestsComplete.accountBalanceLocked) {
        state.errors.accountBalanceLocked = true;
      }
    },
    [fetchStackingInfo.fulfilled.toString()]: (
      state,
      action: PayloadAction<CoreNodePoxResponse>
    ) => {
      state.initialRequestsComplete.poxInfo = true;
      state.errors.poxInfo = false;
      state.poxInfo = action.payload;
    },
    [fetchStackingInfo.rejected.toString()]: state => {
      Iif (!state.initialRequestsComplete.poxInfo) {
        state.errors.poxInfo = true;
      }
    },
    [fetchCoreDetails.fulfilled.toString()]: (
      state,
      action: PayloadAction<CoreNodeInfoResponse>
    ) => {
      state.initialRequestsComplete.coreNodeInfo = true;
      state.errors.coreNodeInfo = false;
      state.coreNodeInfo = action.payload;
    },
    [fetchCoreDetails.rejected.toString()]: state => {
      Iif (!state.initialRequestsComplete.coreNodeInfo) {
        state.errors.coreNodeInfo = true;
      }
    },
    [fetchBlockTimeInfo.fulfilled.toString()]: (
      state,
      action: PayloadAction<NetworkBlockTimesResponse>
    ) => {
      state.errors.blockTimeInfo = false;
      state.initialRequestsComplete.blockTimeInfo = true;
      state.blockTimeInfo = action.payload;
    },
    [fetchBlockTimeInfo.rejected.toString()]: state => {
      Iif (!state.initialRequestsComplete.blockTimeInfo) {
        state.errors.blockTimeInfo = true;
      }
    },
    [fetchStackerInfo.fulfilled.toString()]: (
      state,
      action: PayloadAction<Required<StackerInfo>>
    ) => {
      state.initialRequestsComplete.stackerInfo = true;
      state.errors.stackerInfo = false;
      Iif ('error' in action.payload || !action.payload.stacked) {
        return;
      }
      state.stackerInfo = action.payload;
    },
    [fetchStackerInfo.rejected.toString()]: state => {
      state.initialRequestsComplete.stackerInfo = true;
      Iif (!state.initialRequestsComplete.stackerInfo) state.errors.stackerInfo = true;
    },
    [activeStackingTx.toString()]: (state, action: PayloadAction<{ txId: string }>) => {
      state.contractCallTx = action.payload.txId;
    },
    [removeStackingTx.toString()]: state => {
      state.contractCallTx = null;
    },
  },
});
 
export const stackingActions = stackingSlice.actions;
 
export const selectStackingState = (state: RootState) => state.stacking;
export const selectCoreNodeInfo = createSelector(selectStackingState, state => state.coreNodeInfo);
export const selectAccountBalanceLocked = createSelector(
  selectStackingState,
  state => state.accountBalanceLocked
);
export const selectBlockTimeInfo = createSelector(
  selectStackingState,
  state => state.blockTimeInfo
);
 
export const selectStackingError = createSelector(selectStackingState, state => state.errors);
 
export const selectLoadingStacking = createSelector(
  selectStackingState,
  state => !Object.values(state.initialRequestsComplete).every(value => value === true)
);
 
export const selectActiveStackingTxId = createSelector(
  selectStackingState,
  state => state.contractCallTx
);
 
export const selectPoxInfo = createSelector(selectStackingState, state => {
  Iif (state.poxInfo === null) return null;
  const paddingStackingMargin = stxToMicroStx(100).toNumber();
  const paddedMinimumStackingAmountMicroStx =
    Math.ceil(state.poxInfo.min_amount_ustx / paddingStackingMargin) * paddingStackingMargin;
  return { ...state.poxInfo, paddedMinimumStackingAmountMicroStx };
});
 
export const selectStackerInfo = createSelector(
  selectStackingState,
  selectAddressBalance,
  (state, addressBalances) => {
    Iif (
      state.poxInfo === null ||
      state.stackerInfo === null ||
      state.coreNodeInfo === null ||
      addressBalances === null
    ) {
      return null;
    }
 
    const hasStackingPeriodFinished =
      addressBalances.burnchain_unlock_height <= state.coreNodeInfo.burn_block_height;
 
    const currentCycleOfTotal =
      state.poxInfo.reward_cycle_id - state.stackerInfo.details.first_reward_cycle < 0
        ? 0
        : state.poxInfo.reward_cycle_id - state.stackerInfo.details.first_reward_cycle + 1;
 
    const isPreStackingPeriodStart =
      state.coreNodeInfo.burn_block_height <= addressBalances.lock_height;
 
    const isCurrentlyStacking =
      !isPreStackingPeriodStart && !hasStackingPeriodFinished && addressBalances.lock_height !== 0;
 
    const cycleLengthInBlocks =
      addressBalances.burnchain_unlock_height - addressBalances.burnchain_lock_height;
 
    const blocksUntilUnlocked =
      addressBalances.burnchain_unlock_height - state.coreNodeInfo.burn_block_height;
 
    const blocksUntilStackingCycleBegins =
      addressBalances.lock_height - state.coreNodeInfo.burn_block_height;
 
    const stackingPercentageLong =
      ((cycleLengthInBlocks - blocksUntilUnlocked) / cycleLengthInBlocks) * 100;
 
    const stackingPercentage = Number(stackingPercentageLong.toFixed(2));
 
    let status: StackingStatus = StackingStatus.NotStacking;
    Iif (isPreStackingPeriodStart) status = StackingStatus.StackedPreCycle;
    Iif (isCurrentlyStacking) status = StackingStatus.StackedActive;
    Iif (hasStackingPeriodFinished) status = StackingStatus.FinishedStacking;
 
    return {
      status,
      stackingPercentage,
      isCurrentlyStacking,
      hasStackingPeriodFinished,
      isPreStackingPeriodStart,
      currentCycleOfTotal,
      blocksUntilStackingCycleBegins,
      ...state.stackerInfo,
    };
  }
);
 
export const selectNextCycleInfo = createSelector(
  selectStackingState,
  selectIsStackingCallPending,
  ({ poxInfo, coreNodeInfo, blockTimeInfo }, isStackingCallPending) => {
    Iif (poxInfo === null || coreNodeInfo === null || blockTimeInfo === null) return null;
 
    const nextCycleStartBlock = (poxInfo.reward_cycle_id + 1) * poxInfo.reward_cycle_length + 1;
 
    const blocksToNextCycle =
      poxInfo.reward_cycle_length -
      ((coreNodeInfo.burn_block_height - poxInfo.first_burnchain_block_height - 1) %
        poxInfo.reward_cycle_length);
 
    const secondsToNextCycle = blocksToNextCycle * blockTimeInfo[NETWORK].target_block_time;
 
    const nextCycleStartingAt = new Date();
    nextCycleStartingAt.setSeconds(nextCycleStartingAt.getSeconds() + secondsToNextCycle);
 
    const now = dayjs();
    const timeOfNextCycle = now.add(secondsToNextCycle, 'second');
    const formattedTimeToNextCycle = dayjs().to(timeOfNextCycle, true);
 
    const estimateCycleDurationSeconds =
      poxInfo.reward_cycle_length * blockTimeInfo[NETWORK].target_block_time;
 
    const estimateCycleDuration = dayjs
      .duration(estimateCycleDurationSeconds, 'seconds')
      .humanize();
 
    return {
      nextCycleStartBlock,
      secondsToNextCycle,
      estimateCycleDurationSeconds,
      estimateCycleDuration,
      nextCycleStartingAt,
      formattedTimeToNextCycle,
      blocksToNextCycle,
      isStackingCallPending,
    };
  }
);
 
export const selectEstimatedStackingDuration = (cycles: number) =>
  createSelector(selectStackingState, ({ poxInfo, blockTimeInfo }) => {
    Iif (poxInfo === null || blockTimeInfo === null) return '—';
    return dayjs
      .duration(
        poxInfo.reward_cycle_length * blockTimeInfo[NETWORK].target_block_time * cycles,
        'seconds'
      )
      .humanize();
  });