@talismn/balances-react 0.0.0-pr557-20230216040942 → 0.0.0-pr563-20230221230003
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.
- package/CHANGELOG.md +16 -8
- package/dist/declarations/src/hooks/index.d.ts +18 -0
- package/dist/declarations/src/hooks/useAllAddresses.d.ts +4 -0
- package/dist/declarations/src/hooks/useBalanceModules.d.ts +8 -0
- package/dist/declarations/src/hooks/useBalances.d.ts +3 -6
- package/dist/declarations/src/hooks/useBalancesHydrate.d.ts +2 -0
- package/dist/declarations/src/hooks/useChainConnectors.d.ts +12 -0
- package/dist/declarations/src/hooks/useChaindata.d.ts +6 -23
- package/dist/declarations/src/hooks/useChains.d.ts +3 -0
- package/dist/declarations/src/hooks/useDbCache.d.ts +27 -0
- package/dist/declarations/src/hooks/useDbCacheSubscription.d.ts +9 -0
- package/dist/declarations/src/hooks/useEvmNetworks.d.ts +3 -0
- package/dist/declarations/src/hooks/useTokens.d.ts +3 -0
- package/dist/declarations/src/index.d.ts +1 -0
- package/dist/declarations/src/util/index.d.ts +2 -0
- package/dist/declarations/src/util/provideContext.d.ts +9 -0
- package/dist/declarations/src/util/useMulticastSubscription.d.ts +16 -0
- package/dist/talismn-balances-react.cjs.dev.js +444 -243
- package/dist/talismn-balances-react.cjs.prod.js +444 -243
- package/dist/talismn-balances-react.esm.js +429 -245
- package/package.json +9 -8
|
@@ -2,23 +2,191 @@
|
|
|
2
2
|
|
|
3
3
|
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
4
|
|
|
5
|
+
var react = require('react');
|
|
6
|
+
var jsxRuntime = require('react/jsx-runtime');
|
|
5
7
|
var balances = require('@talismn/balances');
|
|
6
|
-
var chainConnector = require('@talismn/chain-connector');
|
|
7
|
-
var chainConnectorEvm = require('@talismn/chain-connector-evm');
|
|
8
8
|
var dexieReactHooks = require('dexie-react-hooks');
|
|
9
|
-
var react = require('react');
|
|
10
9
|
var reactUse = require('react-use');
|
|
11
|
-
var anylogger = require('anylogger');
|
|
12
10
|
var chaindataProviderExtension = require('@talismn/chaindata-provider-extension');
|
|
13
11
|
var tokenRates = require('@talismn/token-rates');
|
|
12
|
+
var anylogger = require('anylogger');
|
|
13
|
+
var rxjs = require('rxjs');
|
|
14
|
+
var chainConnector = require('@talismn/chain-connector');
|
|
15
|
+
var chainConnectorEvm = require('@talismn/chain-connector-evm');
|
|
14
16
|
|
|
15
17
|
function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
|
|
16
18
|
|
|
17
19
|
var anylogger__default = /*#__PURE__*/_interopDefault(anylogger);
|
|
18
20
|
|
|
21
|
+
const provideContext = useProviderContext => {
|
|
22
|
+
// automatic typing based on our hook's return type
|
|
23
|
+
|
|
24
|
+
const Context = /*#__PURE__*/react.createContext({
|
|
25
|
+
__provideContextInteralDefaultValue: true
|
|
26
|
+
});
|
|
27
|
+
const Provider = ({
|
|
28
|
+
children,
|
|
29
|
+
...props
|
|
30
|
+
}) => {
|
|
31
|
+
const ctx = useProviderContext(props);
|
|
32
|
+
return /*#__PURE__*/jsxRuntime.jsx(Context.Provider, {
|
|
33
|
+
value: ctx,
|
|
34
|
+
children: children
|
|
35
|
+
});
|
|
36
|
+
};
|
|
37
|
+
const useProvidedContext = () => {
|
|
38
|
+
const context = react.useContext(Context);
|
|
39
|
+
if (typeof context === "object" && context && "__provideContextInteralDefaultValue" in context) throw new Error("This hook requires a provider to be present above it in the tree");
|
|
40
|
+
return context;
|
|
41
|
+
};
|
|
42
|
+
const result = [Provider, useProvidedContext];
|
|
43
|
+
return result;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const useAllAddressesProvider = () => react.useState([]);
|
|
47
|
+
const [AllAddressesProvider, useAllAddresses] = provideContext(useAllAddressesProvider);
|
|
48
|
+
|
|
49
|
+
const useBalanceModulesProvider = ({
|
|
50
|
+
balanceModules
|
|
51
|
+
}) => balanceModules;
|
|
52
|
+
const [BalanceModulesProvider, useBalanceModules] = provideContext(useBalanceModulesProvider);
|
|
53
|
+
|
|
54
|
+
function useChaindataProvider(options = {}) {
|
|
55
|
+
const [chaindata, setChaindata] = react.useState();
|
|
56
|
+
react.useEffect(() => {
|
|
57
|
+
setChaindata(new chaindataProviderExtension.ChaindataProviderExtension({
|
|
58
|
+
onfinalityApiKey: options.onfinalityApiKey
|
|
59
|
+
}));
|
|
60
|
+
}, [options.onfinalityApiKey]);
|
|
61
|
+
return chaindata;
|
|
62
|
+
}
|
|
63
|
+
const [ChaindataProvider, useChaindata] = provideContext(useChaindataProvider);
|
|
64
|
+
|
|
65
|
+
function useTokenRates(tokens) {
|
|
66
|
+
const generation = react.useRef(0);
|
|
67
|
+
const [tokenRates$1, setTokenRates] = react.useState({});
|
|
68
|
+
react.useEffect(() => {
|
|
69
|
+
if (!tokens) return;
|
|
70
|
+
if (Object.keys(tokens).length < 1) return;
|
|
71
|
+
|
|
72
|
+
// when we make a new request, we want to ignore any old requests which haven't yet completed
|
|
73
|
+
// otherwise we risk replacing the most recent data with older data
|
|
74
|
+
generation.current = (generation.current + 1) % Number.MAX_SAFE_INTEGER;
|
|
75
|
+
const thisGeneration = generation.current;
|
|
76
|
+
tokenRates.fetchTokenRates(tokens).then(tokenRates => {
|
|
77
|
+
if (thisGeneration !== generation.current) return;
|
|
78
|
+
setTokenRates(tokenRates);
|
|
79
|
+
});
|
|
80
|
+
}, [tokens]);
|
|
81
|
+
return tokenRates$1;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const filterNoTestnet = ({
|
|
85
|
+
isTestnet
|
|
86
|
+
}) => isTestnet === false;
|
|
87
|
+
const DEFAULT_VALUE = {
|
|
88
|
+
chainsWithTestnets: [],
|
|
89
|
+
chainsWithoutTestnets: [],
|
|
90
|
+
evmNetworksWithTestnets: [],
|
|
91
|
+
evmNetworksWithoutTestnets: [],
|
|
92
|
+
tokensWithTestnets: [],
|
|
93
|
+
tokensWithoutTestnets: [],
|
|
94
|
+
chainsWithTestnetsMap: {},
|
|
95
|
+
chainsWithoutTestnetsMap: {},
|
|
96
|
+
evmNetworksWithTestnetsMap: {},
|
|
97
|
+
evmNetworksWithoutTestnetsMap: {},
|
|
98
|
+
tokensWithTestnetsMap: {},
|
|
99
|
+
tokensWithoutTestnetsMap: {},
|
|
100
|
+
balances: [],
|
|
101
|
+
tokenRatesMap: {}
|
|
102
|
+
};
|
|
103
|
+
const consolidateDbCache = (chainsMap, evmNetworksMap, tokensMap, allBalances, tokenRates) => {
|
|
104
|
+
if (!chainsMap || !evmNetworksMap || !tokensMap || !allBalances
|
|
105
|
+
// TODO: Store tokenRates in a DB so that we don't have to wait for tokens before we can begin to fetch tokenRates
|
|
106
|
+
/* || !tokenRates */) return DEFAULT_VALUE;
|
|
107
|
+
|
|
108
|
+
// BEGIN: temp hack to indicate that
|
|
109
|
+
// - EVM GLMR is a mirror of substrate GLMR
|
|
110
|
+
// - EVM MOVR is a mirror of substrate MOVR
|
|
111
|
+
// - EVM DEV is a mirror of substrate DEV
|
|
112
|
+
// - EVM ACA is a mirror of substrate ACA
|
|
113
|
+
const mirrorTokenIds = {
|
|
114
|
+
"1284-evm-native-glmr": "moonbeam-substrate-native-glmr",
|
|
115
|
+
"1285-evm-native-movr": "moonriver-substrate-native-movr",
|
|
116
|
+
"1287-evm-native-dev": "moonbase-alpha-testnet-substrate-native-dev",
|
|
117
|
+
"787-evm-native-aca": "acala-substrate-native-aca"
|
|
118
|
+
};
|
|
119
|
+
Object.entries(mirrorTokenIds).filter(([mirrorToken]) => tokensMap[mirrorToken]).forEach(([mirrorToken, mirrorOf]) => tokensMap[mirrorToken].mirrorOf = mirrorOf);
|
|
120
|
+
// END: temp hack
|
|
121
|
+
|
|
122
|
+
const chainsWithTestnets = Object.values(chainsMap);
|
|
123
|
+
const chainsWithoutTestnets = chainsWithTestnets.filter(filterNoTestnet);
|
|
124
|
+
const chainsWithoutTestnetsMap = Object.fromEntries(chainsWithoutTestnets.map(network => [network.id, network]));
|
|
125
|
+
const evmNetworksWithTestnets = Object.values(evmNetworksMap);
|
|
126
|
+
const evmNetworksWithoutTestnets = evmNetworksWithTestnets.filter(filterNoTestnet);
|
|
127
|
+
const evmNetworksWithoutTestnetsMap = Object.fromEntries(evmNetworksWithoutTestnets.map(network => [network.id, network]));
|
|
128
|
+
|
|
129
|
+
// ensure that we have corresponding network for each token
|
|
130
|
+
const tokensWithTestnets = Object.values(tokensMap).filter(token => token.chain && chainsMap[token.chain.id] || token.evmNetwork && evmNetworksMap[token.evmNetwork.id]);
|
|
131
|
+
const tokensWithoutTestnets = tokensWithTestnets.filter(filterNoTestnet).filter(token => token.chain && chainsWithoutTestnetsMap[token.chain.id] || token.evmNetwork && evmNetworksWithoutTestnetsMap[token.evmNetwork.id]);
|
|
132
|
+
const tokensWithTestnetsMap = Object.fromEntries(tokensWithTestnets.map(token => [token.id, token]));
|
|
133
|
+
const tokensWithoutTestnetsMap = Object.fromEntries(tokensWithoutTestnets.map(token => [token.id, token]));
|
|
134
|
+
|
|
135
|
+
// return only balances for which we have a token
|
|
136
|
+
const balances = allBalances.filter(b => tokensWithTestnetsMap[b.tokenId]);
|
|
137
|
+
return {
|
|
138
|
+
chainsWithTestnets,
|
|
139
|
+
chainsWithoutTestnets,
|
|
140
|
+
evmNetworksWithTestnets,
|
|
141
|
+
evmNetworksWithoutTestnets,
|
|
142
|
+
tokensWithTestnets,
|
|
143
|
+
tokensWithoutTestnets,
|
|
144
|
+
chainsWithTestnetsMap: chainsMap,
|
|
145
|
+
chainsWithoutTestnetsMap,
|
|
146
|
+
evmNetworksWithTestnetsMap: evmNetworksMap,
|
|
147
|
+
evmNetworksWithoutTestnetsMap,
|
|
148
|
+
tokensWithTestnetsMap,
|
|
149
|
+
tokensWithoutTestnetsMap,
|
|
150
|
+
balances,
|
|
151
|
+
tokenRatesMap: tokenRates ?? {}
|
|
152
|
+
};
|
|
153
|
+
};
|
|
154
|
+
const useDbCacheProvider = ({
|
|
155
|
+
useTestnets = false
|
|
156
|
+
}) => {
|
|
157
|
+
const chaindataProvider = useChaindata();
|
|
158
|
+
const chainList = dexieReactHooks.useLiveQuery(() => chaindataProvider?.chains(), [chaindataProvider]);
|
|
159
|
+
const evmNetworkList = dexieReactHooks.useLiveQuery(() => chaindataProvider?.evmNetworks(), [chaindataProvider]);
|
|
160
|
+
const tokenList = dexieReactHooks.useLiveQuery(() => chaindataProvider?.tokens(), [chaindataProvider]);
|
|
161
|
+
const rawBalances = dexieReactHooks.useLiveQuery(() => balances.db.balances.toArray(), []);
|
|
162
|
+
|
|
163
|
+
// TODO: Store in a DB so that we don't have to wait for tokens before we can begin to fetch tokenRates
|
|
164
|
+
const tokenRates = useTokenRates();
|
|
165
|
+
const [dbData, setDbData] = react.useState(DEFAULT_VALUE);
|
|
166
|
+
|
|
167
|
+
// debounce every 500ms to prevent hammering UI with updates
|
|
168
|
+
reactUse.useDebounce(() => {
|
|
169
|
+
setDbData(consolidateDbCache(chainList, evmNetworkList, tokenList, rawBalances, tokenRates));
|
|
170
|
+
}, 500, [chainList, evmNetworkList, tokenList, rawBalances, tokenRates, useTestnets]);
|
|
171
|
+
const refInitialized = react.useRef(false);
|
|
172
|
+
|
|
173
|
+
// force an update as soon as all datasources are fetched, so UI can display data ASAP
|
|
174
|
+
react.useEffect(() => {
|
|
175
|
+
if (!refInitialized.current && chainList && evmNetworkList && tokenList && rawBalances
|
|
176
|
+
// TODO: Store tokenRates in a DB so that we don't have to wait for tokens before we can begin to fetch tokenRates
|
|
177
|
+
// && tokenRates
|
|
178
|
+
) {
|
|
179
|
+
setDbData(consolidateDbCache(chainList, evmNetworkList, tokenList, rawBalances, tokenRates));
|
|
180
|
+
refInitialized.current = true;
|
|
181
|
+
}
|
|
182
|
+
}, [chainList, evmNetworkList, rawBalances, tokenList, tokenRates, useTestnets]);
|
|
183
|
+
return dbData;
|
|
184
|
+
};
|
|
185
|
+
const [DbCacheProvider, useDbCache] = provideContext(useDbCacheProvider);
|
|
186
|
+
|
|
19
187
|
var packageJson = {
|
|
20
188
|
name: "@talismn/balances-react",
|
|
21
|
-
version: "0.0.0-
|
|
189
|
+
version: "0.0.0-pr563-20230221230003",
|
|
22
190
|
author: "Talisman",
|
|
23
191
|
homepage: "https://talisman.xyz",
|
|
24
192
|
license: "UNLICENSED",
|
|
@@ -53,7 +221,8 @@ var packageJson = {
|
|
|
53
221
|
anylogger: "^1.0.11",
|
|
54
222
|
dexie: "^3.2.2",
|
|
55
223
|
"dexie-react-hooks": "^1.1.1",
|
|
56
|
-
"react-use": "^17.4.0"
|
|
224
|
+
"react-use": "^17.4.0",
|
|
225
|
+
rxjs: "^7.8.0"
|
|
57
226
|
},
|
|
58
227
|
devDependencies: {
|
|
59
228
|
"@talismn/eslint-config": "workspace:^",
|
|
@@ -80,139 +249,259 @@ var packageJson = {
|
|
|
80
249
|
|
|
81
250
|
var log = anylogger__default["default"](packageJson.name);
|
|
82
251
|
|
|
83
|
-
|
|
84
|
-
function
|
|
85
|
-
|
|
252
|
+
/**
|
|
253
|
+
* Creates a subscription function that can be used to subscribe to a multicast observable created from an upstream source.
|
|
254
|
+
*
|
|
255
|
+
* An example of when this is useful is when we want to subscribe to some data from multiple components, but we only want
|
|
256
|
+
* to actively keep that data hydrated when at least one component is subscribed to it.
|
|
257
|
+
*
|
|
258
|
+
* When the first component subscribes, the `upstream` function will be called. It should then set up a subscription and return a teardown function.
|
|
259
|
+
* When subsequent components subscribe, they will be added to the existing subscription.
|
|
260
|
+
* When the last component unsubscribes, the teardown function returned from the `upstream` function will be called.
|
|
261
|
+
*
|
|
262
|
+
* @param upstream A function that takes a "next" callback function as an argument, and returns either an unsubscribe function or void.
|
|
263
|
+
* @returns A subscription function that can be used to subscribe to the multicast observable.
|
|
264
|
+
*/
|
|
265
|
+
const useMulticastSubscription = upstream => {
|
|
266
|
+
const subscribe = react.useMemo(() => createMulticastSubscription(upstream), [upstream]);
|
|
267
|
+
return subscribe;
|
|
268
|
+
};
|
|
269
|
+
const createMulticastSubscription = upstream => {
|
|
270
|
+
// Create an upstream observable using the provided function.
|
|
271
|
+
const upstreamObservable = new rxjs.Observable(subscriber => {
|
|
272
|
+
const unsubscribe = upstream(val => subscriber.next(val));
|
|
273
|
+
return () => {
|
|
274
|
+
typeof unsubscribe === "function" && unsubscribe();
|
|
275
|
+
};
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
// Create a multicast observable from the upstream observable, using the shareReplay operator.
|
|
279
|
+
const multicastObservable = rxjs.defer(() => upstreamObservable).pipe(rxjs.shareReplay({
|
|
280
|
+
bufferSize: 1,
|
|
281
|
+
refCount: true
|
|
282
|
+
}));
|
|
283
|
+
|
|
284
|
+
// Create a subscription function that subscribes to the multicast observable and returns an unsubscribe function.
|
|
285
|
+
const subscribe = callback => {
|
|
286
|
+
const subscription = multicastObservable.subscribe(callback);
|
|
287
|
+
const unsubscribe = () => subscription.unsubscribe();
|
|
288
|
+
return unsubscribe;
|
|
289
|
+
};
|
|
290
|
+
return subscribe;
|
|
291
|
+
};
|
|
292
|
+
|
|
293
|
+
function useChainConnectorsProvider(options) {
|
|
294
|
+
// chaindata dependency
|
|
295
|
+
const chaindata = useChaindata();
|
|
86
296
|
|
|
87
|
-
//
|
|
88
|
-
const [
|
|
297
|
+
// substrate connector
|
|
298
|
+
const [substrate, setSubstrate] = react.useState();
|
|
89
299
|
react.useEffect(() => {
|
|
90
|
-
|
|
300
|
+
if (!chaindata) return;
|
|
301
|
+
setSubstrate(new chainConnector.ChainConnector(chaindata));
|
|
302
|
+
}, [chaindata]);
|
|
303
|
+
|
|
304
|
+
// evm connector
|
|
305
|
+
const [evm, setEvm] = react.useState();
|
|
306
|
+
react.useEffect(() => {
|
|
307
|
+
if (!chaindata) return;
|
|
308
|
+
setEvm(new chainConnectorEvm.ChainConnectorEvm(chaindata, {
|
|
91
309
|
onfinalityApiKey: options.onfinalityApiKey
|
|
92
|
-
});
|
|
93
|
-
|
|
94
|
-
|
|
310
|
+
}));
|
|
311
|
+
}, [chaindata, options.onfinalityApiKey]);
|
|
312
|
+
return react.useMemo(() => ({
|
|
313
|
+
substrate,
|
|
314
|
+
evm
|
|
315
|
+
}), [substrate, evm]);
|
|
316
|
+
}
|
|
317
|
+
const [ChainConnectorsProvider, useChainConnectors] = provideContext(useChainConnectorsProvider);
|
|
318
|
+
|
|
319
|
+
const useSubscriptionsProvider = () => [useSubscribeChaindataHydrate("chains"), useSubscribeChaindataHydrate("evmNetworks"), useSubscribeChaindataHydrate("tokens"), useSubscribeBalances()];
|
|
320
|
+
const [SubscriptionsProvider, useSubscriptions] = provideContext(useSubscriptionsProvider);
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* This hook is responsible for fetching the data used for balances and inserting it into the db.
|
|
324
|
+
*/
|
|
325
|
+
const useDbCacheSubscription = subscribeTo => {
|
|
326
|
+
const [subscribeHydrateChains, subscribeHydrateEvmNetworks, subscribeHydrateTokens, subscribeBalances] = useSubscriptions();
|
|
327
|
+
react.useEffect(() => {
|
|
328
|
+
switch (subscribeTo) {
|
|
329
|
+
case "chains":
|
|
330
|
+
return subscribeHydrateChains();
|
|
331
|
+
case "evmNetworks":
|
|
332
|
+
return subscribeHydrateEvmNetworks();
|
|
333
|
+
case "tokens":
|
|
334
|
+
return subscribeHydrateTokens();
|
|
335
|
+
case "balances":
|
|
336
|
+
return subscribeBalances();
|
|
337
|
+
}
|
|
338
|
+
}, [subscribeBalances, subscribeHydrateChains, subscribeHydrateEvmNetworks, subscribeHydrateTokens, subscribeTo]);
|
|
339
|
+
};
|
|
340
|
+
function useSubscribeChaindataHydrate(type) {
|
|
341
|
+
const chaindata =
|
|
342
|
+
// cheeky hack to give us access to the hydrate methods
|
|
343
|
+
useChaindata();
|
|
344
|
+
const createSubscription = react.useCallback(() => {
|
|
345
|
+
if (!chaindata) return;
|
|
346
|
+
let active = true;
|
|
347
|
+
const interval = 300_000; // 300_000ms = 300s = 5 minutes
|
|
348
|
+
|
|
95
349
|
const hydrate = async () => {
|
|
96
|
-
if (!
|
|
350
|
+
if (!active) return;
|
|
97
351
|
try {
|
|
98
|
-
|
|
99
|
-
if (
|
|
100
|
-
|
|
352
|
+
if (type === "chains") await chaindata.hydrateChains();
|
|
353
|
+
if (type === "evmNetworks") await chaindata.hydrateEvmNetworks();
|
|
354
|
+
if (type === "tokens") await chaindata.hydrateTokens();
|
|
355
|
+
setTimeout(hydrate, interval);
|
|
101
356
|
} catch (error) {
|
|
102
357
|
const retryTimeout = 5_000; // 5_000ms = 5 seconds
|
|
103
358
|
log.error(`Failed to fetch chaindata, retrying in ${Math.round(retryTimeout / 1000)} seconds`, error);
|
|
104
359
|
setTimeout(hydrate, retryTimeout);
|
|
105
360
|
}
|
|
106
361
|
};
|
|
107
|
-
setChaindataProvider(chaindataProvider);
|
|
108
362
|
hydrate();
|
|
109
363
|
return () => {
|
|
110
|
-
|
|
364
|
+
active = false;
|
|
111
365
|
};
|
|
112
|
-
}, [
|
|
113
|
-
|
|
114
|
-
return
|
|
366
|
+
}, [chaindata, type]);
|
|
367
|
+
const subscribe = useMulticastSubscription(createSubscription);
|
|
368
|
+
return subscribe;
|
|
115
369
|
}
|
|
116
|
-
function
|
|
117
|
-
const
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
370
|
+
function useSubscribeBalances() {
|
|
371
|
+
const balanceModules = useBalanceModules();
|
|
372
|
+
const chaindataProvider = useChaindata();
|
|
373
|
+
const chainConnectors = useChainConnectors();
|
|
374
|
+
const [allAddresses] = useAllAddresses();
|
|
375
|
+
const tokens = dexieReactHooks.useLiveQuery(() => chaindataProvider?.tokens(), [chaindataProvider]);
|
|
376
|
+
const tokenIds = react.useMemo(() => Object.values(tokens ?? {}).map(({
|
|
377
|
+
id
|
|
378
|
+
}) => id), [tokens]);
|
|
379
|
+
const addressesByToken = react.useMemo(() => Object.fromEntries(tokenIds.map(tokenId => [tokenId, allAddresses])), [allAddresses, tokenIds]);
|
|
380
|
+
const generationRef = react.useRef(0);
|
|
381
|
+
const createSubscription = react.useCallback(() => {
|
|
382
|
+
if (!chainConnectors.substrate) return;
|
|
383
|
+
if (!chainConnectors.evm) return;
|
|
384
|
+
if (!chaindataProvider) return;
|
|
385
|
+
const generation = (generationRef.current + 1) % Number.MAX_SAFE_INTEGER;
|
|
386
|
+
generationRef.current = generation;
|
|
387
|
+
const unsubs = balanceModules.map(balanceModule => {
|
|
388
|
+
// filter out tokens to only include those which this module knows how to fetch balances for
|
|
389
|
+
const moduleTokenIds = Object.values(tokens ?? {}).filter(({
|
|
390
|
+
type
|
|
391
|
+
}) => type === balanceModule.type).map(({
|
|
392
|
+
id
|
|
393
|
+
}) => id);
|
|
394
|
+
const addressesByModuleToken = Object.fromEntries(Object.entries(addressesByToken).filter(([tokenId]) => moduleTokenIds.includes(tokenId)));
|
|
395
|
+
const subscribe = createMulticastSubscription(next => {
|
|
396
|
+
const unsub = balances.balances(balanceModule, chainConnectors, chaindataProvider, addressesByModuleToken, (error, balances) => {
|
|
397
|
+
// log errors
|
|
398
|
+
if (error) return log.error(`Failed to fetch ${balanceModule.type} balances`, error);
|
|
399
|
+
// ignore empty balance responses
|
|
400
|
+
if (!balances) return;
|
|
401
|
+
// ignore balances from old subscriptions which are still in the process of unsubscribing
|
|
402
|
+
if (generationRef.current !== generation) return;
|
|
403
|
+
next(balances);
|
|
404
|
+
});
|
|
405
|
+
return () => {
|
|
406
|
+
// unsubscribe from upstream
|
|
407
|
+
unsub.then(unsubscribe => unsubscribe());
|
|
408
|
+
|
|
409
|
+
// set this subscription's balances in the store to status: cache
|
|
410
|
+
balances.db.transaction("rw", balances.db.balances, async () => await balances.db.balances.filter(balance => {
|
|
411
|
+
if (balance.source !== balanceModule.type) return false;
|
|
412
|
+
if (!Object.keys(addressesByModuleToken).includes(balance.tokenId)) return false;
|
|
413
|
+
if (!addressesByModuleToken[balance.tokenId].includes(balance.address)) return false;
|
|
414
|
+
return true;
|
|
415
|
+
}).modify({
|
|
416
|
+
status: "cache"
|
|
417
|
+
}));
|
|
418
|
+
};
|
|
419
|
+
});
|
|
420
|
+
const unsubscribe = subscribe(balances$1 => {
|
|
421
|
+
const putBalances = Object.entries(balances$1.toJSON()).map(([id, balance]) => ({
|
|
422
|
+
id,
|
|
423
|
+
...balance
|
|
424
|
+
}));
|
|
425
|
+
balances.db.transaction("rw", balances.db.balances, async () => await balances.db.balances.bulkPut(putBalances));
|
|
426
|
+
});
|
|
427
|
+
return unsubscribe;
|
|
124
428
|
});
|
|
125
|
-
|
|
126
|
-
|
|
429
|
+
const unsubscribeAll = () => unsubs.forEach(unsub => unsub());
|
|
430
|
+
return unsubscribeAll;
|
|
431
|
+
}, [addressesByToken, balanceModules, chainConnectors, chaindataProvider, tokens]);
|
|
432
|
+
const subscribe = useMulticastSubscription(createSubscription);
|
|
433
|
+
return subscribe;
|
|
127
434
|
}
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
435
|
+
|
|
436
|
+
function useChains(withTestnets) {
|
|
437
|
+
// keep db data up to date
|
|
438
|
+
useDbCacheSubscription("chains");
|
|
439
|
+
const {
|
|
440
|
+
chainsWithTestnetsMap,
|
|
441
|
+
chainsWithoutTestnetsMap
|
|
442
|
+
} = useDbCache();
|
|
443
|
+
return withTestnets ? chainsWithTestnetsMap : chainsWithoutTestnetsMap;
|
|
136
444
|
}
|
|
137
|
-
function
|
|
138
|
-
const
|
|
139
|
-
|
|
140
|
-
if (!chaindata) return;
|
|
141
|
-
const thisGeneration = chaindata.generation;
|
|
142
|
-
chaindata.evmNetworks().then(evmNetworks => {
|
|
143
|
-
if (thisGeneration !== chaindata.generation) return;
|
|
144
|
-
setEvmNetworks(evmNetworks);
|
|
145
|
-
});
|
|
146
|
-
}, [chaindata, chaindata === null || chaindata === void 0 ? void 0 : chaindata.generation]);
|
|
147
|
-
return evmNetworks || {};
|
|
445
|
+
function useChain(chainId, withTestnets) {
|
|
446
|
+
const chains = useChains(withTestnets);
|
|
447
|
+
return chainId ? chains[chainId] : undefined;
|
|
148
448
|
}
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
449
|
+
|
|
450
|
+
function useEvmNetworks(withTestnets) {
|
|
451
|
+
// keep db data up to date
|
|
452
|
+
useDbCacheSubscription("evmNetworks");
|
|
453
|
+
const {
|
|
454
|
+
evmNetworksWithTestnetsMap,
|
|
455
|
+
evmNetworksWithoutTestnetsMap
|
|
456
|
+
} = useDbCache();
|
|
457
|
+
return withTestnets ? evmNetworksWithTestnetsMap : evmNetworksWithoutTestnetsMap;
|
|
157
458
|
}
|
|
158
|
-
function
|
|
159
|
-
const
|
|
160
|
-
|
|
161
|
-
if (!chaindata) return;
|
|
162
|
-
const thisGeneration = chaindata.generation;
|
|
163
|
-
chaindata.tokens().then(tokens => {
|
|
164
|
-
if (thisGeneration !== chaindata.generation) return;
|
|
165
|
-
setTokens(tokens);
|
|
166
|
-
});
|
|
167
|
-
}, [chaindata, chaindata === null || chaindata === void 0 ? void 0 : chaindata.generation]);
|
|
168
|
-
return tokens || {};
|
|
459
|
+
function useEvmNetwork(evmNetworkId, withTestnets) {
|
|
460
|
+
const evmNetworks = useEvmNetworks(withTestnets);
|
|
461
|
+
return evmNetworkId ? evmNetworks[evmNetworkId] : undefined;
|
|
169
462
|
}
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
463
|
+
|
|
464
|
+
function useTokens(withTestnets) {
|
|
465
|
+
// keep db data up to date
|
|
466
|
+
useDbCacheSubscription("tokens");
|
|
467
|
+
const {
|
|
468
|
+
tokensWithTestnetsMap,
|
|
469
|
+
tokensWithoutTestnetsMap
|
|
470
|
+
} = useDbCache();
|
|
471
|
+
return withTestnets ? tokensWithTestnetsMap : tokensWithoutTestnetsMap;
|
|
472
|
+
}
|
|
473
|
+
function useToken(tokenId, withTestnets) {
|
|
474
|
+
const tokens = useTokens(withTestnets);
|
|
475
|
+
return tokenId ? tokens[tokenId] : undefined;
|
|
178
476
|
}
|
|
179
477
|
|
|
180
|
-
|
|
181
|
-
const
|
|
182
|
-
const
|
|
183
|
-
|
|
184
|
-
if (!tokens) return;
|
|
185
|
-
if (Object.keys(tokens).length < 1) return;
|
|
478
|
+
const useBalancesHydrate = withTestnets => {
|
|
479
|
+
const chains = useChains(withTestnets);
|
|
480
|
+
const evmNetworks = useEvmNetworks(withTestnets);
|
|
481
|
+
const tokens = useTokens(withTestnets);
|
|
186
482
|
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
}
|
|
483
|
+
// TODO: Store in a DB so that we don't have to wait for tokens before we can begin to fetch tokenRates
|
|
484
|
+
// useDbCacheSubscription("tokenRates")
|
|
485
|
+
const {
|
|
486
|
+
tokenRatesMap: tokenRates
|
|
487
|
+
} = useDbCache();
|
|
488
|
+
return react.useMemo(() => ({
|
|
489
|
+
chains,
|
|
490
|
+
evmNetworks,
|
|
491
|
+
tokens,
|
|
492
|
+
tokenRates
|
|
493
|
+
}), [chains, evmNetworks, tokens, tokenRates]);
|
|
494
|
+
};
|
|
198
495
|
|
|
199
|
-
|
|
200
|
-
//
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
// TODO: Make this array of BalanceModules more type-safe
|
|
209
|
-
balanceModules, chaindataProvider, addressesByToken, options = {}) {
|
|
210
|
-
useBalancesSubscriptions(balanceModules, chaindataProvider, addressesByToken, options);
|
|
211
|
-
const chains = useChains(chaindataProvider);
|
|
212
|
-
const evmNetworks = useEvmNetworks(chaindataProvider);
|
|
213
|
-
const tokens = useTokens(chaindataProvider);
|
|
214
|
-
const tokenRates = useTokenRates(tokens);
|
|
215
|
-
const balances$1 = dexieReactHooks.useLiveQuery(async () => new balances.Balances(await balances.db.balances.filter(balance => {
|
|
496
|
+
function useBalances(addressesByToken) {
|
|
497
|
+
// keep db data up to date
|
|
498
|
+
useDbCacheSubscription("balances");
|
|
499
|
+
const balanceModules = useBalanceModules();
|
|
500
|
+
const {
|
|
501
|
+
balances: balances$1
|
|
502
|
+
} = useDbCache();
|
|
503
|
+
const hydrate = useBalancesHydrate();
|
|
504
|
+
return react.useMemo(() => new balances.Balances(balances$1.filter(balance => {
|
|
216
505
|
// check that this balance is included in our queried balance modules
|
|
217
506
|
if (!balanceModules.map(({
|
|
218
507
|
type
|
|
@@ -229,145 +518,57 @@ balanceModules, chaindataProvider, addressesByToken, options = {}) {
|
|
|
229
518
|
|
|
230
519
|
// keep this balance
|
|
231
520
|
return true;
|
|
232
|
-
})
|
|
521
|
+
}),
|
|
233
522
|
// hydrate balance chains, evmNetworks, tokens and tokenRates
|
|
234
|
-
|
|
235
|
-
chains,
|
|
236
|
-
evmNetworks,
|
|
237
|
-
tokens,
|
|
238
|
-
tokenRates
|
|
239
|
-
}), [balanceModules, addressesByToken, chains, evmNetworks, tokens, tokenRates]);
|
|
240
|
-
|
|
241
|
-
// debounce every 100ms to prevent hammering UI with updates
|
|
242
|
-
const [debouncedBalances, setDebouncedBalances] = react.useState(balances$1);
|
|
243
|
-
reactUse.useDebounce(() => balances$1 && setDebouncedBalances(balances$1), 100, [balances$1]);
|
|
244
|
-
return debouncedBalances;
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
// TODO: Turn into react context
|
|
248
|
-
const subscriptions = {};
|
|
249
|
-
|
|
250
|
-
// This hook is responsible for allowing us to call useBalances
|
|
251
|
-
// from multiple components, without setting up unnecessary
|
|
252
|
-
// balance subscriptions
|
|
253
|
-
function useBalancesSubscriptions(
|
|
254
|
-
// TODO: Make this array of BalanceModules more type-safe
|
|
255
|
-
balanceModules, chaindataProvider, addressesByToken, options = {}) {
|
|
256
|
-
// const subscriptions = useRef<
|
|
257
|
-
// Record<string, { unsub: Promise<() => void>; refcount: number; generation: number }>
|
|
258
|
-
// >({})
|
|
259
|
-
|
|
260
|
-
const addSubscription = (key, balanceModule, chainConnectors, chaindataProvider, addressesByToken) => {
|
|
261
|
-
// create subscription if it doesn't already exist
|
|
262
|
-
if (!subscriptions[key] || subscriptions[key].refcount === 0) {
|
|
263
|
-
var _subscriptions$key;
|
|
264
|
-
const generation = ((((_subscriptions$key = subscriptions[key]) === null || _subscriptions$key === void 0 ? void 0 : _subscriptions$key.generation) || 0) + 1) % Number.MAX_SAFE_INTEGER;
|
|
265
|
-
const unsub = balances.balances(balanceModule, chainConnectors, chaindataProvider, addressesByToken, (error, balances$1) => {
|
|
266
|
-
if (error) return log.error(`Failed to fetch ${balanceModule.type} balances`, error);
|
|
267
|
-
if (!balances$1) return;
|
|
268
|
-
|
|
269
|
-
// ignore balances from old subscriptions which are still in the process of unsubscribing
|
|
270
|
-
if (subscriptions[key].generation !== generation) return;
|
|
271
|
-
const putBalances = Object.entries(balances$1.toJSON()).map(([id, balance]) => ({
|
|
272
|
-
id,
|
|
273
|
-
...balance
|
|
274
|
-
}));
|
|
275
|
-
balances.db.transaction("rw", balances.db.balances, async () => await balances.db.balances.bulkPut(putBalances));
|
|
276
|
-
});
|
|
277
|
-
subscriptions[key] = {
|
|
278
|
-
unsub,
|
|
279
|
-
refcount: 0,
|
|
280
|
-
generation
|
|
281
|
-
};
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
// bump up the refcount by 1
|
|
285
|
-
subscriptions[key].refcount += 1;
|
|
286
|
-
};
|
|
287
|
-
const removeSubscription = (key, balanceModule, addressesByToken) => {
|
|
288
|
-
// ignore dead subscriptions
|
|
289
|
-
if (!subscriptions[key] || subscriptions[key].refcount === 0) return;
|
|
290
|
-
|
|
291
|
-
// drop the refcount by one
|
|
292
|
-
subscriptions[key].refcount -= 1;
|
|
293
|
-
|
|
294
|
-
// unsubscribe if refcount is now 0 (nobody wants this subcription anymore)
|
|
295
|
-
if (subscriptions[key].refcount < 1) {
|
|
296
|
-
// remove subscription
|
|
297
|
-
subscriptions[key].unsub.then(unsub => unsub());
|
|
298
|
-
delete subscriptions[key];
|
|
299
|
-
|
|
300
|
-
// set this subscription's balances in the store to status: cache
|
|
301
|
-
balances.db.transaction("rw", balances.db.balances, async () => await balances.db.balances.filter(balance => {
|
|
302
|
-
if (balance.source !== balanceModule.type) return false;
|
|
303
|
-
if (!Object.keys(addressesByToken).includes(balance.tokenId)) return false;
|
|
304
|
-
if (!addressesByToken[balance.tokenId].includes(balance.address)) return false;
|
|
305
|
-
return true;
|
|
306
|
-
}).modify({
|
|
307
|
-
status: "cache"
|
|
308
|
-
}));
|
|
309
|
-
}
|
|
310
|
-
};
|
|
311
|
-
const chainConnector = useChainConnector(chaindataProvider);
|
|
312
|
-
const chainConnectorEvm = useChainConnectorEvm(chaindataProvider, options);
|
|
313
|
-
const tokens = useTokens(chaindataProvider);
|
|
314
|
-
react.useEffect(() => {
|
|
315
|
-
if (chainConnector === null) return;
|
|
316
|
-
if (chainConnectorEvm === null) return;
|
|
317
|
-
if (chaindataProvider === null) return;
|
|
318
|
-
if (addressesByToken === null) return;
|
|
319
|
-
const unsubs = balanceModules.map(balanceModule => {
|
|
320
|
-
const subscriptionKey = `${balanceModule.type}-${JSON.stringify(addressesByToken)}`;
|
|
321
|
-
|
|
322
|
-
// filter out tokens to only include those which this module knows how to fetch balances for
|
|
323
|
-
const moduleTokenIds = Object.values(tokens).filter(({
|
|
324
|
-
type
|
|
325
|
-
}) => type === balanceModule.type).map(({
|
|
326
|
-
id
|
|
327
|
-
}) => id);
|
|
328
|
-
const addressesByModuleToken = Object.fromEntries(Object.entries(addressesByToken).filter(([tokenId]) => moduleTokenIds.includes(tokenId)));
|
|
329
|
-
|
|
330
|
-
// add balance subscription for this module
|
|
331
|
-
addSubscription(subscriptionKey, balanceModule, {
|
|
332
|
-
substrate: chainConnector,
|
|
333
|
-
evm: chainConnectorEvm
|
|
334
|
-
}, chaindataProvider, addressesByModuleToken);
|
|
335
|
-
|
|
336
|
-
// return an unsub method, to be called when this effect unmounts
|
|
337
|
-
return () => removeSubscription(subscriptionKey, balanceModule, addressesByToken);
|
|
338
|
-
});
|
|
339
|
-
const unsubAll = () => unsubs.forEach(unsub => unsub());
|
|
340
|
-
return unsubAll;
|
|
341
|
-
}, [addressesByToken, balanceModules, chainConnector, chainConnectorEvm, chaindataProvider, tokens]);
|
|
523
|
+
hydrate), [balances$1, hydrate, balanceModules, addressesByToken]);
|
|
342
524
|
}
|
|
343
525
|
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
}
|
|
526
|
+
const BalancesProvider = ({
|
|
527
|
+
balanceModules,
|
|
528
|
+
onfinalityApiKey,
|
|
529
|
+
useTestnets,
|
|
530
|
+
children
|
|
531
|
+
}) => /*#__PURE__*/jsxRuntime.jsx(ChaindataProvider, {
|
|
532
|
+
onfinalityApiKey: onfinalityApiKey,
|
|
533
|
+
children: /*#__PURE__*/jsxRuntime.jsx(ChainConnectorsProvider, {
|
|
534
|
+
onfinalityApiKey: onfinalityApiKey,
|
|
535
|
+
children: /*#__PURE__*/jsxRuntime.jsx(AllAddressesProvider, {
|
|
536
|
+
children: /*#__PURE__*/jsxRuntime.jsx(BalanceModulesProvider, {
|
|
537
|
+
balanceModules: balanceModules,
|
|
538
|
+
children: /*#__PURE__*/jsxRuntime.jsx(DbCacheProvider, {
|
|
539
|
+
useTestnets: useTestnets,
|
|
540
|
+
children: /*#__PURE__*/jsxRuntime.jsx(SubscriptionsProvider, {
|
|
541
|
+
children: children
|
|
542
|
+
})
|
|
543
|
+
})
|
|
544
|
+
})
|
|
545
|
+
})
|
|
546
|
+
})
|
|
547
|
+
});
|
|
364
548
|
|
|
549
|
+
exports.AllAddressesProvider = AllAddressesProvider;
|
|
550
|
+
exports.BalanceModulesProvider = BalanceModulesProvider;
|
|
551
|
+
exports.BalancesProvider = BalancesProvider;
|
|
552
|
+
exports.ChainConnectorsProvider = ChainConnectorsProvider;
|
|
553
|
+
exports.ChaindataProvider = ChaindataProvider;
|
|
554
|
+
exports.DbCacheProvider = DbCacheProvider;
|
|
555
|
+
exports.SubscriptionsProvider = SubscriptionsProvider;
|
|
556
|
+
exports.createMulticastSubscription = createMulticastSubscription;
|
|
557
|
+
exports.provideContext = provideContext;
|
|
558
|
+
exports.useAllAddresses = useAllAddresses;
|
|
559
|
+
exports.useBalanceModules = useBalanceModules;
|
|
365
560
|
exports.useBalances = useBalances;
|
|
561
|
+
exports.useBalancesHydrate = useBalancesHydrate;
|
|
366
562
|
exports.useChain = useChain;
|
|
563
|
+
exports.useChainConnectors = useChainConnectors;
|
|
367
564
|
exports.useChaindata = useChaindata;
|
|
368
565
|
exports.useChains = useChains;
|
|
566
|
+
exports.useDbCache = useDbCache;
|
|
567
|
+
exports.useDbCacheSubscription = useDbCacheSubscription;
|
|
369
568
|
exports.useEvmNetwork = useEvmNetwork;
|
|
370
569
|
exports.useEvmNetworks = useEvmNetworks;
|
|
570
|
+
exports.useMulticastSubscription = useMulticastSubscription;
|
|
571
|
+
exports.useSubscriptions = useSubscriptions;
|
|
371
572
|
exports.useToken = useToken;
|
|
372
573
|
exports.useTokenRates = useTokenRates;
|
|
373
574
|
exports.useTokens = useTokens;
|