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<
25 BitcoinAddressHighestIndexState,
29 miss: async ({ extraArgument, options, getState }) => {
30 const stateValue = getState()[name].value;
31 if (!options?.thunkArg) {
32 return stateValue ?? {};
35 const [walletId, walletAccountId] = options?.thunkArg;
37 const index = await extraArgument.walletApi
39 .bitcoin_address.getBitcoinAddressHighestIndex(walletId, walletAccountId)
40 .then((data) => Number(data))
45 [walletAccountId]: { index, time: Date.now() },
49 previous: ({ getState, options }) => {
50 const state = getState()[name];
52 if (!options?.thunkArg || !state.value) {
56 const [, walletAccountId] = options?.thunkArg;
57 const highestIndexValue = state.value[walletAccountId];
59 if (!highestIndexValue) {
67 const initialState = getInitialModelState<Model>();
69 const slice = createSlice({
73 extraReducers: (builder) => {
74 handleAsyncModel(builder, modelThunk);
78 export const bitcoinAddressHighestIndexReducer = { [name]: slice.reducer };
79 export const bitcoinAddressHighestIndexThunk = modelThunk.thunk;