Merge branch 'feat/inda-383-daily-stat' into 'main'
[ProtonMail-WebClient.git] / packages / wallet / store / slices / bitcoinAddressHighestIndex.ts
blobc1f4e9c6566ace59cf82fc19dda446b7e7c62e2d
1 import { createSlice } from '@reduxjs/toolkit';
3 import type { ModelState } from '@proton/account';
4 import { getInitialModelState } from '@proton/account';
5 import { createAsyncModelThunk, handleAsyncModel } from '@proton/redux-utilities';
6 import { MINUTE } from '@proton/shared/lib/constants';
7 import { type SimpleMap } from '@proton/shared/lib/interfaces';
9 import type { WalletThunkArguments } from '../thunk';
11 const name = 'bitcoin_address_highest_index' as const;
13 type HighestIndexByWalletAccountId = SimpleMap<{ time: number; index: number }>;
14 export interface BitcoinAddressHighestIndexState {
15     [name]: ModelState<HighestIndexByWalletAccountId>;
18 type SliceState = BitcoinAddressHighestIndexState[typeof name];
19 type Model = NonNullable<SliceState['value']>;
21 export const selectBitcoinAddressHighestIndex = (state: BitcoinAddressHighestIndexState) => state[name];
23 const modelThunk = createAsyncModelThunk<
24     Model,
25     BitcoinAddressHighestIndexState,
26     WalletThunkArguments,
27     [string, string]
28 >(`${name}/fetch`, {
29     miss: async ({ extraArgument, options, getState }) => {
30         const stateValue = getState()[name].value;
31         if (!options?.thunkArg) {
32             return stateValue ?? {};
33         }
35         const [walletId, walletAccountId] = options?.thunkArg;
37         const index = await extraArgument.walletApi
38             .clients()
39             .bitcoin_address.getBitcoinAddressHighestIndex(walletId, walletAccountId)
40             .then((data) => Number(data))
41             .catch(() => 0);
43         return {
44             ...stateValue,
45             [walletAccountId]: { index, time: Date.now() },
46         };
47     },
48     expiry: 10 * MINUTE,
49     previous: ({ getState, options }) => {
50         const state = getState()[name];
52         if (!options?.thunkArg || !state.value) {
53             return undefined;
54         }
56         const [, walletAccountId] = options?.thunkArg;
57         const highestIndexValue = state.value[walletAccountId];
59         if (!highestIndexValue) {
60             return undefined;
61         }
63         return state;
64     },
65 });
67 const initialState = getInitialModelState<Model>();
69 const slice = createSlice({
70     name,
71     initialState,
72     reducers: {},
73     extraReducers: (builder) => {
74         handleAsyncModel(builder, modelThunk);
75     },
76 });
78 export const bitcoinAddressHighestIndexReducer = { [name]: slice.reducer };
79 export const bitcoinAddressHighestIndexThunk = modelThunk.thunk;