@talismn/balances-react 0.0.0-pr524-20230223180944 → 0.0.0-pr524-20230310034933

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,16 +1,196 @@
1
- import { Balances, db, balances } from '@talismn/balances';
1
+ import { useContext, createContext, useState, useEffect, useMemo, useRef, useCallback } from 'react';
2
+ import { jsx } from 'react/jsx-runtime';
2
3
  import { ChainConnector } from '@talismn/chain-connector';
3
4
  import { ChainConnectorEvm } from '@talismn/chain-connector-evm';
5
+ import { ChaindataProviderExtension } from '@talismn/chaindata-provider-extension';
6
+ import { db as db$1, balances, Balances } from '@talismn/balances';
7
+ import { db, fetchTokenRates } from '@talismn/token-rates';
4
8
  import { useLiveQuery } from 'dexie-react-hooks';
5
- import { useState, useEffect, useRef } from 'react';
6
9
  import { useDebounce } from 'react-use';
10
+ import md5 from 'blueimp-md5';
7
11
  import anylogger from 'anylogger';
8
- import { ChaindataProviderExtension } from '@talismn/chaindata-provider-extension';
9
- import { fetchTokenRates } from '@talismn/token-rates';
12
+ import { Subject, Observable, defer, shareReplay } from 'rxjs';
13
+
14
+ const provideContext = useProviderContext => {
15
+ // automatic typing based on our hook's return type
16
+
17
+ const Context = /*#__PURE__*/createContext({
18
+ __provideContextInternalDefaultValue: true
19
+ });
20
+ const Provider = ({
21
+ children,
22
+ ...props
23
+ }) => {
24
+ const ctx = useProviderContext(props);
25
+ return /*#__PURE__*/jsx(Context.Provider, {
26
+ value: ctx,
27
+ children: children
28
+ });
29
+ };
30
+ const useProvidedContext = () => {
31
+ const context = useContext(Context);
32
+ if (typeof context === "object" && context && "__provideContextInternalDefaultValue" in context) throw new Error("This hook requires a provider to be present above it in the tree");
33
+ return context;
34
+ };
35
+ const result = [Provider, useProvidedContext];
36
+ return result;
37
+ };
38
+
39
+ const useAllAddressesProvider = () => useState([]);
40
+ const [AllAddressesProvider, useAllAddresses] = provideContext(useAllAddressesProvider);
41
+
42
+ function useChaindataProvider(options = {}) {
43
+ const [onfinalityApiKey, setOnfinalityApiKey] = useState(options.onfinalityApiKey);
44
+
45
+ // make sure we recreate provider only when the onfinalityApiKey changes
46
+ useEffect(() => {
47
+ if (options.onfinalityApiKey !== onfinalityApiKey) setOnfinalityApiKey(options.onfinalityApiKey);
48
+ }, [options.onfinalityApiKey, onfinalityApiKey]);
49
+ return useMemo(() => new ChaindataProviderExtension({
50
+ onfinalityApiKey
51
+ }), [onfinalityApiKey]);
52
+ }
53
+ const [ChaindataProvider, useChaindata] = provideContext(useChaindataProvider);
54
+
55
+ function useChainConnectorsProvider(options) {
56
+ const [onfinalityApiKey, setOnfinalityApiKey] = useState(options.onfinalityApiKey);
57
+
58
+ // make sure we recreate provider only when the onfinalityApiKey changes
59
+ useEffect(() => {
60
+ if (options.onfinalityApiKey !== onfinalityApiKey) setOnfinalityApiKey(options.onfinalityApiKey);
61
+ }, [options.onfinalityApiKey, onfinalityApiKey]);
62
+
63
+ // chaindata dependency
64
+ const chaindata = useChaindata();
65
+
66
+ // substrate connector
67
+ const substrate = useMemo(() => new ChainConnector(chaindata), [chaindata]);
68
+
69
+ // evm connector
70
+ const evm = useMemo(() => new ChainConnectorEvm(chaindata, {
71
+ onfinalityApiKey
72
+ }), [chaindata, onfinalityApiKey]);
73
+ return useMemo(() => ({
74
+ substrate,
75
+ evm
76
+ }), [substrate, evm]);
77
+ }
78
+ const [ChainConnectorsProvider, useChainConnectors] = provideContext(useChainConnectorsProvider);
79
+
80
+ const useBalanceModulesProvider = ({
81
+ balanceModules
82
+ }) => {
83
+ const chainConnectors = useChainConnectors();
84
+ const chaindataProvider = useChaindata();
85
+ const hydrated = useMemo(() => chainConnectors.substrate && chainConnectors.evm && chaindataProvider ? balanceModules.map(mod => mod({
86
+ chainConnectors,
87
+ chaindataProvider
88
+ })) : [], [balanceModules, chainConnectors, chaindataProvider]);
89
+ return hydrated;
90
+ };
91
+ const [BalanceModulesProvider, useBalanceModules] = provideContext(useBalanceModulesProvider);
92
+
93
+ const filterNoTestnet = ({
94
+ isTestnet
95
+ }) => isTestnet === false;
96
+ const DEFAULT_VALUE = {
97
+ chainsWithTestnets: [],
98
+ chainsWithoutTestnets: [],
99
+ evmNetworksWithTestnets: [],
100
+ evmNetworksWithoutTestnets: [],
101
+ tokensWithTestnets: [],
102
+ tokensWithoutTestnets: [],
103
+ chainsWithTestnetsMap: {},
104
+ chainsWithoutTestnetsMap: {},
105
+ evmNetworksWithTestnetsMap: {},
106
+ evmNetworksWithoutTestnetsMap: {},
107
+ tokensWithTestnetsMap: {},
108
+ tokensWithoutTestnetsMap: {},
109
+ tokenRatesMap: {},
110
+ balances: []
111
+ };
112
+ const consolidateDbCache = (chainsMap, evmNetworksMap, tokensMap, tokenRates, allBalances) => {
113
+ if (!chainsMap || !evmNetworksMap || !tokensMap || !tokenRates || !allBalances) return DEFAULT_VALUE;
114
+
115
+ // BEGIN: temp hack to indicate that
116
+ // - EVM GLMR is a mirror of substrate GLMR
117
+ // - EVM MOVR is a mirror of substrate MOVR
118
+ // - EVM DEV is a mirror of substrate DEV
119
+ // - EVM ACA is a mirror of substrate ACA
120
+ const mirrorTokenIds = {
121
+ "1284-evm-native-glmr": "moonbeam-substrate-native-glmr",
122
+ "1285-evm-native-movr": "moonriver-substrate-native-movr",
123
+ "1287-evm-native-dev": "moonbase-alpha-testnet-substrate-native-dev",
124
+ "787-evm-native-aca": "acala-substrate-native-aca"
125
+ };
126
+ Object.entries(mirrorTokenIds).filter(([mirrorToken]) => tokensMap[mirrorToken]).forEach(([mirrorToken, mirrorOf]) => tokensMap[mirrorToken].mirrorOf = mirrorOf);
127
+ // END: temp hack
128
+
129
+ const chainsWithTestnets = Object.values(chainsMap);
130
+ const chainsWithoutTestnets = chainsWithTestnets.filter(filterNoTestnet);
131
+ const chainsWithoutTestnetsMap = Object.fromEntries(chainsWithoutTestnets.map(network => [network.id, network]));
132
+ const evmNetworksWithTestnets = Object.values(evmNetworksMap);
133
+ const evmNetworksWithoutTestnets = evmNetworksWithTestnets.filter(filterNoTestnet);
134
+ const evmNetworksWithoutTestnetsMap = Object.fromEntries(evmNetworksWithoutTestnets.map(network => [network.id, network]));
135
+
136
+ // ensure that we have corresponding network for each token
137
+ const tokensWithTestnets = Object.values(tokensMap).filter(token => token.chain && chainsMap[token.chain.id] || token.evmNetwork && evmNetworksMap[token.evmNetwork.id]);
138
+ const tokensWithoutTestnets = tokensWithTestnets.filter(filterNoTestnet).filter(token => token.chain && chainsWithoutTestnetsMap[token.chain.id] || token.evmNetwork && evmNetworksWithoutTestnetsMap[token.evmNetwork.id]);
139
+ const tokensWithTestnetsMap = Object.fromEntries(tokensWithTestnets.map(token => [token.id, token]));
140
+ const tokensWithoutTestnetsMap = Object.fromEntries(tokensWithoutTestnets.map(token => [token.id, token]));
141
+ const tokenRatesMap = Object.fromEntries(tokenRates.map(({
142
+ tokenId,
143
+ rates
144
+ }) => [tokenId, rates]));
145
+
146
+ // return only balances for which we have a token
147
+ const balances = allBalances.filter(b => tokensWithTestnetsMap[b.tokenId]);
148
+ return {
149
+ chainsWithTestnets,
150
+ chainsWithoutTestnets,
151
+ evmNetworksWithTestnets,
152
+ evmNetworksWithoutTestnets,
153
+ tokensWithTestnets,
154
+ tokensWithoutTestnets,
155
+ chainsWithTestnetsMap: chainsMap,
156
+ chainsWithoutTestnetsMap,
157
+ evmNetworksWithTestnetsMap: evmNetworksMap,
158
+ evmNetworksWithoutTestnetsMap,
159
+ tokensWithTestnetsMap,
160
+ tokensWithoutTestnetsMap,
161
+ tokenRatesMap,
162
+ balances
163
+ };
164
+ };
165
+ const useDbCacheProvider = () => {
166
+ const chaindataProvider = useChaindata();
167
+ const chainList = useLiveQuery(() => chaindataProvider === null || chaindataProvider === void 0 ? void 0 : chaindataProvider.chains(), [chaindataProvider]);
168
+ const evmNetworkList = useLiveQuery(() => chaindataProvider === null || chaindataProvider === void 0 ? void 0 : chaindataProvider.evmNetworks(), [chaindataProvider]);
169
+ const tokenList = useLiveQuery(() => chaindataProvider === null || chaindataProvider === void 0 ? void 0 : chaindataProvider.tokens(), [chaindataProvider]);
170
+ const tokenRates = useLiveQuery(() => db.tokenRates.toArray(), []);
171
+ const rawBalances = useLiveQuery(() => db$1.balances.toArray(), []);
172
+ const [dbData, setDbData] = useState(DEFAULT_VALUE);
173
+
174
+ // debounce every 500ms to prevent hammering UI with updates
175
+ useDebounce(() => {
176
+ setDbData(consolidateDbCache(chainList, evmNetworkList, tokenList, tokenRates, rawBalances));
177
+ }, 500, [chainList, evmNetworkList, tokenList, rawBalances, tokenRates]);
178
+ const refInitialized = useRef(false);
179
+
180
+ // force an update as soon as all datasources are fetched, so UI can display data ASAP
181
+ useEffect(() => {
182
+ if (!refInitialized.current && chainList && evmNetworkList && tokenList && tokenRates && rawBalances) {
183
+ setDbData(consolidateDbCache(chainList, evmNetworkList, tokenList, tokenRates, rawBalances));
184
+ refInitialized.current = true;
185
+ }
186
+ }, [chainList, evmNetworkList, rawBalances, tokenList, tokenRates]);
187
+ return dbData;
188
+ };
189
+ const [DbCacheProvider, useDbCache] = provideContext(useDbCacheProvider);
10
190
 
11
191
  var packageJson = {
12
192
  name: "@talismn/balances-react",
13
- version: "0.0.0-pr524-20230223180944",
193
+ version: "0.0.0-pr524-20230310034933",
14
194
  author: "Talisman",
15
195
  homepage: "https://talisman.xyz",
16
196
  license: "UNLICENSED",
@@ -43,9 +223,11 @@ var packageJson = {
43
223
  "@talismn/chaindata-provider-extension": "workspace:^",
44
224
  "@talismn/token-rates": "workspace:^",
45
225
  anylogger: "^1.0.11",
226
+ "blueimp-md5": "2.19.0",
46
227
  dexie: "^3.2.3",
47
228
  "dexie-react-hooks": "^1.1.1",
48
- "react-use": "^17.4.0"
229
+ "react-use": "^17.4.0",
230
+ rxjs: "^7.8.0"
49
231
  },
50
232
  devDependencies: {
51
233
  "@talismn/eslint-config": "workspace:^",
@@ -72,139 +254,365 @@ var packageJson = {
72
254
 
73
255
  var log = anylogger(packageJson.name);
74
256
 
75
- // TODO: Allow user to call useChaindata from multiple places
76
- function useChaindata(options = {}) {
77
- const [chaindataProvider, setChaindataProvider] = useState(null);
257
+ // global data store containing all subscriptions
258
+ const subscriptions = {};
78
259
 
79
- // this number is incremented each time the chaindataProvider has fetched new data
80
- const [generation, setGeneration] = useState(0);
260
+ /**
261
+ * This hook ensures a subscription is created only once, and unsubscribe automatically as soon as there is no consumer to the hook
262
+ * @param key key that is unique to the subscription's parameters
263
+ * @param subscribe // subscribe function that will be shared by all consumers of the key
264
+ */
265
+ const useSharedSubscription = (key, subscribe) => {
266
+ // create the rxJS subject if it doesn't exist
267
+ if (!subscriptions[key]) subscriptions[key] = {
268
+ subject: new Subject()
269
+ };
81
270
  useEffect(() => {
82
- const chaindataProvider = new ChaindataProviderExtension({
83
- onfinalityApiKey: options.onfinalityApiKey
84
- });
85
- let shouldHydrate = true;
86
- const timer = 300_000; // 300_000ms = 300s = 5 minutes
87
- const hydrate = async () => {
88
- if (!shouldHydrate) return;
89
- try {
90
- const updated = await chaindataProvider.hydrate();
91
- if (updated) setGeneration(generation => (generation + 1) % Number.MAX_SAFE_INTEGER);
92
- setTimeout(hydrate, timer);
93
- } catch (error) {
94
- const retryTimeout = 5_000; // 5_000ms = 5 seconds
95
- log.error(`Failed to fetch chaindata, retrying in ${Math.round(retryTimeout / 1000)} seconds`, error);
96
- setTimeout(hydrate, retryTimeout);
271
+ // subscribe to subject.
272
+ // it won't change but we need to count subscribers, to unsubscribe main subscription when no more observers
273
+ const s = subscriptions[key].subject.subscribe();
274
+ return () => {
275
+ // unsubscribe from our local observable updates to prevent memory leaks
276
+ s.unsubscribe();
277
+ const {
278
+ subject,
279
+ unsubscribe
280
+ } = subscriptions[key];
281
+ if (!subject.observed && unsubscribe) {
282
+ log.debug(`[useSharedSubscription] unsubscribing ${key}`);
283
+
284
+ // unsubscribe from backend updates to prevent unnecessary network connections
285
+ unsubscribe();
286
+ delete subscriptions[key].unsubscribe;
97
287
  }
98
288
  };
99
- setChaindataProvider(chaindataProvider);
100
- hydrate();
289
+ }, [key]);
290
+
291
+ // Initialize subscription
292
+ useEffect(() => {
293
+ const {
294
+ unsubscribe
295
+ } = subscriptions[key];
296
+ // launch the subscription if it's a new key
297
+ if (!unsubscribe) {
298
+ const cb = subscribe();
299
+ log.debug(`[useSharedSubscription] subscribing ${key}`);
300
+ if (cb) subscriptions[key].unsubscribe = cb;
301
+ // this error should only happen when developping a new hook, let it bubble up
302
+ else throw new Error(`${key} subscribe did not return an unsubscribe callback`);
303
+ }
304
+ }, [key, subscribe]);
305
+ };
306
+
307
+ function useTokens(withTestnets) {
308
+ // keep db data up to date
309
+ useDbCacheSubscription("tokens");
310
+ const {
311
+ tokensWithTestnetsMap,
312
+ tokensWithoutTestnetsMap
313
+ } = useDbCache();
314
+ return withTestnets ? tokensWithTestnetsMap : tokensWithoutTestnetsMap;
315
+ }
316
+ function useToken(tokenId, withTestnets) {
317
+ const tokens = useTokens(withTestnets);
318
+ return tokenId ? tokens[tokenId] : undefined;
319
+ }
320
+
321
+ /**
322
+ * Creates a subscription function that can be used to subscribe to a multicast observable created from an upstream source.
323
+ *
324
+ * An example of when this is useful is when we want to subscribe to some data from multiple components, but we only want
325
+ * to actively keep that data hydrated when at least one component is subscribed to it.
326
+ *
327
+ * When the first component subscribes, the `upstream` function will be called. It should then set up a subscription and return a teardown function.
328
+ * When subsequent components subscribe, they will be added to the existing subscription.
329
+ * When the last component unsubscribes, the teardown function returned from the `upstream` function will be called.
330
+ *
331
+ * @param upstream A function that takes a "next" callback function as an argument, and returns either an unsubscribe function or void.
332
+ * @returns A subscription function that can be used to subscribe to the multicast observable.
333
+ */
334
+ const useMulticastSubscription = upstream => {
335
+ const subscribe = useMemo(() => createMulticastSubscription(upstream), [upstream]);
336
+ return subscribe;
337
+ };
338
+ const createMulticastSubscription = upstream => {
339
+ // Create an upstream observable using the provided function.
340
+ const upstreamObservable = new Observable(subscriber => {
341
+ const unsubscribe = upstream(val => subscriber.next(val));
101
342
  return () => {
102
- shouldHydrate = false;
343
+ typeof unsubscribe === "function" && unsubscribe();
103
344
  };
104
- }, [options.onfinalityApiKey]);
105
- if (chaindataProvider) chaindataProvider.generation = generation;
106
- return chaindataProvider;
107
- }
108
- function useChains(chaindata) {
109
- const [chains, setChains] = useState();
110
- useEffect(() => {
111
- if (!chaindata) return;
112
- const thisGeneration = chaindata.generation;
113
- chaindata.chains().then(chains => {
114
- if (thisGeneration !== chaindata.generation) return;
115
- setChains(chains);
116
- });
117
- }, [chaindata, chaindata === null || chaindata === void 0 ? void 0 : chaindata.generation]);
118
- return chains || {};
345
+ });
346
+
347
+ // Create a multicast observable from the upstream observable, using the shareReplay operator.
348
+ const multicastObservable = defer(() => upstreamObservable).pipe(shareReplay({
349
+ bufferSize: 1,
350
+ refCount: true
351
+ }));
352
+
353
+ // Create a subscription function that subscribes to the multicast observable and returns an unsubscribe function.
354
+ const subscribe = callback => {
355
+ const subscription = multicastObservable.subscribe(callback);
356
+ const unsubscribe = () => subscription.unsubscribe();
357
+ return unsubscribe;
358
+ };
359
+ return subscribe;
360
+ };
361
+
362
+ const useWithTestnetsProvider = ({
363
+ withTestnets
364
+ }) => {
365
+ return {
366
+ withTestnets
367
+ };
368
+ };
369
+ const [WithTestnetsProvider, useWithTestnets] = provideContext(useWithTestnetsProvider);
370
+
371
+ /**
372
+ * This hook is responsible for fetching the data used for balances and inserting it into the db.
373
+ */
374
+ const useDbCacheSubscription = subscribeTo => {
375
+ const provider = useChaindata();
376
+
377
+ // can't handle balances & tokenRates here as they have other dependencies, it would trigger to many subscriptions
378
+ const subscribe = useCallback(() => {
379
+ switch (subscribeTo) {
380
+ case "chains":
381
+ return subscribeChainDataHydrate(provider, "chains");
382
+ case "evmNetworks":
383
+ return subscribeChainDataHydrate(provider, "evmNetworks");
384
+ case "tokens":
385
+ return subscribeChainDataHydrate(provider, "tokens");
386
+ }
387
+ }, [provider, subscribeTo]);
388
+ useSharedSubscription(subscribeTo, subscribe);
389
+ };
390
+
391
+ /**
392
+ * This hook is responsible for fetching the data used for token rates and inserting it into the db.
393
+ */
394
+ function useDbCacheTokenRatesSubscription() {
395
+ const {
396
+ withTestnets
397
+ } = useWithTestnets();
398
+ const tokens = useTokens(withTestnets);
399
+ const subscriptionKey = useMemo(
400
+ // not super sexy but we need key to change based on this stuff
401
+ () => {
402
+ const key = Object.values(tokens ?? {}).map(({
403
+ id
404
+ }) => id).sort().join();
405
+ return `tokenRates-${md5(key)}`;
406
+ }, [tokens]);
407
+ const subscription = useCallback(() => {
408
+ if (!Object.values(tokens ?? {}).length) return () => {};
409
+ return subscribeTokenRates(tokens);
410
+ }, [tokens]);
411
+ useSharedSubscription(subscriptionKey, subscription);
119
412
  }
120
- function useChain(chaindata, chainId) {
121
- const [chain, setChain] = useState();
122
- useEffect(() => {
123
- if (chaindata === null) return;
124
- if (!chainId) return;
125
- chaindata.getChain(chainId).then(setChain);
126
- }, [chainId, chaindata, chaindata === null || chaindata === void 0 ? void 0 : chaindata.generation]);
127
- return chain;
413
+
414
+ /**
415
+ * This hook is responsible for fetching the data used for balances and inserting it into the db.
416
+ */
417
+ function useDbCacheBalancesSubscription() {
418
+ const {
419
+ withTestnets
420
+ } = useWithTestnets();
421
+ const balanceModules = useBalanceModules();
422
+ const chaindataProvider = useChaindata();
423
+ const chainConnectors = useChainConnectors();
424
+ const [allAddresses] = useAllAddresses();
425
+ const tokens = useTokens(withTestnets);
426
+ const subscriptionKey = useMemo(
427
+ // not super sexy but we need key to change based on this stuff
428
+ () => {
429
+ const key = allAddresses.sort().join().concat(...Object.values(tokens ?? {}).map(({
430
+ id
431
+ }) => id).sort()).concat(`evm:${!!chainConnectors.evm}`, `sub:${!!chainConnectors.substrate}`, ...balanceModules.map(m => m.type).sort(), `cd:${!!chaindataProvider}`);
432
+ return `balances-${md5(key)}`;
433
+ }, [allAddresses, balanceModules, chainConnectors, chaindataProvider, tokens]);
434
+ const subscription = useCallback(() => {
435
+ if (!Object.values(tokens ?? {}).length || !allAddresses.length) return () => {};
436
+ return subscribeBalances(tokens ?? {}, allAddresses, chainConnectors, chaindataProvider, balanceModules);
437
+ }, [allAddresses, balanceModules, chainConnectors, chaindataProvider, tokens]);
438
+ useSharedSubscription(subscriptionKey, subscription);
128
439
  }
129
- function useEvmNetworks(chaindata) {
130
- const [evmNetworks, setEvmNetworks] = useState();
131
- useEffect(() => {
132
- if (!chaindata) return;
133
- const thisGeneration = chaindata.generation;
134
- chaindata.evmNetworks().then(evmNetworks => {
135
- if (thisGeneration !== chaindata.generation) return;
136
- setEvmNetworks(evmNetworks);
440
+ const subscribeChainDataHydrate = (provider, type) => {
441
+ const chaindata = provider;
442
+ const delay = 300_000; // 300_000ms = 300s = 5 minutes
443
+
444
+ let timeout = null;
445
+ const hydrate = async () => {
446
+ try {
447
+ if (type === "chains") await chaindata.hydrateChains();
448
+ if (type === "evmNetworks") await chaindata.hydrateEvmNetworks();
449
+ if (type === "tokens") await chaindata.hydrateTokens();
450
+ timeout = setTimeout(hydrate, delay);
451
+ } catch (error) {
452
+ const retryTimeout = 5_000; // 5_000ms = 5 seconds
453
+ log.error(`Failed to fetch chaindata, retrying in ${Math.round(retryTimeout / 1000)} seconds`, error);
454
+ timeout = setTimeout(hydrate, retryTimeout);
455
+ }
456
+ };
457
+
458
+ // launch the loop
459
+ hydrate();
460
+ return () => {
461
+ if (timeout) clearTimeout(timeout);
462
+ };
463
+ };
464
+ const subscribeTokenRates = tokens => {
465
+ const REFRESH_INTERVAL = 300_000; // 6 minutes
466
+ const RETRY_INTERVAL = 5_000; // 5 sec
467
+
468
+ let timeout = null;
469
+ const refreshTokenRates = async () => {
470
+ try {
471
+ if (timeout) clearTimeout(timeout);
472
+ const tokenRates = await fetchTokenRates(tokens);
473
+ const putTokenRates = Object.entries(tokenRates).map(([tokenId, rates]) => ({
474
+ tokenId,
475
+ rates
476
+ }));
477
+ db.transaction("rw", db.tokenRates, async () => await db.tokenRates.bulkPut(putTokenRates));
478
+ timeout = setTimeout(() => {
479
+ refreshTokenRates();
480
+ }, REFRESH_INTERVAL);
481
+ } catch (error) {
482
+ log.error(`Failed to fetch tokenRates, retrying in ${Math.round(RETRY_INTERVAL / 1000)} seconds`, error);
483
+ setTimeout(async () => {
484
+ refreshTokenRates();
485
+ }, RETRY_INTERVAL);
486
+ }
487
+ };
488
+
489
+ // launch the loop
490
+ refreshTokenRates();
491
+ return () => {
492
+ if (timeout) clearTimeout(timeout);
493
+ };
494
+ };
495
+ const subscribeBalances = (tokens, addresses, chainConnectors, provider, balanceModules) => {
496
+ const tokenIds = Object.values(tokens).map(({
497
+ id
498
+ }) => id);
499
+ const addressesByToken = Object.fromEntries(tokenIds.map(tokenId => [tokenId, addresses]));
500
+ const updateDb = balances => {
501
+ const putBalances = Object.entries(balances.toJSON()).map(([id, balance]) => ({
502
+ id,
503
+ ...balance
504
+ }));
505
+ db$1.transaction("rw", db$1.balances, async () => await db$1.balances.bulkPut(putBalances));
506
+ };
507
+ let unsubscribed = false;
508
+
509
+ // eslint-disable-next-line no-console
510
+ log.log("subscribing to balance changes for %d tokens and %d addresses", tokenIds.length, addresses.length);
511
+ const unsubs = balanceModules.map(async balanceModule => {
512
+ // filter out tokens to only include those which this module knows how to fetch balances for
513
+ const moduleTokenIds = Object.values(tokens ?? {}).filter(({
514
+ type
515
+ }) => type === balanceModule.type).map(({
516
+ id
517
+ }) => id);
518
+ const addressesByModuleToken = Object.fromEntries(Object.entries(addressesByToken).filter(([tokenId]) => moduleTokenIds.includes(tokenId)));
519
+ const unsub = balances(balanceModule, addressesByModuleToken, (error, balances) => {
520
+ // log errors
521
+ if (error) return log.error(`Failed to fetch ${balanceModule.type} balances`, error);
522
+ // ignore empty balance responses
523
+ if (!balances) return;
524
+ // ignore balances from old subscriptions which are still in the process of unsubscribing
525
+ if (unsubscribed) return;
526
+ updateDb(balances);
137
527
  });
138
- }, [chaindata, chaindata === null || chaindata === void 0 ? void 0 : chaindata.generation]);
139
- return evmNetworks || {};
528
+ return () => {
529
+ // wait 2 seconds before actually unsubscribing, allowing for websocket to be reused
530
+ unsub.then(unsubscribe => {
531
+ setTimeout(unsubscribe, 2_000);
532
+ });
533
+ db$1.transaction("rw", db$1.balances, async () => await db$1.balances.filter(balance => {
534
+ if (balance.source !== balanceModule.type) return false;
535
+ if (!Object.keys(addressesByModuleToken).includes(balance.tokenId)) return false;
536
+ if (!addressesByModuleToken[balance.tokenId].includes(balance.address)) return false;
537
+ return true;
538
+ }).modify({
539
+ status: "cache"
540
+ }));
541
+ };
542
+ });
543
+ const unsubscribeAll = () => {
544
+ unsubscribed = true;
545
+ unsubs.forEach(unsub => unsub.then(unsubscribe => unsubscribe()));
546
+ };
547
+ return unsubscribeAll;
548
+ };
549
+
550
+ function useChains(withTestnets) {
551
+ // keep db data up to date
552
+ useDbCacheSubscription("chains");
553
+ const {
554
+ chainsWithTestnetsMap,
555
+ chainsWithoutTestnetsMap
556
+ } = useDbCache();
557
+ return withTestnets ? chainsWithTestnetsMap : chainsWithoutTestnetsMap;
140
558
  }
141
- function useEvmNetwork(chaindata, evmNetworkId) {
142
- const [evmNetwork, setEvmNetwork] = useState();
143
- useEffect(() => {
144
- if (chaindata === null) return;
145
- if (!evmNetworkId) return;
146
- chaindata.getEvmNetwork(evmNetworkId).then(setEvmNetwork);
147
- }, [chaindata, chaindata === null || chaindata === void 0 ? void 0 : chaindata.generation, evmNetworkId]);
148
- return evmNetwork;
559
+ function useChain(chainId, withTestnets) {
560
+ const chains = useChains(withTestnets);
561
+ return chainId ? chains[chainId] : undefined;
149
562
  }
150
- function useTokens(chaindata) {
151
- const [tokens, setTokens] = useState();
152
- useEffect(() => {
153
- if (!chaindata) return;
154
- const thisGeneration = chaindata.generation;
155
- chaindata.tokens().then(tokens => {
156
- if (thisGeneration !== chaindata.generation) return;
157
- setTokens(tokens);
158
- });
159
- }, [chaindata, chaindata === null || chaindata === void 0 ? void 0 : chaindata.generation]);
160
- return tokens || {};
563
+
564
+ function useEvmNetworks(withTestnets) {
565
+ // keep db data up to date
566
+ useDbCacheSubscription("evmNetworks");
567
+ const {
568
+ evmNetworksWithTestnetsMap,
569
+ evmNetworksWithoutTestnetsMap
570
+ } = useDbCache();
571
+ return withTestnets ? evmNetworksWithTestnetsMap : evmNetworksWithoutTestnetsMap;
161
572
  }
162
- function useToken(chaindata, tokenId) {
163
- const [token, setToken] = useState();
164
- useEffect(() => {
165
- if (chaindata === null) return;
166
- if (!tokenId) return;
167
- chaindata.getToken(tokenId).then(setToken);
168
- }, [chaindata, chaindata === null || chaindata === void 0 ? void 0 : chaindata.generation, tokenId]);
169
- return token;
573
+ function useEvmNetwork(evmNetworkId, withTestnets) {
574
+ const evmNetworks = useEvmNetworks(withTestnets);
575
+ return evmNetworkId ? evmNetworks[evmNetworkId] : undefined;
170
576
  }
171
577
 
172
- function useTokenRates(tokens) {
173
- const generation = useRef(0);
174
- const [tokenRates, setTokenRates] = useState();
175
- useEffect(() => {
176
- if (!tokens) return;
177
- if (Object.keys(tokens).length < 1) return;
178
-
179
- // when we make a new request, we want to ignore any old requests which haven't yet completed
180
- // otherwise we risk replacing the most recent data with older data
181
- generation.current = (generation.current + 1) % Number.MAX_SAFE_INTEGER;
182
- const thisGeneration = generation.current;
183
- fetchTokenRates(tokens).then(tokenRates => {
184
- if (thisGeneration !== generation.current) return;
185
- setTokenRates(tokenRates);
186
- });
187
- }, [tokens]);
188
- return tokenRates || {};
578
+ function useTokenRates() {
579
+ // keep db data up to date
580
+ useDbCacheTokenRatesSubscription();
581
+ const {
582
+ tokenRatesMap
583
+ } = useDbCache();
584
+ return tokenRatesMap;
585
+ }
586
+ function useTokenRate(tokenId) {
587
+ const tokenRates = useTokenRates();
588
+ return tokenId ? tokenRates[tokenId] : undefined;
189
589
  }
190
590
 
191
- // TODO: Add the equivalent functionalty of `useDbCache` directly to this library.
192
- //
193
- // How it will work:
194
- //
195
- // useChains/useEvmNetworks/useTokens/useTokenRates will all make use of a
196
- // useCachedDb hook, which internally subscribes to all of the db tables
197
- // for everything, and then filters the subscribed data based on what params
198
- // the caller of useChains/useTokens/etc has provided.
199
- function useBalances(
200
- // TODO: Make this array of BalanceModules more type-safe
201
- balanceModules, chaindataProvider, addressesByToken, options = {}) {
202
- useBalancesSubscriptions(balanceModules, chaindataProvider, addressesByToken, options);
203
- const chains = useChains(chaindataProvider);
204
- const evmNetworks = useEvmNetworks(chaindataProvider);
205
- const tokens = useTokens(chaindataProvider);
206
- const tokenRates = useTokenRates(tokens);
207
- const balances = useLiveQuery(async () => new Balances(await db.balances.filter(balance => {
591
+ const useBalancesHydrate = () => {
592
+ const {
593
+ withTestnets
594
+ } = useWithTestnets();
595
+ const chains = useChains(withTestnets);
596
+ const evmNetworks = useEvmNetworks(withTestnets);
597
+ const tokens = useTokens(withTestnets);
598
+ const tokenRates = useTokenRates();
599
+ return useMemo(() => ({
600
+ chains,
601
+ evmNetworks,
602
+ tokens,
603
+ tokenRates
604
+ }), [chains, evmNetworks, tokens, tokenRates]);
605
+ };
606
+
607
+ function useBalances(addressesByToken) {
608
+ // keep db data up to date
609
+ useDbCacheBalancesSubscription();
610
+ const balanceModules = useBalanceModules();
611
+ const {
612
+ balances
613
+ } = useDbCache();
614
+ const hydrate = useBalancesHydrate();
615
+ return useMemo(() => new Balances(balances.filter(balance => {
208
616
  // check that this balance is included in our queried balance modules
209
617
  if (!balanceModules.map(({
210
618
  type
@@ -221,137 +629,32 @@ balanceModules, chaindataProvider, addressesByToken, options = {}) {
221
629
 
222
630
  // keep this balance
223
631
  return true;
224
- }).toArray(),
632
+ }),
225
633
  // hydrate balance chains, evmNetworks, tokens and tokenRates
226
- {
227
- chains,
228
- evmNetworks,
229
- tokens,
230
- tokenRates
231
- }), [balanceModules, addressesByToken, chains, evmNetworks, tokens, tokenRates]);
232
-
233
- // debounce every 100ms to prevent hammering UI with updates
234
- const [debouncedBalances, setDebouncedBalances] = useState(balances);
235
- useDebounce(() => balances && setDebouncedBalances(balances), 100, [balances]);
236
- return debouncedBalances;
634
+ hydrate), [balances, hydrate, balanceModules, addressesByToken]);
237
635
  }
238
636
 
239
- // TODO: Turn into react context
240
- const subscriptions = {};
241
-
242
- // This hook is responsible for allowing us to call useBalances
243
- // from multiple components, without setting up unnecessary
244
- // balance subscriptions
245
- function useBalancesSubscriptions(
246
- // TODO: Make this array of BalanceModules more type-safe
247
- balanceModules, chaindataProvider, addressesByToken, options = {}) {
248
- // const subscriptions = useRef<
249
- // Record<string, { unsub: Promise<() => void>; refcount: number; generation: number }>
250
- // >({})
251
-
252
- const addSubscription = (key, balanceModule, chainConnectors, chaindataProvider, addressesByToken) => {
253
- // create subscription if it doesn't already exist
254
- if (!subscriptions[key] || subscriptions[key].refcount === 0) {
255
- var _subscriptions$key;
256
- const generation = ((((_subscriptions$key = subscriptions[key]) === null || _subscriptions$key === void 0 ? void 0 : _subscriptions$key.generation) || 0) + 1) % Number.MAX_SAFE_INTEGER;
257
- const unsub = balances(balanceModule, chainConnectors, chaindataProvider, addressesByToken, (error, balances) => {
258
- if (error) return log.error(`Failed to fetch ${balanceModule.type} balances`, error);
259
- if (!balances) return;
260
-
261
- // ignore balances from old subscriptions which are still in the process of unsubscribing
262
- if (subscriptions[key].generation !== generation) return;
263
- const putBalances = Object.entries(balances.toJSON()).map(([id, balance]) => ({
264
- id,
265
- ...balance
266
- }));
267
- db.transaction("rw", db.balances, async () => await db.balances.bulkPut(putBalances));
268
- });
269
- subscriptions[key] = {
270
- unsub,
271
- refcount: 0,
272
- generation
273
- };
274
- }
275
-
276
- // bump up the refcount by 1
277
- subscriptions[key].refcount += 1;
278
- };
279
- const removeSubscription = (key, balanceModule, addressesByToken) => {
280
- // ignore dead subscriptions
281
- if (!subscriptions[key] || subscriptions[key].refcount === 0) return;
282
-
283
- // drop the refcount by one
284
- subscriptions[key].refcount -= 1;
285
-
286
- // unsubscribe if refcount is now 0 (nobody wants this subcription anymore)
287
- if (subscriptions[key].refcount < 1) {
288
- // remove subscription
289
- subscriptions[key].unsub.then(unsub => unsub());
290
- delete subscriptions[key];
291
-
292
- // set this subscription's balances in the store to status: cache
293
- db.transaction("rw", db.balances, async () => await db.balances.filter(balance => {
294
- if (balance.source !== balanceModule.type) return false;
295
- if (!Object.keys(addressesByToken).includes(balance.tokenId)) return false;
296
- if (!addressesByToken[balance.tokenId].includes(balance.address)) return false;
297
- return true;
298
- }).modify({
299
- status: "cache"
300
- }));
301
- }
302
- };
303
- const chainConnector = useChainConnector(chaindataProvider);
304
- const chainConnectorEvm = useChainConnectorEvm(chaindataProvider, options);
305
- const tokens = useTokens(chaindataProvider);
306
- useEffect(() => {
307
- if (chainConnector === null) return;
308
- if (chainConnectorEvm === null) return;
309
- if (chaindataProvider === null) return;
310
- if (addressesByToken === null) return;
311
- const unsubs = balanceModules.map(balanceModule => {
312
- const subscriptionKey = `${balanceModule.type}-${JSON.stringify(addressesByToken)}`;
313
-
314
- // filter out tokens to only include those which this module knows how to fetch balances for
315
- const moduleTokenIds = Object.values(tokens).filter(({
316
- type
317
- }) => type === balanceModule.type).map(({
318
- id
319
- }) => id);
320
- const addressesByModuleToken = Object.fromEntries(Object.entries(addressesByToken).filter(([tokenId]) => moduleTokenIds.includes(tokenId)));
321
-
322
- // add balance subscription for this module
323
- addSubscription(subscriptionKey, balanceModule, {
324
- substrate: chainConnector,
325
- evm: chainConnectorEvm
326
- }, chaindataProvider, addressesByModuleToken);
327
-
328
- // return an unsub method, to be called when this effect unmounts
329
- return () => removeSubscription(subscriptionKey, balanceModule, addressesByToken);
330
- });
331
- const unsubAll = () => unsubs.forEach(unsub => unsub());
332
- return unsubAll;
333
- }, [addressesByToken, balanceModules, chainConnector, chainConnectorEvm, chaindataProvider, tokens]);
334
- }
335
-
336
- // TODO: Allow advanced users of this library to provide their own chain connector
337
- function useChainConnector(chaindataProvider) {
338
- const [chainConnector, setChainConnector] = useState(null);
339
- useEffect(() => {
340
- if (chaindataProvider === null) return;
341
- setChainConnector(new ChainConnector(chaindataProvider));
342
- }, [chaindataProvider]);
343
- return chainConnector;
344
- }
345
- // TODO: Allow advanced users of this library to provide their own chain connector
346
- function useChainConnectorEvm(chaindataProvider, options = {}) {
347
- const [chainConnectorEvm, setChainConnectorEvm] = useState(null);
348
- useEffect(() => {
349
- if (chaindataProvider === null) return;
350
- setChainConnectorEvm(new ChainConnectorEvm(chaindataProvider, {
351
- onfinalityApiKey: options.onfinalityApiKey
352
- }));
353
- }, [chaindataProvider, options.onfinalityApiKey]);
354
- return chainConnectorEvm;
355
- }
637
+ const BalancesProvider = ({
638
+ balanceModules,
639
+ onfinalityApiKey,
640
+ withTestnets,
641
+ children
642
+ }) => /*#__PURE__*/jsx(WithTestnetsProvider, {
643
+ withTestnets: withTestnets,
644
+ children: /*#__PURE__*/jsx(ChaindataProvider, {
645
+ onfinalityApiKey: onfinalityApiKey,
646
+ children: /*#__PURE__*/jsx(ChainConnectorsProvider, {
647
+ onfinalityApiKey: onfinalityApiKey,
648
+ children: /*#__PURE__*/jsx(AllAddressesProvider, {
649
+ children: /*#__PURE__*/jsx(BalanceModulesProvider, {
650
+ balanceModules: balanceModules,
651
+ children: /*#__PURE__*/jsx(DbCacheProvider, {
652
+ children: children
653
+ })
654
+ })
655
+ })
656
+ })
657
+ })
658
+ });
356
659
 
357
- export { useBalances, useChain, useChaindata, useChains, useEvmNetwork, useEvmNetworks, useToken, useTokenRates, useTokens };
660
+ export { AllAddressesProvider, BalanceModulesProvider, BalancesProvider, ChainConnectorsProvider, ChaindataProvider, DbCacheProvider, WithTestnetsProvider, createMulticastSubscription, provideContext, useAllAddresses, useBalanceModules, useBalances, useBalancesHydrate, useChain, useChainConnectors, useChaindata, useChains, useDbCache, useDbCacheBalancesSubscription, useDbCacheSubscription, useDbCacheTokenRatesSubscription, useEvmNetwork, useEvmNetworks, useMulticastSubscription, useToken, useTokenRate, useTokenRates, useTokens, useWithTestnets };