-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathuseMoneyAccountBalance.ts
More file actions
275 lines (243 loc) · 9.66 KB
/
Copy pathuseMoneyAccountBalance.ts
File metadata and controls
275 lines (243 loc) · 9.66 KB
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
import { useDispatch, useSelector } from 'react-redux';
import { useEffect, useMemo, useCallback, useRef } from 'react';
import {
type MoneyAccountBalanceResponse,
type NormalizedVaultApyResponse,
} from '@metamask/money-account-balance-service';
import { useQuery } from '@metamask/react-data-query';
import type { UseQueryResult } from '@tanstack/react-query';
import BigNumber from 'bignumber.js';
import { moneyFormatUsd } from '../utils/moneyFormatFiat';
import { selectCurrentCurrency } from '../../../../selectors/currencyRateController';
import { MUSD_DECIMALS } from '../../Earn/constants/musd';
import { MoneyAccountBalanceServiceQueryKeys } from '../queryKeys';
import Engine from '../../../../core/Engine';
import ReactQueryService from '../../../../core/ReactQueryService';
import useMoneyAccountInfo from './useMoneyAccountInfo';
import {
isPersistedMoneyBalanceUsable,
selectLastKnownMoneyBalance,
setLastKnownMoneyBalance,
} from '../../../../core/redux/slices/moneyBalance';
import { selectMoneyVaultApyRemoteConfig } from '../selectors/featureFlags';
const DEFAULT_REFETCH_INTERVAL = 30 * 1000; // 30 seconds
const FIVE_MINUTES_MS = 5 * 60 * 1000;
/**
* Fetches the live exchange rate for the mUSD token.
* This is necessary when we need the most current rate at runtime (e.g. Money account withdrawal).
* @returns The live exchange rate for the mUSD token.
*/
export const getLiveVedaVaultExchangeRate = async () =>
Engine.controllerMessenger
.call('MoneyAccountBalanceService:getExchangeRate', { staleTime: 0 })
.then(({ rate }) => rate);
interface UseMoneyAccountBalanceResult {
moneyBalanceQuery: UseQueryResult<MoneyAccountBalanceResponse>;
vaultApyQuery: UseQueryResult<NormalizedVaultApyResponse>;
isBalanceLoading: boolean;
isBalanceFetchError: boolean;
isBalanceFetching: boolean;
isBalanceUnavailable: boolean;
lastKnownTotalFiatFormatted: string | undefined;
refetchBalance: () => void;
tokenTotal: BigNumber | undefined;
totalFiatFormatted: string | undefined;
totalFiatRaw: string | undefined;
withdrawableFiatFormatted: string | undefined;
withdrawableFiatRaw: string | undefined;
withdrawableMusd: BigNumber | undefined;
apyDecimal: number | undefined;
apyPercent: number | undefined;
apyPercentFormatted: string | undefined;
/**
* True while the APY query is loading and no APY of any kind is available
* (no live value, no carried last-known value, no override, no fallback).
* Prefer this over `vaultApyQuery.isLoading` for skeletons: the raw flag
* flips back to true whenever the bridge bug (see the last-known carry
* below) rebuilds the query, which would flicker UI that already has an
* APY to show.
*/
isApyLoading: boolean;
}
const useMoneyAccountBalance = (
refetchInterval: number = DEFAULT_REFETCH_INTERVAL,
): UseMoneyAccountBalanceResult => {
const dispatch = useDispatch();
const { primaryMoneyAccount } = useMoneyAccountInfo();
const moneyAccountAddress = primaryMoneyAccount?.address;
const currentCurrency = useSelector(selectCurrentCurrency);
const lastKnownBalance = useSelector(selectLastKnownMoneyBalance);
const { vaultApyFallback, vaultApyOverride } = useSelector(
selectMoneyVaultApyRemoteConfig,
);
const moneyBalanceQuery = useQuery({
queryKey: [
MoneyAccountBalanceServiceQueryKeys.GET_MONEY_ACCOUNT_BALANCE,
moneyAccountAddress as string,
],
enabled: Boolean(moneyAccountAddress),
refetchInterval,
}) as UseQueryResult<MoneyAccountBalanceResponse>;
const vaultApyQuery = useQuery({
queryKey: [MoneyAccountBalanceServiceQueryKeys.GET_VAULT_APY],
refetchInterval: FIVE_MINUTES_MS,
}) as UseQueryResult<NormalizedVaultApyResponse>;
/**
* True while the balance query is loading with no cached data (even if stale).
*/
const isBalanceLoading = moneyBalanceQuery.isLoading;
/** Any balance fetch failure → full error state. */
const isBalanceFetchError = moneyBalanceQuery.isError;
/**
* True while a refetch is in flight. Combined with isError, lets callers
* distinguish retry-in-flight (show skeleton) from silent auto-refetch.
*/
const isBalanceFetching = moneyBalanceQuery.isFetching;
const refetchBalance = useCallback(
() =>
ReactQueryService.queryClient.invalidateQueries({
queryKey: [
MoneyAccountBalanceServiceQueryKeys.GET_MONEY_ACCOUNT_BALANCE,
moneyAccountAddress,
],
refetchType: 'all',
}),
[moneyAccountAddress],
);
const { tokenTotal, totalFiat, withdrawableFiat, withdrawableMusd } =
useMemo(() => {
// Total balance (mUSD + vmUSD) from the service's Multicall3 response.
const totalDecimal = moneyBalanceQuery.data?.totalBalance
? new BigNumber(moneyBalanceQuery.data.totalBalance).shiftedBy(
-MUSD_DECIMALS,
)
: new BigNumber(0);
// the withdrawable amount.
const vmusdDecimal = moneyBalanceQuery.data?.vmusdValueInMusd
? new BigNumber(moneyBalanceQuery.data.vmusdValueInMusd).shiftedBy(
-MUSD_DECIMALS,
)
: new BigNumber(0);
// Undefined while loading or on error so callers can distinguish from a genuine zero.
const computedWithdrawableMusd =
isBalanceLoading || isBalanceFetchError ? undefined : vmusdDecimal;
const computedTokenTotal =
isBalanceLoading || isBalanceFetchError ? undefined : totalDecimal;
// mUSD is USD-pegged 1:1, so the dollar value equals the token amount —
// no conversion rate is needed to show the balance in dollars.
return {
tokenTotal: computedTokenTotal,
totalFiat: computedTokenTotal,
withdrawableFiat: computedWithdrawableMusd,
withdrawableMusd: computedWithdrawableMusd,
};
}, [isBalanceLoading, isBalanceFetchError, moneyBalanceQuery.data]);
const totalFiatFormatted =
!isBalanceFetchError && totalFiat ? moneyFormatUsd(totalFiat) : undefined;
const totalFiatRaw =
!isBalanceFetchError && totalFiat ? totalFiat.toString() : undefined;
const withdrawableFiatFormatted =
!isBalanceFetchError && withdrawableFiat
? moneyFormatUsd(withdrawableFiat)
: undefined;
const withdrawableFiatRaw =
!isBalanceFetchError && withdrawableFiat
? withdrawableFiat.toString()
: undefined;
// Persist every successful balance so it can be shown as the "last known"
// figure (for the current account/currency) the next time the live balance
// is unavailable — including after an app restart.
useEffect(() => {
if (
moneyAccountAddress &&
!isBalanceFetchError &&
!isBalanceLoading &&
totalFiatFormatted !== undefined
) {
dispatch(
setLastKnownMoneyBalance({
address: moneyAccountAddress,
value: totalFiatFormatted,
currency: currentCurrency,
updatedAt: Date.now(),
}),
);
}
}, [
dispatch,
moneyAccountAddress,
isBalanceFetchError,
totalFiatFormatted,
currentCurrency,
isBalanceLoading,
]);
// True whenever there is no fresh balance to show — still loading or a fetch
// error.
const isBalanceUnavailable = totalFiatFormatted === undefined;
// Last successfully fetched balance, but only when it still matches the
// account and currency in view; otherwise it would be misleading.
const lastKnownTotalFiatFormatted = isPersistedMoneyBalanceUsable(
lastKnownBalance,
{ address: moneyAccountAddress, currency: currentCurrency },
)
? lastKnownBalance.value
: undefined;
const liveServiceApy = vaultApyQuery.data?.apy;
// Currently `BaseDataService` in core clears cached data every 5 minutes
// even if it's actively observed. When the component using this hook re-renders
// this lead to `data:undefined` being returned.
//
// This should be properly fixed in core - but for the time being we've
// created this ref which holds onto the last known value - so in cases
// where we lose the underlying data we still render the last good value.
const lastKnownServiceApyRef = useRef<number | undefined>(undefined);
useEffect(() => {
if (liveServiceApy !== undefined) {
lastKnownServiceApyRef.current = liveServiceApy;
}
}, [liveServiceApy]);
const serviceApy = liveServiceApy ?? lastKnownServiceApyRef.current;
// During first load with no cache, do not show fallback to avoid flicker.
// Show fallback on explicit APY query errors (service outage path) or when
// a settled query still yields no APY value.
const shouldUseFallback =
!vaultApyQuery.isLoading &&
(vaultApyQuery.isError || serviceApy === undefined);
// Override always wins when set; otherwise use live service value; then use
// fallback only when the APY query is settled/error and no live APY exists.
const apyDecimal =
vaultApyOverride !== undefined
? vaultApyOverride
: (serviceApy ?? (shouldUseFallback ? vaultApyFallback : undefined));
const apyPercent =
apyDecimal !== undefined
? new BigNumber(apyDecimal)
.multipliedBy(100)
.dp(1, BigNumber.ROUND_HALF_UP)
.toNumber()
: undefined;
const apyPercentFormatted =
apyPercent !== undefined ? `${apyPercent}%` : undefined;
const isApyLoading = vaultApyQuery.isLoading && apyDecimal === undefined;
return {
moneyBalanceQuery,
vaultApyQuery,
isBalanceLoading,
isBalanceFetchError,
isBalanceFetching,
isBalanceUnavailable,
lastKnownTotalFiatFormatted,
refetchBalance,
tokenTotal,
totalFiatFormatted,
totalFiatRaw,
withdrawableFiatFormatted,
withdrawableFiatRaw,
withdrawableMusd,
apyDecimal,
apyPercent,
apyPercentFormatted,
isApyLoading,
};
};
export default useMoneyAccountBalance;