@talismn/balances-react 0.0.0-pr2079-20250710050859 → 0.0.0-pr2091-20250715012835
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/dist/declarations/src/atoms/balances.d.ts +1 -5
- package/dist/declarations/src/atoms/balancesProvider.d.ts +2 -0
- package/dist/declarations/src/atoms/chaindata.d.ts +427 -1450
- package/dist/declarations/src/atoms/config.d.ts +0 -4
- package/dist/declarations/src/hooks/useBalances.d.ts +1 -2
- package/dist/declarations/src/hooks/useChaindata.d.ts +633 -709
- package/dist/declarations/src/index.d.ts +2 -8
- package/dist/talismn-balances-react.cjs.dev.js +103 -351
- package/dist/talismn-balances-react.cjs.prod.js +103 -351
- package/dist/talismn-balances-react.esm.js +105 -341
- package/package.json +11 -11
- package/dist/declarations/src/atoms/balanceModules.d.ts +0 -2
- package/dist/declarations/src/util/balancesPersist.d.ts +0 -10
|
@@ -1,12 +1,10 @@
|
|
|
1
|
-
import { AnyBalanceModule, Hydrate } from "@talismn/balances";
|
|
2
1
|
import { ReactNode } from "react";
|
|
3
|
-
export { evmErc20TokenId, evmNativeTokenId,
|
|
2
|
+
export { evmErc20TokenId, evmNativeTokenId, subAssetTokenId, subNativeTokenId, subPsp22TokenId, subTokensTokenId, } from "@talismn/chaindata-provider";
|
|
4
3
|
export * from "./hooks/useBalances";
|
|
5
4
|
export * from "./hooks/useChainConnectors";
|
|
6
5
|
export * from "./hooks/useChaindata";
|
|
7
6
|
export * from "./hooks/useTokenRates";
|
|
8
7
|
export * from "./atoms/allAddresses";
|
|
9
|
-
export * from "./atoms/balanceModules";
|
|
10
8
|
export * from "./atoms/balances";
|
|
11
9
|
export * from "./atoms/chainConnectors";
|
|
12
10
|
export * from "./atoms/chaindata";
|
|
@@ -15,10 +13,6 @@ export * from "./atoms/config";
|
|
|
15
13
|
export * from "./atoms/cryptoWaitReady";
|
|
16
14
|
export * from "./atoms/tokenRates";
|
|
17
15
|
export type BalancesConfig = {
|
|
18
|
-
/**
|
|
19
|
-
* Optionally provide your own array of BalanceModules, when you don't want to use the defaults.
|
|
20
|
-
*/
|
|
21
|
-
balanceModules?: Array<(hydrate: Hydrate) => AnyBalanceModule>;
|
|
22
16
|
coinsApiUrl?: string;
|
|
23
17
|
/** Enables balances fetching for tokens on testnet chains. */
|
|
24
18
|
withTestnets?: boolean;
|
|
@@ -71,4 +65,4 @@ export type BalancesConfig = {
|
|
|
71
65
|
enabledTokens?: string[];
|
|
72
66
|
children?: ReactNode;
|
|
73
67
|
};
|
|
74
|
-
export declare const BalancesProvider: ({
|
|
68
|
+
export declare const BalancesProvider: ({ coinsApiUrl, withTestnets, enabledChains, enabledTokens, children, }: BalancesConfig) => import("react/jsx-runtime").JSX.Element;
|
|
@@ -2,29 +2,26 @@
|
|
|
2
2
|
|
|
3
3
|
var jotai = require('jotai');
|
|
4
4
|
var react = require('react');
|
|
5
|
-
var balances = require('@talismn/balances');
|
|
6
5
|
var tokenRates = require('@talismn/token-rates');
|
|
7
6
|
var jsxRuntime = require('react/jsx-runtime');
|
|
8
7
|
var chaindataProvider = require('@talismn/chaindata-provider');
|
|
9
|
-
var
|
|
8
|
+
var balances = require('@talismn/balances');
|
|
10
9
|
var jotaiEffect = require('jotai-effect');
|
|
11
|
-
var
|
|
12
|
-
var lodash = require('lodash');
|
|
13
|
-
var rxjs = require('rxjs');
|
|
14
|
-
var anylogger = require('anylogger');
|
|
10
|
+
var lodashEs = require('lodash-es');
|
|
15
11
|
var chainConnector = require('@talismn/chain-connector');
|
|
16
12
|
var chainConnectorEvm = require('@talismn/chain-connector-evm');
|
|
17
13
|
var connectionMeta = require('@talismn/connection-meta');
|
|
14
|
+
var util = require('@talismn/util');
|
|
15
|
+
var utils = require('jotai/utils');
|
|
16
|
+
var rxjs = require('rxjs');
|
|
18
17
|
var dexie = require('dexie');
|
|
19
|
-
var
|
|
18
|
+
var anylogger = require('anylogger');
|
|
20
19
|
var utilCrypto = require('@polkadot/util-crypto');
|
|
21
20
|
|
|
22
21
|
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
23
22
|
|
|
24
23
|
var anylogger__default = /*#__PURE__*/_interopDefault(anylogger);
|
|
25
|
-
var isEqual__default = /*#__PURE__*/_interopDefault(isEqual);
|
|
26
24
|
|
|
27
|
-
const balanceModuleCreatorsAtom = jotai.atom(balances.defaultBalanceModules);
|
|
28
25
|
const innerCoinsApiConfigAtom = jotai.atom(tokenRates.DEFAULT_COINSAPI_CONFIG);
|
|
29
26
|
const coinsApiConfigAtom = jotai.atom(get => get(innerCoinsApiConfigAtom), (_get, set, options) => set(innerCoinsApiConfigAtom, {
|
|
30
27
|
apiUrl: options.apiUrl ?? tokenRates.DEFAULT_COINSAPI_CONFIG.apiUrl
|
|
@@ -36,55 +33,6 @@ const enabledTokensAtom = jotai.atom(undefined);
|
|
|
36
33
|
/** Sets the list of addresses for which token balances will be fetched by the balances subscription */
|
|
37
34
|
const allAddressesAtom = jotai.atom([]);
|
|
38
35
|
|
|
39
|
-
var packageJson = {
|
|
40
|
-
name: "@talismn/balances-react"};
|
|
41
|
-
|
|
42
|
-
var log = anylogger__default.default(packageJson.name);
|
|
43
|
-
|
|
44
|
-
/**
|
|
45
|
-
// Persistence backend for indexedDB
|
|
46
|
-
// Add a new backend by implementing the BalancesPersistBackend interface
|
|
47
|
-
// configureStore can be called with a different indexedDB table
|
|
48
|
-
*/
|
|
49
|
-
const {
|
|
50
|
-
persistData,
|
|
51
|
-
retrieveData
|
|
52
|
-
} = balances.configureStore();
|
|
53
|
-
|
|
54
|
-
/**
|
|
55
|
-
// Persistence backend for localStorage
|
|
56
|
-
*/
|
|
57
|
-
const localStoragePersist = async balances$1 => {
|
|
58
|
-
const storedBalances = balances$1.map(b => {
|
|
59
|
-
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
60
|
-
const {
|
|
61
|
-
status,
|
|
62
|
-
...rest
|
|
63
|
-
} = b;
|
|
64
|
-
return rest;
|
|
65
|
-
});
|
|
66
|
-
const deflated = balances.compress(storedBalances);
|
|
67
|
-
localStorage.setItem("talismanBalances", deflated.toString());
|
|
68
|
-
};
|
|
69
|
-
const localStorageRetrieve = async () => {
|
|
70
|
-
const deflated = localStorage.getItem("talismanBalances");
|
|
71
|
-
if (deflated) {
|
|
72
|
-
// deflated will be a long string of numbers separated by commas
|
|
73
|
-
const deflatedArray = deflated.split(",").map(n => parseInt(n, 10));
|
|
74
|
-
const deflatedBytes = new Uint8Array(deflatedArray.length);
|
|
75
|
-
deflatedArray.forEach((n, i) => deflatedBytes[i] = n);
|
|
76
|
-
return balances.decompress(deflatedBytes).map(b => ({
|
|
77
|
-
...b,
|
|
78
|
-
status: "cache"
|
|
79
|
-
}));
|
|
80
|
-
}
|
|
81
|
-
return [];
|
|
82
|
-
};
|
|
83
|
-
const localStorageBalancesPersistBackend = {
|
|
84
|
-
persist: localStoragePersist,
|
|
85
|
-
retrieve: localStorageRetrieve
|
|
86
|
-
};
|
|
87
|
-
|
|
88
36
|
const chaindataProviderAtom = jotai.atom(() => {
|
|
89
37
|
return new chaindataProvider.ChaindataProvider({});
|
|
90
38
|
});
|
|
@@ -99,19 +47,44 @@ const chainConnectorsAtom = jotai.atom(get => {
|
|
|
99
47
|
};
|
|
100
48
|
});
|
|
101
49
|
|
|
102
|
-
const
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
50
|
+
const balancesProviderAtom = jotai.atom(get => {
|
|
51
|
+
return new balances.BalancesProvider(get(chaindataProviderAtom), get(chainConnectorsAtom)) // TODO pass storage
|
|
52
|
+
;
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
const chaindataAtom = utils.atomWithObservable(get => {
|
|
56
|
+
return rxjs.combineLatest({
|
|
57
|
+
networks: get(chaindataProviderAtom).networks$,
|
|
58
|
+
tokens: get(chaindataProviderAtom).tokens$
|
|
59
|
+
}).pipe(util.firstThenDebounce(1_000));
|
|
60
|
+
});
|
|
61
|
+
const filteredChaindataAtom = jotai.atom(async get => {
|
|
62
|
+
const enabledNetworkIds = get(enabledChainsAtom);
|
|
63
|
+
const enabledTokenIds = get(enabledTokensAtom);
|
|
64
|
+
const enableTestnets = get(enableTestnetsAtom);
|
|
65
|
+
const chaindata = await get(chaindataAtom);
|
|
66
|
+
const networks = chaindata.networks.filter(n => (enabledNetworkIds?.includes(n.id) || n.isDefault) && (enableTestnets || !n.isTestnet));
|
|
67
|
+
const networkById = lodashEs.keyBy(networks, n => n.id);
|
|
68
|
+
const tokens = chaindata.tokens.filter(token => (enabledTokenIds?.includes(token.id) || token.isDefault) && networkById[token.networkId]);
|
|
69
|
+
return {
|
|
70
|
+
networks,
|
|
71
|
+
tokens
|
|
72
|
+
};
|
|
73
|
+
});
|
|
74
|
+
const tokensAtom = jotai.atom(async get => {
|
|
75
|
+
const chaindata = await get(filteredChaindataAtom);
|
|
76
|
+
return chaindata.tokens;
|
|
77
|
+
});
|
|
78
|
+
const networksAtom = jotai.atom(async get => {
|
|
79
|
+
const chaindata = await get(filteredChaindataAtom);
|
|
80
|
+
return chaindata.networks;
|
|
113
81
|
});
|
|
114
82
|
|
|
83
|
+
var packageJson = {
|
|
84
|
+
name: "@talismn/balances-react"};
|
|
85
|
+
|
|
86
|
+
var log = anylogger__default.default(packageJson.name);
|
|
87
|
+
|
|
115
88
|
/**
|
|
116
89
|
* Converts a dexie Observable into an rxjs Observable.
|
|
117
90
|
*/
|
|
@@ -125,54 +98,6 @@ function dexieToRxjs(o) {
|
|
|
125
98
|
});
|
|
126
99
|
}
|
|
127
100
|
|
|
128
|
-
const chainsAtom = jotai.atom(async get => (await get(chaindataAtom)).chains);
|
|
129
|
-
const chainsByIdAtom = jotai.atom(async get => (await get(chaindataAtom)).chainsById);
|
|
130
|
-
const chainsByGenesisHashAtom = jotai.atom(async get => (await get(chaindataAtom)).chainsByGenesisHash);
|
|
131
|
-
const evmNetworksAtom = jotai.atom(async get => (await get(chaindataAtom)).evmNetworks);
|
|
132
|
-
const evmNetworksByIdAtom = jotai.atom(async get => (await get(chaindataAtom)).evmNetworksById);
|
|
133
|
-
const tokensAtom = jotai.atom(async get => (await get(chaindataAtom)).tokens);
|
|
134
|
-
const tokensByIdAtom = jotai.atom(async get => (await get(chaindataAtom)).tokensById);
|
|
135
|
-
const miniMetadatasAtom = jotai.atom(async get => (await get(chaindataAtom)).miniMetadatas);
|
|
136
|
-
const chaindataAtom = utils.atomWithObservable(get => {
|
|
137
|
-
const enableTestnets = get(enableTestnetsAtom);
|
|
138
|
-
const filterTestnets = items => enableTestnets ? items : items.filter(({
|
|
139
|
-
isTestnet
|
|
140
|
-
}) => !isTestnet);
|
|
141
|
-
const filterMapTestnets = items => enableTestnets ? items : Object.fromEntries(Object.entries(items).filter(([, {
|
|
142
|
-
isTestnet
|
|
143
|
-
}]) => !isTestnet));
|
|
144
|
-
const filterEnabledTokens = tokens => tokens.filter(token => token.isDefault || "isCustom" in token && token.isCustom);
|
|
145
|
-
const filterMapEnabledTokens = tokensById => Object.fromEntries(Object.entries(tokensById).filter(([, token]) => token.isDefault || "isCustom" in token && token.isCustom));
|
|
146
|
-
const distinctUntilIsEqual = rxjs.distinctUntilChanged((a, b) => isEqual__default.default(a, b));
|
|
147
|
-
const chains = get(chaindataProviderAtom).getNetworks$("polkadot").pipe(distinctUntilIsEqual, rxjs.map(filterTestnets), distinctUntilIsEqual);
|
|
148
|
-
const chainsById = get(chaindataProviderAtom).getNetworksMapById$("polkadot").pipe(distinctUntilIsEqual, rxjs.map(filterMapTestnets), distinctUntilIsEqual);
|
|
149
|
-
const chainsByGenesisHash = get(chaindataProviderAtom).getNetworksMapByGenesisHash$().pipe(distinctUntilIsEqual, rxjs.map(filterMapTestnets), distinctUntilIsEqual);
|
|
150
|
-
const evmNetworks = get(chaindataProviderAtom).getNetworks$("ethereum").pipe(distinctUntilIsEqual, rxjs.map(filterTestnets), distinctUntilIsEqual);
|
|
151
|
-
const networks = get(chaindataProviderAtom).getNetworks$().pipe(distinctUntilIsEqual, rxjs.map(filterTestnets), distinctUntilIsEqual);
|
|
152
|
-
const evmNetworksById = get(chaindataProviderAtom).getNetworksMapById$("ethereum").pipe(distinctUntilIsEqual, rxjs.map(filterMapTestnets), distinctUntilIsEqual);
|
|
153
|
-
const networksById = get(chaindataProviderAtom).getNetworksMapById$().pipe(distinctUntilIsEqual, rxjs.map(filterMapTestnets), distinctUntilIsEqual);
|
|
154
|
-
const tokens = get(chaindataProviderAtom).tokens$.pipe(distinctUntilIsEqual, rxjs.map(filterEnabledTokens), distinctUntilIsEqual);
|
|
155
|
-
const tokensById = get(chaindataProviderAtom).getTokensMapById$().pipe(distinctUntilIsEqual, rxjs.map(filterMapEnabledTokens), distinctUntilIsEqual);
|
|
156
|
-
const miniMetadatasObservable = dexieToRxjs(dexie.liveQuery(() => balances.db.miniMetadatas.toArray()));
|
|
157
|
-
const miniMetadatas = rxjs.combineLatest([miniMetadatasObservable.pipe(distinctUntilIsEqual), chainsById]).pipe(rxjs.map(([miniMetadatas, chainsById]) => miniMetadatas.filter(m => chainsById[m.chainId])), distinctUntilIsEqual);
|
|
158
|
-
return rxjs.combineLatest({
|
|
159
|
-
networks,
|
|
160
|
-
networksById,
|
|
161
|
-
chains,
|
|
162
|
-
chainsById,
|
|
163
|
-
chainsByGenesisHash,
|
|
164
|
-
evmNetworks,
|
|
165
|
-
evmNetworksById,
|
|
166
|
-
tokens,
|
|
167
|
-
tokensById,
|
|
168
|
-
miniMetadatas
|
|
169
|
-
}).pipe(
|
|
170
|
-
// debounce to prevent hammering UI with updates
|
|
171
|
-
util.firstThenDebounce(1_000), distinctUntilIsEqual);
|
|
172
|
-
});
|
|
173
|
-
|
|
174
|
-
const cryptoWaitReadyAtom = jotai.atom(async () => await utilCrypto.cryptoWaitReady());
|
|
175
|
-
|
|
176
101
|
const tokenRatesAtom = jotai.atom(async get => {
|
|
177
102
|
// runs a timer to keep tokenRates up to date
|
|
178
103
|
get(tokenRatesFetcherAtomEffect);
|
|
@@ -193,9 +118,9 @@ const tokenRatesFetcherAtomEffect = jotaiEffect.atomEffect(get => {
|
|
|
193
118
|
|
|
194
119
|
// we have to get these synchronously so that jotai knows to restart our timer when they change
|
|
195
120
|
const coinsApiConfig = get(coinsApiConfigAtom);
|
|
196
|
-
const
|
|
121
|
+
const tokensPromise = get(tokensAtom);
|
|
197
122
|
(async () => {
|
|
198
|
-
const tokensById = await
|
|
123
|
+
const tokensById = lodashEs.keyBy(await tokensPromise, "id");
|
|
199
124
|
const tokenIds = Object.keys(tokensById);
|
|
200
125
|
const loopMs = 300_000; // 300_000ms = 300s = 5 minutes
|
|
201
126
|
const retryTimeout = 5_000; // 5_000ms = 5 seconds
|
|
@@ -236,213 +161,42 @@ const tokenRatesFetcherAtomEffect = jotaiEffect.atomEffect(get => {
|
|
|
236
161
|
return () => abort.abort("Unsubscribed");
|
|
237
162
|
});
|
|
238
163
|
|
|
239
|
-
const
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
const [balances$1, hydrateData] = await Promise.all([get(balancesObservableAtom), get(balancesHydrateDataAtom)]);
|
|
243
|
-
return new balances.Balances(Object.values(balances$1).filter(balance => !!hydrateData?.tokens?.[balance.tokenId]),
|
|
244
|
-
// hydrate balance chains, evmNetworks, tokens and tokenRates
|
|
245
|
-
hydrateData);
|
|
164
|
+
const addressesByTokenIdAtom = jotai.atom(async get => {
|
|
165
|
+
const [tokens, addresses] = await Promise.all([get(tokensAtom), get(allAddressesAtom)]);
|
|
166
|
+
return lodashEs.fromPairs(tokens.map(token => [token.id, addresses]));
|
|
246
167
|
});
|
|
247
|
-
const
|
|
248
|
-
const
|
|
249
|
-
const
|
|
250
|
-
const
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
168
|
+
const rawBalancesAtom = jotai.atom([]);
|
|
169
|
+
const subscribeBalancesAtom = jotaiEffect.atomEffect((get, set) => {
|
|
170
|
+
const unsub = (async () => {
|
|
171
|
+
const balancesProvider = get(balancesProviderAtom);
|
|
172
|
+
const addressesByTokenId = await get(addressesByTokenIdAtom);
|
|
173
|
+
const sub = balancesProvider.getBalances$(addressesByTokenId).subscribe(balances => {
|
|
174
|
+
set(rawBalancesAtom, balances.balances);
|
|
175
|
+
});
|
|
176
|
+
return () => {
|
|
177
|
+
return sub.unsubscribe();
|
|
178
|
+
};
|
|
179
|
+
})();
|
|
180
|
+
return () => {
|
|
181
|
+
unsub.then(unsubscribe => unsubscribe());
|
|
182
|
+
};
|
|
257
183
|
});
|
|
258
184
|
const balancesHydrateDataAtom = jotai.atom(async get => {
|
|
259
|
-
const [
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
}, tokenRates] = await Promise.all([get(chaindataAtom), get(tokenRatesAtom)]);
|
|
185
|
+
const [chaindata, tokenRates] = await Promise.all([get(chaindataAtom), get(tokenRatesAtom)]);
|
|
186
|
+
const networksById = lodashEs.keyBy(chaindata.networks, "id");
|
|
187
|
+
const tokensById = lodashEs.keyBy(chaindata.tokens, "id");
|
|
263
188
|
return {
|
|
264
189
|
networks: networksById,
|
|
265
190
|
tokens: tokensById,
|
|
266
191
|
tokenRates
|
|
267
192
|
};
|
|
268
193
|
});
|
|
269
|
-
const
|
|
270
|
-
//
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
const atomDependencies = Promise.all([get(cryptoWaitReadyAtom), get(balanceModulesAtom), get(allAddressesAtom), get(chainsAtom), get(chainsByIdAtom), get(evmNetworksAtom), get(evmNetworksByIdAtom), get(tokensAtom), get(tokensByIdAtom), get(miniMetadatasAtom), get(enabledChainsAtom), get(enabledTokensAtom), get(hydrateBalancesObservableAtom)]);
|
|
276
|
-
const persistBackend = get(balancesPersistBackendAtom);
|
|
277
|
-
const unsubsPromise = (async () => {
|
|
278
|
-
const [_cryptoReady, balanceModules, allAddresses, chains, chainsById, evmNetworks, evmNetworksById, tokens, tokensById, _miniMetadatas, enabledChainsConfig, enabledTokensConfig] = await atomDependencies;
|
|
279
|
-
if (abort.signal.aborted) return;
|
|
280
|
-
|
|
281
|
-
// persist data every thirty seconds
|
|
282
|
-
balancesObservable.pipe(rxjs.debounceTime(10000)).subscribe(balancesUpdate => {
|
|
283
|
-
persistBackend.persist(Object.values(balancesUpdate));
|
|
284
|
-
});
|
|
285
|
-
const updateBalances = async balancesUpdates => {
|
|
286
|
-
if (abort.signal.aborted) return;
|
|
287
|
-
const updatesWithIds = new balances.Balances(balancesUpdates);
|
|
288
|
-
const existing = balancesObservable.value;
|
|
289
|
-
|
|
290
|
-
// update initialising set here - before filtering out zero balances
|
|
291
|
-
// while this may include stale balances, the important thing is that the balance is no longer "initialising"
|
|
292
|
-
// balancesUpdates.forEach((b) => this.#initialising.delete(getBalanceId(b)))
|
|
293
|
-
|
|
294
|
-
const newlyZeroBalances = [];
|
|
295
|
-
const changedBalances = Object.fromEntries(updatesWithIds.each.filter(newB => {
|
|
296
|
-
const isZero = newB.total.tokens === "0";
|
|
297
|
-
// Keep new balances which are not zeros
|
|
298
|
-
const existingB = existing[newB.id];
|
|
299
|
-
if (!existingB && !isZero) return true;
|
|
300
|
-
const hasChanged = !lodash.isEqual(existingB, newB.toJSON());
|
|
301
|
-
// Collect balances now confirmed to be zero separately, so they can be filtered out from the main set
|
|
302
|
-
if (existingB && hasChanged && isZero) newlyZeroBalances.push(newB.id);
|
|
303
|
-
// Keep changed balances, which are not known zeros
|
|
304
|
-
return hasChanged && !isZero;
|
|
305
|
-
}).map(b => [b.id, b.toJSON()]));
|
|
306
|
-
if (Object.keys(changedBalances).length === 0 && newlyZeroBalances.length === 0) return;
|
|
307
|
-
const nonZeroBalances = newlyZeroBalances.length > 0 ? Object.fromEntries(Object.entries(existing).filter(([id]) => !newlyZeroBalances.includes(id))) : existing;
|
|
308
|
-
const newBalancesState = {
|
|
309
|
-
...nonZeroBalances,
|
|
310
|
-
...changedBalances
|
|
311
|
-
};
|
|
312
|
-
if (Object.keys(newBalancesState).length === 0) return;
|
|
313
|
-
balancesObservable.next(newBalancesState);
|
|
314
|
-
};
|
|
315
|
-
const deleteBalances = async balancesFilter => {
|
|
316
|
-
if (abort.signal.aborted) return;
|
|
317
|
-
const balancesToKeep = Object.fromEntries(new balances.Balances(Object.values(await get(balancesObservableAtom))).each.filter(b => !balancesFilter(b)).map(b => [b.id, b.toJSON()]));
|
|
318
|
-
balancesObservable.next(balancesToKeep);
|
|
319
|
-
};
|
|
320
|
-
const enabledChainIds = enabledChainsConfig?.map(genesisHash => chains.find(chain => chain.genesisHash === genesisHash)?.id);
|
|
321
|
-
const enabledChainsFilter = enabledChainIds ? token => token.platform === "polkadot" && enabledChainIds?.includes(token.networkId) : () => true;
|
|
322
|
-
const enabledTokensFilter = enabledTokensConfig ? token => enabledTokensConfig.includes(token.id) : () => true;
|
|
323
|
-
const enabledTokenIds = tokens.filter(enabledChainsFilter).filter(enabledTokensFilter).map(({
|
|
324
|
-
id
|
|
325
|
-
}) => id);
|
|
326
|
-
if (enabledTokenIds.length < 1 || allAddresses.length < 1) return;
|
|
327
|
-
const addressesByTokenByModule = {};
|
|
328
|
-
enabledTokenIds.flatMap(tokenId => tokensById[tokenId]).forEach(token => {
|
|
329
|
-
// filter out tokens on chains/evmNetworks which have no rpcs
|
|
330
|
-
const hasRpcs = token.networkId && (chainsById[token.networkId]?.rpcs?.length ?? 0) > 0 || token.networkId && (evmNetworksById[token.networkId]?.rpcs?.length ?? 0) > 0;
|
|
331
|
-
if (!hasRpcs) return;
|
|
332
|
-
if (!addressesByTokenByModule[token.type]) addressesByTokenByModule[token.type] = {};
|
|
333
|
-
addressesByTokenByModule[token.type][token.id] = allAddresses.filter(address => {
|
|
334
|
-
// for each address, fetch balances only from compatible chains
|
|
335
|
-
return util.isEthereumAddress(address) ? token.networkId || chainsById[token.networkId ?? ""]?.account === "secp256k1" : token.networkId && chainsById[token.networkId ?? ""]?.account !== "secp256k1";
|
|
336
|
-
});
|
|
337
|
-
});
|
|
338
|
-
|
|
339
|
-
// Delete invalid cached balances
|
|
340
|
-
const chainIds = new Set(chains.map(chain => chain.id));
|
|
341
|
-
const evmNetworkIds = new Set(evmNetworks.map(evmNetwork => evmNetwork.id));
|
|
342
|
-
await deleteBalances(balance => {
|
|
343
|
-
// delete cached balances for accounts which don't exist anymore
|
|
344
|
-
if (!balance.address || !allAddresses.includes(balance.address)) return true;
|
|
345
|
-
|
|
346
|
-
// delete cached balances when chain/evmNetwork doesn't exist
|
|
347
|
-
if (!chainIds.has(balance.networkId) && !evmNetworkIds.has(balance.networkId)) return true;
|
|
348
|
-
|
|
349
|
-
// delete cached balance when token doesn't exist / is disabled
|
|
350
|
-
if (!enabledTokenIds.includes(balance.tokenId)) return true;
|
|
351
|
-
|
|
352
|
-
// delete cached balance when module doesn't exist
|
|
353
|
-
if (!balanceModules.find(module => module.type === balance.source)) return true;
|
|
354
|
-
|
|
355
|
-
// delete cached balance for accounts on incompatible chains
|
|
356
|
-
// (substrate accounts shouldn't have evm balances)
|
|
357
|
-
// (evm accounts shouldn't have substrate balances (unless the chain uses secp256k1 accounts))
|
|
358
|
-
const chain = chains.find(({
|
|
359
|
-
id
|
|
360
|
-
}) => id === balance.networkId) || null;
|
|
361
|
-
const hasChain = chainIds.has(balance.networkId);
|
|
362
|
-
const hasEvmNetwork = evmNetworkIds.has(balance.networkId);
|
|
363
|
-
const chainUsesSecp256k1Accounts = chain?.account === "secp256k1";
|
|
364
|
-
if (!util.isEthereumAddress(balance.address)) {
|
|
365
|
-
if (!hasChain) return true;
|
|
366
|
-
if (chainUsesSecp256k1Accounts) return true;
|
|
367
|
-
}
|
|
368
|
-
if (util.isEthereumAddress(balance.address)) {
|
|
369
|
-
if (!hasEvmNetwork && !chainUsesSecp256k1Accounts) return true;
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
// keep balance
|
|
373
|
-
return false;
|
|
374
|
-
});
|
|
375
|
-
if (abort.signal.aborted) return;
|
|
376
|
-
|
|
377
|
-
// after 30 seconds, change the status of all balances still initializing to stale
|
|
378
|
-
setTimeout(() => {
|
|
379
|
-
if (abort.signal.aborted) return;
|
|
380
|
-
const staleObservable = balancesObservable.pipe(rxjs.map(val => Object.values(val).filter(({
|
|
381
|
-
status
|
|
382
|
-
}) => status === "cache").map(balance => ({
|
|
383
|
-
...balance,
|
|
384
|
-
status: "stale"
|
|
385
|
-
}))));
|
|
386
|
-
rxjs.firstValueFrom(staleObservable).then(v => {
|
|
387
|
-
if (v.length) updateBalances(v);
|
|
388
|
-
});
|
|
389
|
-
}, 30_000);
|
|
390
|
-
return balanceModules.map(balanceModule => {
|
|
391
|
-
const unsub = balances.balances(balanceModule, addressesByTokenByModule[balanceModule.type] ?? {}, (error, balances) => {
|
|
392
|
-
// log errors
|
|
393
|
-
if (error) {
|
|
394
|
-
if (error?.type === "STALE_RPC_ERROR" || error?.type === "WEBSOCKET_ALLOCATION_EXHAUSTED_ERROR") {
|
|
395
|
-
const addressesByModuleToken = addressesByTokenByModule[balanceModule.type] ?? {};
|
|
396
|
-
const staleObservable = balancesObservable.pipe(rxjs.map(val => Object.values(val).filter(balance => {
|
|
397
|
-
const {
|
|
398
|
-
tokenId,
|
|
399
|
-
address,
|
|
400
|
-
source
|
|
401
|
-
} = balance;
|
|
402
|
-
const chainComparison = error.chainId ? "chainId" in balance && error.chainId === balance.chainId : error.evmNetworkId ? "evmNetworkId" in balance && error.evmNetworkId === balance.evmNetworkId : true;
|
|
403
|
-
return chainComparison && addressesByModuleToken[tokenId]?.includes(address) && source === balanceModule.type;
|
|
404
|
-
}).map(balance => ({
|
|
405
|
-
...balance,
|
|
406
|
-
status: "stale"
|
|
407
|
-
}))));
|
|
408
|
-
rxjs.firstValueFrom(staleObservable).then(v => {
|
|
409
|
-
if (v.length) updateBalances(v);
|
|
410
|
-
});
|
|
411
|
-
}
|
|
412
|
-
return log.error(`Failed to fetch ${balanceModule.type} balances`, error);
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
// ignore empty balance responses
|
|
416
|
-
if (!balances) return;
|
|
417
|
-
// ignore balances from old subscriptions which are still in the process of unsubscribing
|
|
418
|
-
if (abort.signal.aborted) return;
|
|
419
|
-
|
|
420
|
-
// good balances
|
|
421
|
-
if (balances) {
|
|
422
|
-
if ("status" in balances) {
|
|
423
|
-
// For modules using the new SubscriptionResultWithStatus pattern
|
|
424
|
-
//TODO fix initialisin
|
|
425
|
-
// if (result.status === "initialising") this.#initialising.add(balanceModule.type)
|
|
426
|
-
// else this.#initialising.delete(balanceModule.type)
|
|
427
|
-
updateBalances(balances.data);
|
|
428
|
-
} else {
|
|
429
|
-
// add good ones to initialisedBalances
|
|
430
|
-
updateBalances(Object.values(balances.toJSON()));
|
|
431
|
-
}
|
|
432
|
-
}
|
|
433
|
-
});
|
|
434
|
-
return () => unsub.then(unsubscribe => unsubscribe());
|
|
435
|
-
});
|
|
436
|
-
})();
|
|
437
|
-
|
|
438
|
-
// close the existing subscriptions when our effect unmounts
|
|
439
|
-
// (wait 2 seconds before actually unsubscribing, to allow the websocket to be reused in that time)
|
|
440
|
-
const unsubscribe = () => unsubsPromise.then(unsubs => {
|
|
441
|
-
persistBackend.persist(Object.values(balancesObservable.value));
|
|
442
|
-
unsubs?.forEach(unsub => unsub());
|
|
443
|
-
});
|
|
444
|
-
abort.signal.addEventListener("abort", () => setTimeout(unsubscribe, 2_000));
|
|
445
|
-
return () => abort.abort("Unsubscribed");
|
|
194
|
+
const balancesAtom = jotai.atom(async get => {
|
|
195
|
+
// subscribe to balancesProvider getBalance with addressesByTokenIdAtom as param
|
|
196
|
+
get(subscribeBalancesAtom);
|
|
197
|
+
const hydrate = await get(balancesHydrateDataAtom);
|
|
198
|
+
const rawBalances = get(rawBalancesAtom);
|
|
199
|
+
return new balances.Balances(rawBalances, hydrate);
|
|
446
200
|
});
|
|
447
201
|
|
|
448
202
|
const useSetBalancesAddresses = addresses => {
|
|
@@ -459,10 +213,8 @@ const useSetBalancesAddresses = addresses => {
|
|
|
459
213
|
* @returns a Balances object containing the current balances state.
|
|
460
214
|
*/
|
|
461
215
|
|
|
462
|
-
const useBalances =
|
|
463
|
-
|
|
464
|
-
if (persistBackend) setPersistBackend(persistBackend);
|
|
465
|
-
return jotai.useAtomValue(allBalancesAtom);
|
|
216
|
+
const useBalances = () => {
|
|
217
|
+
return jotai.useAtomValue(balancesAtom);
|
|
466
218
|
};
|
|
467
219
|
|
|
468
220
|
// TODO: Extract to shared definition between extension and @talismn/balances-react
|
|
@@ -499,30 +251,41 @@ const useChainConnectors = () => jotai.useAtomValue(chainConnectorsAtom);
|
|
|
499
251
|
|
|
500
252
|
const useChaindataProvider = () => jotai.useAtomValue(chaindataProviderAtom);
|
|
501
253
|
const useChaindata = () => jotai.useAtomValue(chaindataAtom);
|
|
502
|
-
const
|
|
503
|
-
const
|
|
504
|
-
const
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
const
|
|
254
|
+
const useNetworks = () => useChaindata().networks;
|
|
255
|
+
const useNetworksById = () => {
|
|
256
|
+
const {
|
|
257
|
+
networks
|
|
258
|
+
} = useChaindata();
|
|
259
|
+
return react.useMemo(() => lodashEs.keyBy(networks, n => n.id), [networks]);
|
|
260
|
+
};
|
|
261
|
+
const useNetwork = networkId => {
|
|
262
|
+
const networksById = useNetworksById();
|
|
263
|
+
return networksById[networkId ?? ""] ?? null;
|
|
264
|
+
};
|
|
265
|
+
const useTokens = () => useChaindata().tokens;
|
|
266
|
+
const useTokensById = () => {
|
|
267
|
+
const {
|
|
268
|
+
tokens
|
|
269
|
+
} = useChaindata();
|
|
270
|
+
return react.useMemo(() => lodashEs.keyBy(tokens, t => t.id), [tokens]);
|
|
271
|
+
};
|
|
272
|
+
const useToken = tokenId => {
|
|
273
|
+
const tokensById = useTokensById();
|
|
274
|
+
return tokensById[tokenId ?? ""] ?? null;
|
|
275
|
+
};
|
|
510
276
|
|
|
511
277
|
const useTokenRates = () => jotai.useAtomValue(tokenRatesAtom);
|
|
512
278
|
const useTokenRate = tokenId => useTokenRates()[tokenId ?? ""] ?? undefined;
|
|
513
279
|
|
|
280
|
+
const cryptoWaitReadyAtom = jotai.atom(async () => await utilCrypto.cryptoWaitReady());
|
|
281
|
+
|
|
514
282
|
const BalancesProvider = ({
|
|
515
|
-
balanceModules,
|
|
516
283
|
coinsApiUrl,
|
|
517
284
|
withTestnets,
|
|
518
285
|
enabledChains,
|
|
519
286
|
enabledTokens,
|
|
520
287
|
children
|
|
521
288
|
}) => {
|
|
522
|
-
const setBalanceModules = jotai.useSetAtom(balanceModuleCreatorsAtom);
|
|
523
|
-
react.useEffect(() => {
|
|
524
|
-
if (balanceModules !== undefined) setBalanceModules(balanceModules);
|
|
525
|
-
}, [balanceModules, setBalanceModules]);
|
|
526
289
|
const setCoinsApiConfig = jotai.useSetAtom(coinsApiConfigAtom);
|
|
527
290
|
react.useEffect(() => {
|
|
528
291
|
setCoinsApiConfig({
|
|
@@ -572,41 +335,30 @@ Object.defineProperty(exports, "subTokensTokenId", {
|
|
|
572
335
|
});
|
|
573
336
|
exports.BalancesProvider = BalancesProvider;
|
|
574
337
|
exports.allAddressesAtom = allAddressesAtom;
|
|
575
|
-
exports.
|
|
576
|
-
exports.balanceModuleCreatorsAtom = balanceModuleCreatorsAtom;
|
|
577
|
-
exports.balanceModulesAtom = balanceModulesAtom;
|
|
578
|
-
exports.balancesPersistBackendAtom = balancesPersistBackendAtom;
|
|
338
|
+
exports.balancesAtom = balancesAtom;
|
|
579
339
|
exports.chainConnectorsAtom = chainConnectorsAtom;
|
|
580
340
|
exports.chaindataAtom = chaindataAtom;
|
|
581
341
|
exports.chaindataProviderAtom = chaindataProviderAtom;
|
|
582
|
-
exports.chainsAtom = chainsAtom;
|
|
583
|
-
exports.chainsByGenesisHashAtom = chainsByGenesisHashAtom;
|
|
584
|
-
exports.chainsByIdAtom = chainsByIdAtom;
|
|
585
342
|
exports.coinsApiConfigAtom = coinsApiConfigAtom;
|
|
586
343
|
exports.cryptoWaitReadyAtom = cryptoWaitReadyAtom;
|
|
587
344
|
exports.enableTestnetsAtom = enableTestnetsAtom;
|
|
588
345
|
exports.enabledChainsAtom = enabledChainsAtom;
|
|
589
346
|
exports.enabledTokensAtom = enabledTokensAtom;
|
|
590
|
-
exports.evmNetworksAtom = evmNetworksAtom;
|
|
591
|
-
exports.evmNetworksByIdAtom = evmNetworksByIdAtom;
|
|
592
347
|
exports.getStaleChains = getStaleChains;
|
|
593
|
-
exports.
|
|
348
|
+
exports.networksAtom = networksAtom;
|
|
594
349
|
exports.tokenRatesAtom = tokenRatesAtom;
|
|
595
350
|
exports.tokensAtom = tokensAtom;
|
|
596
|
-
exports.tokensByIdAtom = tokensByIdAtom;
|
|
597
351
|
exports.useBalances = useBalances;
|
|
598
352
|
exports.useBalancesStatus = useBalancesStatus;
|
|
599
|
-
exports.useChain = useChain;
|
|
600
353
|
exports.useChainConnectors = useChainConnectors;
|
|
601
354
|
exports.useChaindata = useChaindata;
|
|
602
355
|
exports.useChaindataProvider = useChaindataProvider;
|
|
603
|
-
exports.
|
|
604
|
-
exports.
|
|
605
|
-
exports.
|
|
606
|
-
exports.useEvmNetworks = useEvmNetworks;
|
|
607
|
-
exports.useMiniMetadatas = useMiniMetadatas;
|
|
356
|
+
exports.useNetwork = useNetwork;
|
|
357
|
+
exports.useNetworks = useNetworks;
|
|
358
|
+
exports.useNetworksById = useNetworksById;
|
|
608
359
|
exports.useSetBalancesAddresses = useSetBalancesAddresses;
|
|
609
360
|
exports.useToken = useToken;
|
|
610
361
|
exports.useTokenRate = useTokenRate;
|
|
611
362
|
exports.useTokenRates = useTokenRates;
|
|
612
363
|
exports.useTokens = useTokens;
|
|
364
|
+
exports.useTokensById = useTokensById;
|