forked from Koniverse/SubWallet-Extension
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.tsx
337 lines (305 loc) · 10.8 KB
/
index.tsx
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
// Copyright 2019-2022 @subwallet/extension-koni-ui authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { YieldPoolType, YieldPositionInfo } from '@subwallet/extension-base/types';
import { AlertModal, EmptyList, FilterModal, Layout } from '@subwallet/extension-koni-ui/components';
import { EarningPositionItem } from '@subwallet/extension-koni-ui/components/Earning';
import { ASTAR_PORTAL_URL, BN_TEN } from '@subwallet/extension-koni-ui/constants';
import { useAlert, useFilterModal, useSelector, useTranslation } from '@subwallet/extension-koni-ui/hooks';
import { reloadCron } from '@subwallet/extension-koni-ui/messaging';
import { EarningEntryView, EarningPositionDetailParam, ExtraYieldPositionInfo, ThemeProps } from '@subwallet/extension-koni-ui/types';
import { isRelatedToAstar, openInNewTab } from '@subwallet/extension-koni-ui/utils';
import { Button, ButtonProps, Icon, ModalContext, SwList } from '@subwallet/react-ui';
import BigN from 'bignumber.js';
import CN from 'classnames';
import { ArrowsClockwise, FadersHorizontal, Plus, PlusCircle, Vault } from 'phosphor-react';
import React, { SyntheticEvent, useCallback, useContext, useEffect, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import styled from 'styled-components';
type Props = ThemeProps & {
earningPositions: YieldPositionInfo[];
setEntryView: React.Dispatch<React.SetStateAction<EarningEntryView>>;
setLoading: React.Dispatch<React.SetStateAction<boolean>>;
}
let cacheData: Record<string, boolean> = {};
const FILTER_MODAL_ID = 'earning-positions-filter-modal';
const alertModalId = 'earning-positions-alert-modal';
function Component ({ className, earningPositions, setEntryView, setLoading }: Props) {
const { t } = useTranslation();
const navigate = useNavigate();
const { activeModal } = useContext(ModalContext);
const isShowBalance = useSelector((state) => state.settings.isShowBalance);
const { currencyData, priceMap } = useSelector((state) => state.price);
const { assetRegistry: assetInfoMap } = useSelector((state) => state.assetRegistry);
const chainInfoMap = useSelector((state) => state.chainStore.chainInfoMap);
const { currentAccount } = useSelector((state) => state.accountState);
const { filterSelectionMap, onApplyFilter, onChangeFilterOption, onCloseFilterModal, selectedFilters } = useFilterModal(FILTER_MODAL_ID);
const { alertProps, closeAlert, openAlert } = useAlert(alertModalId);
const items: ExtraYieldPositionInfo[] = useMemo(() => {
if (!earningPositions.length) {
return [];
}
return earningPositions
.map((item): ExtraYieldPositionInfo => {
const priceToken = assetInfoMap[item.balanceToken];
const price = priceMap[priceToken?.priceId || ''] || 0;
return {
...item,
asset: priceToken,
price,
currency: currencyData
};
})
.sort((firstItem, secondItem) => {
const getValue = (item: ExtraYieldPositionInfo): number => {
return new BigN(item.totalStake)
.dividedBy(BN_TEN.pow(item.asset.decimals || 0))
.multipliedBy(item.price)
.toNumber();
};
return getValue(secondItem) - getValue(firstItem);
});
}, [assetInfoMap, currencyData, earningPositions, priceMap]);
const lastItem = useMemo(() => {
return items[items.length - 1];
}, [items]);
const filterOptions = [
{ label: t('Nomination pool'), value: YieldPoolType.NOMINATION_POOL },
{ label: t('Direct nomination'), value: YieldPoolType.NATIVE_STAKING },
{ label: t('Liquid staking'), value: YieldPoolType.LIQUID_STAKING },
{ label: t('Lending'), value: YieldPoolType.LENDING },
{ label: t('Parachain staking'), value: YieldPoolType.PARACHAIN_STAKING },
{ label: t('Single farming'), value: YieldPoolType.SINGLE_FARMING }
];
const filterFunction = useMemo<(items: ExtraYieldPositionInfo) => boolean>(() => {
return (item) => {
if (!selectedFilters.length) {
return true;
}
for (const filter of selectedFilters) {
if (filter === '') {
return true;
}
if (filter === YieldPoolType.NOMINATION_POOL && item.type === YieldPoolType.NOMINATION_POOL) {
return true;
} else if (filter === YieldPoolType.NATIVE_STAKING && item.type === YieldPoolType.NATIVE_STAKING) {
return true;
} else if (filter === YieldPoolType.LIQUID_STAKING && item.type === YieldPoolType.LIQUID_STAKING) {
return true;
} else if (filter === YieldPoolType.LENDING && item.type === YieldPoolType.LENDING) {
return true;
}
// Uncomment the following code block if needed
// else if (filter === YieldPoolType.PARACHAIN_STAKING && item.type === YieldPoolType.PARACHAIN_STAKING) {
// return true;
// } else if (filter === YieldPoolType.SINGLE_FARMING && item.type === YieldPoolType.SINGLE_FARMING) {
// return true;
// }
}
return false;
};
}, [selectedFilters]);
const onClickItem = useCallback((item: ExtraYieldPositionInfo) => {
return () => {
if (isRelatedToAstar(item.slug)) {
openAlert({
title: t('Enter Astar portal'),
content: t('Navigate to Astar portal to view and manage your stake in Astar dApp staking v3'),
cancelButton: {
text: t('Cancel'),
schema: 'secondary',
onClick: closeAlert
},
okButton: {
text: t('Enter Astar portal'),
onClick: () => {
openInNewTab(ASTAR_PORTAL_URL)();
closeAlert();
}
}
});
} else {
navigate('/home/earning/position-detail', { state: {
earningSlug: item.slug
} as EarningPositionDetailParam });
}
};
}, [closeAlert, navigate, openAlert, t]);
const onClickExploreEarning = useCallback(() => {
setEntryView(EarningEntryView.OPTIONS);
}, [setEntryView]);
const renderItem = useCallback(
(item: ExtraYieldPositionInfo) => {
return (
<>
<EarningPositionItem
className={'earning-position-item'}
isShowBalance={isShowBalance}
key={item.slug}
onClick={onClickItem(item)}
positionInfo={item}
/>
{item.slug === lastItem.slug && <div className={'__footer-button'}>
<Button
icon={(
<Icon
phosphorIcon={Plus}
size='sm'
/>
)}
onClick={onClickExploreEarning}
size={'xs'}
type={'ghost'}
>
{t('Explore earning options')}
</Button>
</div>}
</>
);
},
[lastItem.slug, isShowBalance, onClickItem, onClickExploreEarning, t]
);
const emptyList = useCallback(() => {
return (
<EmptyList
buttonProps={{
icon: (
<Icon
phosphorIcon={PlusCircle}
weight={'fill'}
/>),
onClick: () => {
setEntryView(EarningEntryView.OPTIONS);
},
size: 'xs',
shape: 'circle',
children: t('Explore earning options')
}}
emptyMessage={t('Change your search or explore other earning options')}
emptyTitle={t('No earning position found')}
phosphorIcon={Vault}
/>
);
}, [setEntryView, t]);
const searchFunction = useCallback(({ balanceToken, chain: _chain }: ExtraYieldPositionInfo, searchText: string) => {
const chainInfo = chainInfoMap[_chain];
const assetInfo = assetInfoMap[balanceToken];
return (
chainInfo?.name.replace(' Relay Chain', '').toLowerCase().includes(searchText.toLowerCase()) ||
assetInfo?.symbol.toLowerCase().includes(searchText.toLowerCase())
);
}, [assetInfoMap, chainInfoMap]);
const subHeaderButtons: ButtonProps[] = useMemo(() => {
return [
{
icon: (
<Icon
phosphorIcon={ArrowsClockwise}
size='sm'
type='phosphor'
/>
),
onClick: () => {
setLoading(true);
reloadCron({ data: 'staking' })
.catch(console.error).finally(() => {
setTimeout(() => {
setLoading(false);
}, 1000);
});
}
},
{
icon: (
<Icon
phosphorIcon={Plus}
size='sm'
type='phosphor'
/>
),
onClick: () => {
setEntryView(EarningEntryView.OPTIONS);
}
}
];
}, [setEntryView, setLoading]);
useEffect(() => {
const address = currentAccount?.address || '';
if (cacheData[address] === undefined) {
cacheData = { [address]: !items.length };
}
}, [items.length, currentAccount]);
const onClickFilterButton = useCallback(
(e?: SyntheticEvent) => {
e && e.stopPropagation();
activeModal(FILTER_MODAL_ID);
},
[activeModal]
);
return (
<>
<Layout.Base
className={CN(className)}
showSubHeader={true}
subHeaderBackground={'transparent'}
subHeaderCenter={false}
subHeaderIcons={subHeaderButtons}
subHeaderPaddingVertical={true}
title={t<string>('Your earning positions')}
>
<SwList.Section
actionBtnIcon={<Icon phosphorIcon={FadersHorizontal} />}
className={'__section-list-container'}
enableSearchInput
filterBy={filterFunction}
list={items}
onClickActionBtn={onClickFilterButton}
renderItem={renderItem}
renderWhenEmpty={emptyList}
searchFunction={searchFunction}
searchMinCharactersCount={2}
searchPlaceholder={t<string>('Search token')}
showActionBtn
/>
<FilterModal
applyFilterButtonTitle={t('Apply filter')}
id={FILTER_MODAL_ID}
onApplyFilter={onApplyFilter}
onCancel={onCloseFilterModal}
onChangeOption={onChangeFilterOption}
optionSelectionMap={filterSelectionMap}
options={filterOptions}
title={t('Filter')}
/>
</Layout.Base>
{
!!alertProps && (
<AlertModal
modalId={alertModalId}
{...alertProps}
/>
)
}
</>
);
}
const EarningPositions = styled(Component)<Props>(({ theme: { token } }: Props) => ({
'.ant-sw-sub-header-container': {
marginBottom: token.marginXS
},
'.__section-list-container': {
height: '100%',
flex: 1
},
'.__footer-button': {
display: 'flex',
justifyContent: 'center',
marginBottom: token.size,
marginTop: token.marginXS
},
'.earning-position-item': {
'+ .earning-position-item': {
marginTop: token.marginXS
}
}
}));
export default EarningPositions;