@talismn/balances 0.0.0-pr599-20230306082809 → 0.0.0-pr600-20230307005925

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 CHANGED
@@ -1,13 +1,13 @@
1
1
  # @talismn/balances
2
2
 
3
- ## 0.0.0-pr599-20230306082809
3
+ ## 0.0.0-pr600-20230307005925
4
4
 
5
5
  ### Patch Changes
6
6
 
7
7
  - 6643a4e: fix: tokenRates in @talismn/balances-react
8
8
  - 6643a4e: fix: ported useDbCache related perf fixes to @talismn/balances-react
9
9
  - Updated dependencies [6643a4e]
10
- - @talismn/token-rates@0.0.0-pr599-20230306082809
10
+ - @talismn/token-rates@0.0.0-pr600-20230307005925
11
11
 
12
12
  ## 0.3.3
13
13
 
@@ -25,20 +25,29 @@ export type TransferTokenTx = {
25
25
  type: "evm";
26
26
  tx: ethers.providers.TransactionRequest;
27
27
  };
28
+ export type ChainConnectors = {
29
+ substrate?: ChainConnector;
30
+ evm?: ChainConnectorEvm;
31
+ };
32
+ export type Hydrate = {
33
+ chainConnectors: ChainConnectors;
34
+ chaindataProvider: ChaindataProvider;
35
+ };
36
+ export type NewBalanceModule<TModuleType extends string, TTokenType extends ExtendableTokenType, TChainMeta extends ExtendableChainMeta = DefaultChainMeta, TModuleConfig extends ExtendableModuleConfig = DefaultModuleConfig, TTransferParams extends ExtendableTransferParams = DefaultTransferParams> = (hydrate: Hydrate) => BalanceModule<TModuleType, TTokenType, TChainMeta, TModuleConfig, TTransferParams>;
28
37
  export interface BalanceModule<TModuleType extends string, TTokenType extends ExtendableTokenType, TChainMeta extends ExtendableChainMeta = DefaultChainMeta, TModuleConfig extends ExtendableModuleConfig = DefaultModuleConfig, TTransferParams extends ExtendableTransferParams = DefaultTransferParams> extends BalanceModuleSubstrate<TModuleType, TTokenType, TChainMeta, TModuleConfig, TTransferParams>, BalanceModuleEvm<TModuleType, TTokenType, TChainMeta, TModuleConfig, TTransferParams> {
29
38
  }
30
39
  export declare const DefaultBalanceModule: <TModuleType extends string, TTokenType extends IToken, TChainMeta extends ExtendableChainMeta = undefined, TModuleConfig extends ExtendableModuleConfig = undefined, TTransferParams extends ExtendableTransferParams = undefined>(type: TModuleType) => BalanceModule<TModuleType, TTokenType, TChainMeta, TModuleConfig, TTransferParams>;
31
40
  interface BalanceModuleSubstrate<TModuleType extends string, TTokenType extends ExtendableTokenType, TChainMeta extends ExtendableChainMeta = DefaultChainMeta, TModuleConfig extends ExtendableModuleConfig = DefaultModuleConfig, TTransferParams extends ExtendableTransferParams = DefaultTransferParams> extends BalanceModuleCommon<TModuleType, TTokenType, TTransferParams> {
32
41
  /** Pre-processes any substrate chain metadata required by this module ahead of time */
33
- fetchSubstrateChainMeta(chainConnector: ChainConnector, chaindataProvider: ChaindataProvider, chainId: ChainId, moduleConfig: TModuleConfig | undefined): Promise<TChainMeta | null>;
42
+ fetchSubstrateChainMeta(chainId: ChainId, moduleConfig?: TModuleConfig): Promise<TChainMeta | null>;
34
43
  /** Detects which tokens are available on a given substrate chain */
35
- fetchSubstrateChainTokens(chainConnector: ChainConnector, chaindataProvider: ChaindataProvider, chainId: ChainId, chainMeta: TChainMeta, moduleConfig: TModuleConfig | undefined): Promise<Record<TTokenType["id"], TTokenType>>;
44
+ fetchSubstrateChainTokens(chainId: ChainId, chainMeta: TChainMeta, moduleConfig?: TModuleConfig): Promise<Record<TTokenType["id"], TTokenType>>;
36
45
  }
37
46
  interface BalanceModuleEvm<TModuleType extends string, TTokenType extends ExtendableTokenType, TChainMeta extends ExtendableChainMeta = DefaultChainMeta, TModuleConfig extends ExtendableModuleConfig = DefaultModuleConfig, TTransferParams extends ExtendableTransferParams = DefaultTransferParams> extends BalanceModuleCommon<TModuleType, TTokenType, TTransferParams> {
38
47
  /** Pre-processes any evm chain metadata required by this module ahead of time */
39
- fetchEvmChainMeta(chainConnector: ChainConnectorEvm, chaindataProvider: ChaindataProvider, chainId: ChainId, moduleConfig: TModuleConfig | undefined): Promise<TChainMeta | null>;
48
+ fetchEvmChainMeta(chainId: ChainId, moduleConfig?: TModuleConfig): Promise<TChainMeta | null>;
40
49
  /** Detects which tokens are available on a given evm chain */
41
- fetchEvmChainTokens(chainConnector: ChainConnectorEvm, chaindataProvider: ChaindataProvider, chainId: ChainId, chainMeta: TChainMeta, moduleConfig: TModuleConfig | undefined): Promise<Record<TTokenType["id"], TTokenType>>;
50
+ fetchEvmChainTokens(chainId: ChainId, chainMeta: TChainMeta, moduleConfig?: TModuleConfig): Promise<Record<TTokenType["id"], TTokenType>>;
42
51
  }
43
52
  interface BalanceModuleCommon<TModuleType extends string, TTokenType extends ExtendableTokenType, TTransferParams extends ExtendableTransferParams> {
44
53
  get type(): TModuleType;
@@ -47,19 +56,10 @@ interface BalanceModuleCommon<TModuleType extends string, TTokenType extends Ext
47
56
  *
48
57
  * If subscriptions are not possible, this function should poll at some reasonable interval.
49
58
  */
50
- subscribeBalances(chainConnectors: {
51
- substrate?: ChainConnector;
52
- evm?: ChainConnectorEvm;
53
- }, chaindataProvider: ChaindataProvider, addressesByToken: AddressesByToken<TTokenType>, callback: SubscriptionCallback<Balances>): Promise<UnsubscribeFn>;
59
+ subscribeBalances(addressesByToken: AddressesByToken<TTokenType>, callback: SubscriptionCallback<Balances>): Promise<UnsubscribeFn>;
54
60
  /** Fetch balances for this module with optional filtering */
55
- fetchBalances(chainConnectors: {
56
- substrate?: ChainConnector;
57
- evm?: ChainConnectorEvm;
58
- }, chaindataProvider: ChaindataProvider, addressesByToken: AddressesByToken<TTokenType>): Promise<Balances>;
59
- transferToken(chainConnectors: {
60
- substrate?: ChainConnector;
61
- evm?: ChainConnectorEvm;
62
- }, chaindataProvider: ChaindataProvider, transferParams: TTransferParams): Promise<TransferTokenTx | null>;
63
- [x: string | number | symbol]: unknown;
61
+ fetchBalances(addressesByToken: AddressesByToken<TTokenType>): Promise<Balances>;
62
+ /** Prepare a tx to transfer some tokens from this module */
63
+ transferToken(transferParams: TTransferParams): Promise<TransferTokenTx | null>;
64
64
  }
65
65
  export {};
@@ -1,21 +1,20 @@
1
- import { TypeRegistry } from "@polkadot/types";
2
- import { ChainConnector } from "@talismn/chain-connector";
3
- import { ChainConnectorEvm } from "@talismn/chain-connector-evm";
4
- import { ChaindataProvider } from "@talismn/chaindata-provider";
1
+ import { Metadata } from "@polkadot/types";
2
+ import type { Registry } from "@polkadot/types-codec/types";
3
+ import { ChainId } from "@talismn/chaindata-provider";
5
4
  import { BalanceModule, DefaultChainMeta, DefaultModuleConfig, DefaultTransferParams, ExtendableChainMeta, ExtendableModuleConfig, ExtendableTokenType, ExtendableTransferParams } from "./BalanceModule";
6
5
  import { AddressesByToken, Balance, Balances, SubscriptionCallback, UnsubscribeFn } from "./types";
7
6
  /**
8
7
  * Wraps a BalanceModule's fetch/subscribe methods with a single `balances` method.
9
8
  * This `balances` method will subscribe if a callback parameter is provided, or otherwise fetch.
10
9
  */
11
- export declare function balances<TModuleType extends string, TTokenType extends ExtendableTokenType, TChainMeta extends ExtendableChainMeta = DefaultChainMeta, TModuleConfig extends ExtendableModuleConfig = DefaultModuleConfig, TTransferParams extends ExtendableTransferParams = DefaultTransferParams>(balanceModule: BalanceModule<TModuleType, TTokenType, TChainMeta, TModuleConfig, TTransferParams>, chainConnectors: {
12
- substrate?: ChainConnector;
13
- evm?: ChainConnectorEvm;
14
- }, chaindataProvider: ChaindataProvider, addressesByToken: AddressesByToken<TTokenType>): Promise<Balances>;
15
- export declare function balances<TModuleType extends string, TTokenType extends ExtendableTokenType, TChainMeta extends ExtendableChainMeta = DefaultChainMeta, TModuleConfig extends ExtendableModuleConfig = DefaultModuleConfig, TTransferParams extends ExtendableTransferParams = DefaultTransferParams>(balanceModule: BalanceModule<TModuleType, TTokenType, TChainMeta, TModuleConfig, TTransferParams>, chainConnectors: {
16
- substrate?: ChainConnector;
17
- evm?: ChainConnectorEvm;
18
- }, chaindataProvider: ChaindataProvider, addressesByToken: AddressesByToken<TTokenType>, callback: SubscriptionCallback<Balances>): Promise<UnsubscribeFn>;
10
+ export declare function balances<TModuleType extends string, TTokenType extends ExtendableTokenType, TChainMeta extends ExtendableChainMeta = DefaultChainMeta, TModuleConfig extends ExtendableModuleConfig = DefaultModuleConfig, TTransferParams extends ExtendableTransferParams = DefaultTransferParams>(balanceModule: BalanceModule<TModuleType, TTokenType, TChainMeta, TModuleConfig, TTransferParams>, addressesByToken: AddressesByToken<TTokenType>): Promise<Balances>;
11
+ export declare function balances<TModuleType extends string, TTokenType extends ExtendableTokenType, TChainMeta extends ExtendableChainMeta = DefaultChainMeta, TModuleConfig extends ExtendableModuleConfig = DefaultModuleConfig, TTransferParams extends ExtendableTransferParams = DefaultTransferParams>(balanceModule: BalanceModule<TModuleType, TTokenType, TChainMeta, TModuleConfig, TTransferParams>, addressesByToken: AddressesByToken<TTokenType>, callback: SubscriptionCallback<Balances>): Promise<UnsubscribeFn>;
12
+ export declare const useMetadataCache: () => {
13
+ getOrCreateMetadata: (chainId: ChainId, metadataRpc: `0x${string}`) => Metadata;
14
+ };
15
+ export declare const useTypeRegistryCache: () => {
16
+ getOrCreateTypeRegistry: (chainId: ChainId, metadataRpc: `0x${string}`) => Registry;
17
+ };
19
18
  export declare const filterMirrorTokens: (balance: Balance, i: number, balances: Balance[]) => boolean;
20
19
  /**
21
20
  * Used by a variety of balance modules to help encode and decode substrate state calls.
@@ -23,7 +22,7 @@ export declare const filterMirrorTokens: (balance: Balance, i: number, balances:
23
22
  export declare class StorageHelper {
24
23
  #private;
25
24
  tags: any;
26
- constructor(registry: TypeRegistry, module: string, method: string, ...parameters: any[]);
25
+ constructor(registry: Registry, module: string, method: string, ...parameters: any[]);
27
26
  get stateKey(): `0x${string}` | undefined;
28
27
  get module(): string;
29
28
  get method(): string;
@@ -80,6 +80,7 @@ export declare class Balances {
80
80
  * @returns The new collection of balances.
81
81
  */
82
82
  remove: (ids: string[] | string) => Balances;
83
+ get each(): Balance[];
83
84
  /**
84
85
  * Get an array of balances in this collection, sorted by chain sortIndex.
85
86
  *
@@ -6,17 +6,10 @@ var dexie = require('dexie');
6
6
  var types = require('@polkadot/types');
7
7
  var anylogger = require('anylogger');
8
8
  var util = require('@talismn/util');
9
- var memoize = require('lodash/memoize');
10
- var typescriptMemoize = require('typescript-memoize');
11
9
 
12
10
  function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
13
11
 
14
12
  var anylogger__default = /*#__PURE__*/_interopDefault(anylogger);
15
- var memoize__default = /*#__PURE__*/_interopDefault(memoize);
16
-
17
- //
18
- // exported
19
- //
20
13
 
21
14
  // TODO: Document default balances module purpose/usage
22
15
  const DefaultBalanceModule = type => ({
@@ -35,7 +28,7 @@ const DefaultBalanceModule = type => ({
35
28
  async fetchEvmChainTokens() {
36
29
  return Promise.resolve({});
37
30
  },
38
- async subscribeBalances(_chainConnectors, _chaindataProvider, _addressesByToken, callback) {
31
+ async subscribeBalances(_, callback) {
39
32
  callback(new Error("Balance subscriptions are not implemented in this module."));
40
33
  return () => {};
41
34
  },
@@ -74,7 +67,7 @@ const db = new TalismanBalancesDatabase();
74
67
 
75
68
  var packageJson = {
76
69
  name: "@talismn/balances",
77
- version: "0.0.0-pr599-20230306082809",
70
+ version: "0.0.0-pr600-20230307005925",
78
71
  author: "Talisman",
79
72
  homepage: "https://talisman.xyz",
80
73
  license: "UNLICENSED",
@@ -107,9 +100,7 @@ var packageJson = {
107
100
  "@talismn/token-rates": "workspace:^",
108
101
  "@talismn/util": "workspace:^",
109
102
  anylogger: "^1.0.11",
110
- dexie: "^3.2.3",
111
- lodash: "^4.17.21",
112
- "typescript-memoize": "^1.1.0"
103
+ dexie: "^3.2.3"
113
104
  },
114
105
  devDependencies: {
115
106
  "@polkadot/types": "^9.10.5",
@@ -140,13 +131,37 @@ var packageJson = {
140
131
 
141
132
  var log = anylogger__default["default"](packageJson.name);
142
133
 
143
- async function balances(balanceModule, chainConnectors, chaindataProvider, addressesByToken, callback) {
134
+ async function balances(balanceModule, addressesByToken, callback) {
144
135
  // subscription request
145
- if (callback !== undefined) return await balanceModule.subscribeBalances(chainConnectors, chaindataProvider, addressesByToken, callback);
136
+ if (callback !== undefined) return await balanceModule.subscribeBalances(addressesByToken, callback);
146
137
 
147
138
  // one-off request
148
- return await balanceModule.fetchBalances(chainConnectors, chaindataProvider, addressesByToken);
139
+ return await balanceModule.fetchBalances(addressesByToken);
149
140
  }
141
+ const useMetadataCache = () => {
142
+ const metadataCache = new Map();
143
+ const getOrCreateMetadata = (chainId, metadataRpc) => {
144
+ // TODO: Delete cache when metadataRpc is different from last time
145
+ const cached = metadataCache.get(chainId);
146
+ if (cached) return cached;
147
+ const metadata = new types.Metadata(new types.TypeRegistry(), metadataRpc);
148
+ metadata.registry.setMetadata(metadata);
149
+ metadataCache.set(chainId, metadata);
150
+ return metadata;
151
+ };
152
+ return {
153
+ getOrCreateMetadata
154
+ };
155
+ };
156
+ const useTypeRegistryCache = () => {
157
+ const {
158
+ getOrCreateMetadata
159
+ } = useMetadataCache();
160
+ const getOrCreateTypeRegistry = (chainId, metadataRpc) => getOrCreateMetadata(chainId, metadataRpc).registry;
161
+ return {
162
+ getOrCreateTypeRegistry
163
+ };
164
+ };
150
165
  const filterMirrorTokens = (balance, i, balances) => {
151
166
  var _balance$token;
152
167
  // TODO: implement a mirrorOf property, which should be set from chaindata
@@ -236,30 +251,6 @@ class StorageHelper {
236
251
  }
237
252
  }
238
253
 
239
- function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
240
- var desc = {};
241
- Object.keys(descriptor).forEach(function (key) {
242
- desc[key] = descriptor[key];
243
- });
244
- desc.enumerable = !!desc.enumerable;
245
- desc.configurable = !!desc.configurable;
246
- if ('value' in desc || desc.initializer) {
247
- desc.writable = true;
248
- }
249
- desc = decorators.slice().reverse().reduce(function (desc, decorator) {
250
- return decorator(target, property, desc) || desc;
251
- }, desc);
252
- if (context && desc.initializer !== void 0) {
253
- desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
254
- desc.initializer = undefined;
255
- }
256
- if (desc.initializer === void 0) {
257
- Object.defineProperty(target, property, desc);
258
- desc = null;
259
- }
260
- return desc;
261
- }
262
-
263
254
  function excludeFromTransferableAmount(locks) {
264
255
  if (typeof locks === "string") return BigInt(locks);
265
256
  if (!Array.isArray(locks)) locks = [locks];
@@ -281,8 +272,6 @@ function includeInTotalExtraAmount(extra) {
281
272
 
282
273
  /** Used by plugins to help define their custom `BalanceType` */
283
274
 
284
- var _dec, _dec2, _dec3, _class, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10, _class2, _dec11, _class3, _dec12, _dec13, _dec14, _dec15, _dec16, _dec17, _dec18, _class4;
285
-
286
275
  /**
287
276
  * Have the importing library define its Token and BalanceJson enums (as a sum type of all plugins) and pass them into some
288
277
  * internal global typescript context, which is then picked up on by this module.
@@ -293,12 +282,12 @@ var _dec, _dec2, _dec3, _class, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10
293
282
  /**
294
283
  * A collection of balances.
295
284
  */
296
- let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Memoize(), _dec3 = typescriptMemoize.Memoize(), (_class = class Balances {
285
+ class Balances {
297
286
  //
298
287
  // Properties
299
288
  //
300
289
 
301
- #balances = {};
290
+ #balances = [];
302
291
 
303
292
  //
304
293
  // Methods
@@ -306,7 +295,7 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
306
295
 
307
296
  constructor(balances, hydrate) {
308
297
  // handle Balances (convert to Balance[])
309
- if (balances instanceof Balances) return new Balances([...balances], hydrate);
298
+ if (balances instanceof Balances) return new Balances(balances.each, hydrate);
310
299
 
311
300
  // handle Balance (convert to Balance[])
312
301
  if (balances instanceof Balance) return new Balances([balances], hydrate);
@@ -321,19 +310,19 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
321
310
  if (!util.isArrayOf(balances, Balance)) return new Balances(balances.map(storage => new Balance(storage)), hydrate);
322
311
 
323
312
  // handle Balance[]
324
- this.#balances = Object.fromEntries(balances.map(balance => [balance.id, balance]));
313
+ this.#balances = balances;
325
314
  if (hydrate !== undefined) this.hydrate(hydrate);
326
315
  }
327
316
 
328
317
  /**
329
318
  * Calling toJSON on a collection of balances will return the underlying BalanceJsonList.
330
319
  */
331
- toJSON = () => Object.fromEntries(Object.entries(this.#balances).map(([id, balance]) => {
320
+ toJSON = () => Object.fromEntries(this.#balances.map(balance => {
332
321
  try {
333
- return [id, balance.toJSON()];
322
+ return [balance.id, balance.toJSON()];
334
323
  } catch (error) {
335
324
  log.error("Failed to convert balance to JSON", error, {
336
- id,
325
+ id: balance.id,
337
326
  balance
338
327
  });
339
328
  return null;
@@ -353,7 +342,7 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
353
342
  */
354
343
  [Symbol.iterator] = () =>
355
344
  // Create an array of the balances in this collection and return the result of its iterator.
356
- Object.values(this.#balances)[Symbol.iterator]();
345
+ this.#balances[Symbol.iterator]();
357
346
 
358
347
  /**
359
348
  * Hydrates all balances in this collection.
@@ -361,7 +350,7 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
361
350
  * @param sources - The sources to hydrate from.
362
351
  */
363
352
  hydrate = sources => {
364
- Object.values(this.#balances).map(balance => balance.hydrate(sources));
353
+ this.#balances.map(balance => balance.hydrate(sources));
365
354
  };
366
355
 
367
356
  /**
@@ -370,7 +359,7 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
370
359
  * @param id - The id of the balance to fetch.
371
360
  * @returns The balance if one exists, or none.
372
361
  */
373
- get = id => this.#balances[id] || null;
362
+ get = id => this.#balances.find(balance => balance.id === id) ?? null;
374
363
 
375
364
  /**
376
365
  * Retrieve balances from this collection by search query.
@@ -403,10 +392,8 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
403
392
  if (balances instanceof Balance) return this.add(new Balances(balances));
404
393
 
405
394
  // merge balances
406
- const mergedBalances = {
407
- ...this.#balances
408
- };
409
- [...balances].forEach(balance => mergedBalances[balance.id] = balance);
395
+ const mergedBalances = Object.fromEntries(this.#balances.map(balance => [balance.id, balance]));
396
+ balances.each.forEach(balance => mergedBalances[balance.id] = balance);
410
397
 
411
398
  // return new balances
412
399
  return new Balances(Object.values(mergedBalances));
@@ -424,18 +411,16 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
424
411
  // handle single id
425
412
  if (!Array.isArray(ids)) return this.remove([ids]);
426
413
 
427
- // merge balances
428
- const removedBalances = {
429
- ...this.#balances
430
- };
431
- ids.forEach(id => delete removedBalances[id]);
432
-
433
- // return new balances
434
- return new Balances(Object.values(removedBalances));
414
+ // merge and return new balances
415
+ return new Balances(this.#balances.filter(balance => !ids.includes(balance.id)));
435
416
  };
436
417
 
437
418
  // TODO: Add some more useful aggregator methods
438
419
 
420
+ get each() {
421
+ return [...this];
422
+ }
423
+
439
424
  /**
440
425
  * Get an array of balances in this collection, sorted by chain sortIndex.
441
426
  *
@@ -444,7 +429,7 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
444
429
  get sorted() {
445
430
  return [...this].sort((a, b) => {
446
431
  var _ref, _ref2;
447
- return (((_ref = a.chain || a.evmNetwork) === null || _ref === void 0 ? void 0 : _ref.sortIndex) || Number.MAX_SAFE_INTEGER) - (((_ref2 = b.chain || b.evmNetwork) === null || _ref2 === void 0 ? void 0 : _ref2.sortIndex) || Number.MAX_SAFE_INTEGER);
432
+ return (((_ref = a.chain || a.evmNetwork) === null || _ref === void 0 ? void 0 : _ref.sortIndex) ?? Number.MAX_SAFE_INTEGER) - (((_ref2 = b.chain || b.evmNetwork) === null || _ref2 === void 0 ? void 0 : _ref2.sortIndex) ?? Number.MAX_SAFE_INTEGER);
448
433
  });
449
434
  }
450
435
 
@@ -468,12 +453,12 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
468
453
  get sum() {
469
454
  return new SumBalancesFormatter(this);
470
455
  }
471
- }, (_applyDecoratedDescriptor(_class.prototype, "sorted", [_dec], Object.getOwnPropertyDescriptor(_class.prototype, "sorted"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "count", [_dec2], Object.getOwnPropertyDescriptor(_class.prototype, "count"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "sum", [_dec3], Object.getOwnPropertyDescriptor(_class.prototype, "sum"), _class.prototype)), _class));
456
+ }
472
457
 
473
458
  /**
474
459
  * An individual balance.
475
460
  */
476
- let Balance = (_dec4 = typescriptMemoize.Memoize(), _dec5 = typescriptMemoize.Memoize(), _dec6 = typescriptMemoize.Memoize(), _dec7 = typescriptMemoize.Memoize(), _dec8 = typescriptMemoize.Memoize(), _dec9 = typescriptMemoize.Memoize(), _dec10 = typescriptMemoize.Memoize(), (_class2 = class Balance {
461
+ class Balance {
477
462
  //
478
463
  // Properties
479
464
  //
@@ -487,7 +472,6 @@ let Balance = (_dec4 = typescriptMemoize.Memoize(), _dec5 = typescriptMemoize.Me
487
472
  //
488
473
 
489
474
  constructor(storage, hydrate) {
490
- this.#format = memoize__default["default"](this.#format);
491
475
  this.#storage = storage;
492
476
  if (hydrate !== undefined) this.hydrate(hydrate);
493
477
  }
@@ -621,8 +605,8 @@ let Balance = (_dec4 = typescriptMemoize.Memoize(), _dec5 = typescriptMemoize.Me
621
605
  // subtract the lock from the free amount (but don't go below 0)
622
606
  return this.#format(util.BigMath.max(this.free.planck - excludeAmount, BigInt("0")));
623
607
  }
624
- }, (_applyDecoratedDescriptor(_class2.prototype, "total", [_dec4], Object.getOwnPropertyDescriptor(_class2.prototype, "total"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "free", [_dec5], Object.getOwnPropertyDescriptor(_class2.prototype, "free"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "reserved", [_dec6], Object.getOwnPropertyDescriptor(_class2.prototype, "reserved"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "locked", [_dec7], Object.getOwnPropertyDescriptor(_class2.prototype, "locked"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "frozen", [_dec8], Object.getOwnPropertyDescriptor(_class2.prototype, "frozen"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "transferable", [_dec9], Object.getOwnPropertyDescriptor(_class2.prototype, "transferable"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "feePayable", [_dec10], Object.getOwnPropertyDescriptor(_class2.prototype, "feePayable"), _class2.prototype)), _class2));
625
- let BalanceFormatter = (_dec11 = typescriptMemoize.Memoize(), (_class3 = class BalanceFormatter {
608
+ }
609
+ class BalanceFormatter {
626
610
  #planck;
627
611
  #decimals;
628
612
  #fiatRatios;
@@ -630,7 +614,6 @@ let BalanceFormatter = (_dec11 = typescriptMemoize.Memoize(), (_class3 = class B
630
614
  this.#planck = typeof planck === "bigint" ? planck.toString() : planck ?? "0";
631
615
  this.#decimals = decimals || 0;
632
616
  this.#fiatRatios = fiatRatios || null;
633
- this.fiat = memoize__default["default"](this.fiat);
634
617
  }
635
618
  toJSON = () => this.#planck;
636
619
  get planck() {
@@ -645,14 +628,13 @@ let BalanceFormatter = (_dec11 = typescriptMemoize.Memoize(), (_class3 = class B
645
628
  if (!ratio) return null;
646
629
  return parseFloat(this.tokens) * ratio;
647
630
  }
648
- }, (_applyDecoratedDescriptor(_class3.prototype, "tokens", [_dec11], Object.getOwnPropertyDescriptor(_class3.prototype, "tokens"), _class3.prototype)), _class3));
649
- let FiatSumBalancesFormatter = (_dec12 = typescriptMemoize.Memoize(), _dec13 = typescriptMemoize.Memoize(), _dec14 = typescriptMemoize.Memoize(), _dec15 = typescriptMemoize.Memoize(), _dec16 = typescriptMemoize.Memoize(), _dec17 = typescriptMemoize.Memoize(), _dec18 = typescriptMemoize.Memoize(), (_class4 = class FiatSumBalancesFormatter {
631
+ }
632
+ class FiatSumBalancesFormatter {
650
633
  #balances;
651
634
  #currency;
652
635
  constructor(balances, currency) {
653
636
  this.#balances = balances;
654
637
  this.#currency = currency;
655
- this.#sum = memoize__default["default"](this.#sum);
656
638
  }
657
639
  #sum = balanceField => {
658
640
  // a function to get a fiat amount from a balance
@@ -699,12 +681,11 @@ let FiatSumBalancesFormatter = (_dec12 = typescriptMemoize.Memoize(), _dec13 = t
699
681
  get feePayable() {
700
682
  return this.#sum("feePayable");
701
683
  }
702
- }, (_applyDecoratedDescriptor(_class4.prototype, "total", [_dec12], Object.getOwnPropertyDescriptor(_class4.prototype, "total"), _class4.prototype), _applyDecoratedDescriptor(_class4.prototype, "free", [_dec13], Object.getOwnPropertyDescriptor(_class4.prototype, "free"), _class4.prototype), _applyDecoratedDescriptor(_class4.prototype, "reserved", [_dec14], Object.getOwnPropertyDescriptor(_class4.prototype, "reserved"), _class4.prototype), _applyDecoratedDescriptor(_class4.prototype, "locked", [_dec15], Object.getOwnPropertyDescriptor(_class4.prototype, "locked"), _class4.prototype), _applyDecoratedDescriptor(_class4.prototype, "frozen", [_dec16], Object.getOwnPropertyDescriptor(_class4.prototype, "frozen"), _class4.prototype), _applyDecoratedDescriptor(_class4.prototype, "transferable", [_dec17], Object.getOwnPropertyDescriptor(_class4.prototype, "transferable"), _class4.prototype), _applyDecoratedDescriptor(_class4.prototype, "feePayable", [_dec18], Object.getOwnPropertyDescriptor(_class4.prototype, "feePayable"), _class4.prototype)), _class4));
684
+ }
703
685
  class SumBalancesFormatter {
704
686
  #balances;
705
687
  constructor(balances) {
706
688
  this.#balances = balances;
707
- this.fiat = memoize__default["default"](this.fiat);
708
689
  }
709
690
  fiat(currency) {
710
691
  return new FiatSumBalancesFormatter(this.#balances, currency);
@@ -725,3 +706,5 @@ exports.excludeFromFeePayableLocks = excludeFromFeePayableLocks;
725
706
  exports.excludeFromTransferableAmount = excludeFromTransferableAmount;
726
707
  exports.filterMirrorTokens = filterMirrorTokens;
727
708
  exports.includeInTotalExtraAmount = includeInTotalExtraAmount;
709
+ exports.useMetadataCache = useMetadataCache;
710
+ exports.useTypeRegistryCache = useTypeRegistryCache;
@@ -6,17 +6,10 @@ var dexie = require('dexie');
6
6
  var types = require('@polkadot/types');
7
7
  var anylogger = require('anylogger');
8
8
  var util = require('@talismn/util');
9
- var memoize = require('lodash/memoize');
10
- var typescriptMemoize = require('typescript-memoize');
11
9
 
12
10
  function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
13
11
 
14
12
  var anylogger__default = /*#__PURE__*/_interopDefault(anylogger);
15
- var memoize__default = /*#__PURE__*/_interopDefault(memoize);
16
-
17
- //
18
- // exported
19
- //
20
13
 
21
14
  // TODO: Document default balances module purpose/usage
22
15
  const DefaultBalanceModule = type => ({
@@ -35,7 +28,7 @@ const DefaultBalanceModule = type => ({
35
28
  async fetchEvmChainTokens() {
36
29
  return Promise.resolve({});
37
30
  },
38
- async subscribeBalances(_chainConnectors, _chaindataProvider, _addressesByToken, callback) {
31
+ async subscribeBalances(_, callback) {
39
32
  callback(new Error("Balance subscriptions are not implemented in this module."));
40
33
  return () => {};
41
34
  },
@@ -74,7 +67,7 @@ const db = new TalismanBalancesDatabase();
74
67
 
75
68
  var packageJson = {
76
69
  name: "@talismn/balances",
77
- version: "0.0.0-pr599-20230306082809",
70
+ version: "0.0.0-pr600-20230307005925",
78
71
  author: "Talisman",
79
72
  homepage: "https://talisman.xyz",
80
73
  license: "UNLICENSED",
@@ -107,9 +100,7 @@ var packageJson = {
107
100
  "@talismn/token-rates": "workspace:^",
108
101
  "@talismn/util": "workspace:^",
109
102
  anylogger: "^1.0.11",
110
- dexie: "^3.2.3",
111
- lodash: "^4.17.21",
112
- "typescript-memoize": "^1.1.0"
103
+ dexie: "^3.2.3"
113
104
  },
114
105
  devDependencies: {
115
106
  "@polkadot/types": "^9.10.5",
@@ -140,13 +131,37 @@ var packageJson = {
140
131
 
141
132
  var log = anylogger__default["default"](packageJson.name);
142
133
 
143
- async function balances(balanceModule, chainConnectors, chaindataProvider, addressesByToken, callback) {
134
+ async function balances(balanceModule, addressesByToken, callback) {
144
135
  // subscription request
145
- if (callback !== undefined) return await balanceModule.subscribeBalances(chainConnectors, chaindataProvider, addressesByToken, callback);
136
+ if (callback !== undefined) return await balanceModule.subscribeBalances(addressesByToken, callback);
146
137
 
147
138
  // one-off request
148
- return await balanceModule.fetchBalances(chainConnectors, chaindataProvider, addressesByToken);
139
+ return await balanceModule.fetchBalances(addressesByToken);
149
140
  }
141
+ const useMetadataCache = () => {
142
+ const metadataCache = new Map();
143
+ const getOrCreateMetadata = (chainId, metadataRpc) => {
144
+ // TODO: Delete cache when metadataRpc is different from last time
145
+ const cached = metadataCache.get(chainId);
146
+ if (cached) return cached;
147
+ const metadata = new types.Metadata(new types.TypeRegistry(), metadataRpc);
148
+ metadata.registry.setMetadata(metadata);
149
+ metadataCache.set(chainId, metadata);
150
+ return metadata;
151
+ };
152
+ return {
153
+ getOrCreateMetadata
154
+ };
155
+ };
156
+ const useTypeRegistryCache = () => {
157
+ const {
158
+ getOrCreateMetadata
159
+ } = useMetadataCache();
160
+ const getOrCreateTypeRegistry = (chainId, metadataRpc) => getOrCreateMetadata(chainId, metadataRpc).registry;
161
+ return {
162
+ getOrCreateTypeRegistry
163
+ };
164
+ };
150
165
  const filterMirrorTokens = (balance, i, balances) => {
151
166
  var _balance$token;
152
167
  // TODO: implement a mirrorOf property, which should be set from chaindata
@@ -236,30 +251,6 @@ class StorageHelper {
236
251
  }
237
252
  }
238
253
 
239
- function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
240
- var desc = {};
241
- Object.keys(descriptor).forEach(function (key) {
242
- desc[key] = descriptor[key];
243
- });
244
- desc.enumerable = !!desc.enumerable;
245
- desc.configurable = !!desc.configurable;
246
- if ('value' in desc || desc.initializer) {
247
- desc.writable = true;
248
- }
249
- desc = decorators.slice().reverse().reduce(function (desc, decorator) {
250
- return decorator(target, property, desc) || desc;
251
- }, desc);
252
- if (context && desc.initializer !== void 0) {
253
- desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
254
- desc.initializer = undefined;
255
- }
256
- if (desc.initializer === void 0) {
257
- Object.defineProperty(target, property, desc);
258
- desc = null;
259
- }
260
- return desc;
261
- }
262
-
263
254
  function excludeFromTransferableAmount(locks) {
264
255
  if (typeof locks === "string") return BigInt(locks);
265
256
  if (!Array.isArray(locks)) locks = [locks];
@@ -281,8 +272,6 @@ function includeInTotalExtraAmount(extra) {
281
272
 
282
273
  /** Used by plugins to help define their custom `BalanceType` */
283
274
 
284
- var _dec, _dec2, _dec3, _class, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10, _class2, _dec11, _class3, _dec12, _dec13, _dec14, _dec15, _dec16, _dec17, _dec18, _class4;
285
-
286
275
  /**
287
276
  * Have the importing library define its Token and BalanceJson enums (as a sum type of all plugins) and pass them into some
288
277
  * internal global typescript context, which is then picked up on by this module.
@@ -293,12 +282,12 @@ var _dec, _dec2, _dec3, _class, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10
293
282
  /**
294
283
  * A collection of balances.
295
284
  */
296
- let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Memoize(), _dec3 = typescriptMemoize.Memoize(), (_class = class Balances {
285
+ class Balances {
297
286
  //
298
287
  // Properties
299
288
  //
300
289
 
301
- #balances = {};
290
+ #balances = [];
302
291
 
303
292
  //
304
293
  // Methods
@@ -306,7 +295,7 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
306
295
 
307
296
  constructor(balances, hydrate) {
308
297
  // handle Balances (convert to Balance[])
309
- if (balances instanceof Balances) return new Balances([...balances], hydrate);
298
+ if (balances instanceof Balances) return new Balances(balances.each, hydrate);
310
299
 
311
300
  // handle Balance (convert to Balance[])
312
301
  if (balances instanceof Balance) return new Balances([balances], hydrate);
@@ -321,19 +310,19 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
321
310
  if (!util.isArrayOf(balances, Balance)) return new Balances(balances.map(storage => new Balance(storage)), hydrate);
322
311
 
323
312
  // handle Balance[]
324
- this.#balances = Object.fromEntries(balances.map(balance => [balance.id, balance]));
313
+ this.#balances = balances;
325
314
  if (hydrate !== undefined) this.hydrate(hydrate);
326
315
  }
327
316
 
328
317
  /**
329
318
  * Calling toJSON on a collection of balances will return the underlying BalanceJsonList.
330
319
  */
331
- toJSON = () => Object.fromEntries(Object.entries(this.#balances).map(([id, balance]) => {
320
+ toJSON = () => Object.fromEntries(this.#balances.map(balance => {
332
321
  try {
333
- return [id, balance.toJSON()];
322
+ return [balance.id, balance.toJSON()];
334
323
  } catch (error) {
335
324
  log.error("Failed to convert balance to JSON", error, {
336
- id,
325
+ id: balance.id,
337
326
  balance
338
327
  });
339
328
  return null;
@@ -353,7 +342,7 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
353
342
  */
354
343
  [Symbol.iterator] = () =>
355
344
  // Create an array of the balances in this collection and return the result of its iterator.
356
- Object.values(this.#balances)[Symbol.iterator]();
345
+ this.#balances[Symbol.iterator]();
357
346
 
358
347
  /**
359
348
  * Hydrates all balances in this collection.
@@ -361,7 +350,7 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
361
350
  * @param sources - The sources to hydrate from.
362
351
  */
363
352
  hydrate = sources => {
364
- Object.values(this.#balances).map(balance => balance.hydrate(sources));
353
+ this.#balances.map(balance => balance.hydrate(sources));
365
354
  };
366
355
 
367
356
  /**
@@ -370,7 +359,7 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
370
359
  * @param id - The id of the balance to fetch.
371
360
  * @returns The balance if one exists, or none.
372
361
  */
373
- get = id => this.#balances[id] || null;
362
+ get = id => this.#balances.find(balance => balance.id === id) ?? null;
374
363
 
375
364
  /**
376
365
  * Retrieve balances from this collection by search query.
@@ -403,10 +392,8 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
403
392
  if (balances instanceof Balance) return this.add(new Balances(balances));
404
393
 
405
394
  // merge balances
406
- const mergedBalances = {
407
- ...this.#balances
408
- };
409
- [...balances].forEach(balance => mergedBalances[balance.id] = balance);
395
+ const mergedBalances = Object.fromEntries(this.#balances.map(balance => [balance.id, balance]));
396
+ balances.each.forEach(balance => mergedBalances[balance.id] = balance);
410
397
 
411
398
  // return new balances
412
399
  return new Balances(Object.values(mergedBalances));
@@ -424,18 +411,16 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
424
411
  // handle single id
425
412
  if (!Array.isArray(ids)) return this.remove([ids]);
426
413
 
427
- // merge balances
428
- const removedBalances = {
429
- ...this.#balances
430
- };
431
- ids.forEach(id => delete removedBalances[id]);
432
-
433
- // return new balances
434
- return new Balances(Object.values(removedBalances));
414
+ // merge and return new balances
415
+ return new Balances(this.#balances.filter(balance => !ids.includes(balance.id)));
435
416
  };
436
417
 
437
418
  // TODO: Add some more useful aggregator methods
438
419
 
420
+ get each() {
421
+ return [...this];
422
+ }
423
+
439
424
  /**
440
425
  * Get an array of balances in this collection, sorted by chain sortIndex.
441
426
  *
@@ -444,7 +429,7 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
444
429
  get sorted() {
445
430
  return [...this].sort((a, b) => {
446
431
  var _ref, _ref2;
447
- return (((_ref = a.chain || a.evmNetwork) === null || _ref === void 0 ? void 0 : _ref.sortIndex) || Number.MAX_SAFE_INTEGER) - (((_ref2 = b.chain || b.evmNetwork) === null || _ref2 === void 0 ? void 0 : _ref2.sortIndex) || Number.MAX_SAFE_INTEGER);
432
+ return (((_ref = a.chain || a.evmNetwork) === null || _ref === void 0 ? void 0 : _ref.sortIndex) ?? Number.MAX_SAFE_INTEGER) - (((_ref2 = b.chain || b.evmNetwork) === null || _ref2 === void 0 ? void 0 : _ref2.sortIndex) ?? Number.MAX_SAFE_INTEGER);
448
433
  });
449
434
  }
450
435
 
@@ -468,12 +453,12 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
468
453
  get sum() {
469
454
  return new SumBalancesFormatter(this);
470
455
  }
471
- }, (_applyDecoratedDescriptor(_class.prototype, "sorted", [_dec], Object.getOwnPropertyDescriptor(_class.prototype, "sorted"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "count", [_dec2], Object.getOwnPropertyDescriptor(_class.prototype, "count"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "sum", [_dec3], Object.getOwnPropertyDescriptor(_class.prototype, "sum"), _class.prototype)), _class));
456
+ }
472
457
 
473
458
  /**
474
459
  * An individual balance.
475
460
  */
476
- let Balance = (_dec4 = typescriptMemoize.Memoize(), _dec5 = typescriptMemoize.Memoize(), _dec6 = typescriptMemoize.Memoize(), _dec7 = typescriptMemoize.Memoize(), _dec8 = typescriptMemoize.Memoize(), _dec9 = typescriptMemoize.Memoize(), _dec10 = typescriptMemoize.Memoize(), (_class2 = class Balance {
461
+ class Balance {
477
462
  //
478
463
  // Properties
479
464
  //
@@ -487,7 +472,6 @@ let Balance = (_dec4 = typescriptMemoize.Memoize(), _dec5 = typescriptMemoize.Me
487
472
  //
488
473
 
489
474
  constructor(storage, hydrate) {
490
- this.#format = memoize__default["default"](this.#format);
491
475
  this.#storage = storage;
492
476
  if (hydrate !== undefined) this.hydrate(hydrate);
493
477
  }
@@ -621,8 +605,8 @@ let Balance = (_dec4 = typescriptMemoize.Memoize(), _dec5 = typescriptMemoize.Me
621
605
  // subtract the lock from the free amount (but don't go below 0)
622
606
  return this.#format(util.BigMath.max(this.free.planck - excludeAmount, BigInt("0")));
623
607
  }
624
- }, (_applyDecoratedDescriptor(_class2.prototype, "total", [_dec4], Object.getOwnPropertyDescriptor(_class2.prototype, "total"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "free", [_dec5], Object.getOwnPropertyDescriptor(_class2.prototype, "free"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "reserved", [_dec6], Object.getOwnPropertyDescriptor(_class2.prototype, "reserved"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "locked", [_dec7], Object.getOwnPropertyDescriptor(_class2.prototype, "locked"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "frozen", [_dec8], Object.getOwnPropertyDescriptor(_class2.prototype, "frozen"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "transferable", [_dec9], Object.getOwnPropertyDescriptor(_class2.prototype, "transferable"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "feePayable", [_dec10], Object.getOwnPropertyDescriptor(_class2.prototype, "feePayable"), _class2.prototype)), _class2));
625
- let BalanceFormatter = (_dec11 = typescriptMemoize.Memoize(), (_class3 = class BalanceFormatter {
608
+ }
609
+ class BalanceFormatter {
626
610
  #planck;
627
611
  #decimals;
628
612
  #fiatRatios;
@@ -630,7 +614,6 @@ let BalanceFormatter = (_dec11 = typescriptMemoize.Memoize(), (_class3 = class B
630
614
  this.#planck = typeof planck === "bigint" ? planck.toString() : planck ?? "0";
631
615
  this.#decimals = decimals || 0;
632
616
  this.#fiatRatios = fiatRatios || null;
633
- this.fiat = memoize__default["default"](this.fiat);
634
617
  }
635
618
  toJSON = () => this.#planck;
636
619
  get planck() {
@@ -645,14 +628,13 @@ let BalanceFormatter = (_dec11 = typescriptMemoize.Memoize(), (_class3 = class B
645
628
  if (!ratio) return null;
646
629
  return parseFloat(this.tokens) * ratio;
647
630
  }
648
- }, (_applyDecoratedDescriptor(_class3.prototype, "tokens", [_dec11], Object.getOwnPropertyDescriptor(_class3.prototype, "tokens"), _class3.prototype)), _class3));
649
- let FiatSumBalancesFormatter = (_dec12 = typescriptMemoize.Memoize(), _dec13 = typescriptMemoize.Memoize(), _dec14 = typescriptMemoize.Memoize(), _dec15 = typescriptMemoize.Memoize(), _dec16 = typescriptMemoize.Memoize(), _dec17 = typescriptMemoize.Memoize(), _dec18 = typescriptMemoize.Memoize(), (_class4 = class FiatSumBalancesFormatter {
631
+ }
632
+ class FiatSumBalancesFormatter {
650
633
  #balances;
651
634
  #currency;
652
635
  constructor(balances, currency) {
653
636
  this.#balances = balances;
654
637
  this.#currency = currency;
655
- this.#sum = memoize__default["default"](this.#sum);
656
638
  }
657
639
  #sum = balanceField => {
658
640
  // a function to get a fiat amount from a balance
@@ -699,12 +681,11 @@ let FiatSumBalancesFormatter = (_dec12 = typescriptMemoize.Memoize(), _dec13 = t
699
681
  get feePayable() {
700
682
  return this.#sum("feePayable");
701
683
  }
702
- }, (_applyDecoratedDescriptor(_class4.prototype, "total", [_dec12], Object.getOwnPropertyDescriptor(_class4.prototype, "total"), _class4.prototype), _applyDecoratedDescriptor(_class4.prototype, "free", [_dec13], Object.getOwnPropertyDescriptor(_class4.prototype, "free"), _class4.prototype), _applyDecoratedDescriptor(_class4.prototype, "reserved", [_dec14], Object.getOwnPropertyDescriptor(_class4.prototype, "reserved"), _class4.prototype), _applyDecoratedDescriptor(_class4.prototype, "locked", [_dec15], Object.getOwnPropertyDescriptor(_class4.prototype, "locked"), _class4.prototype), _applyDecoratedDescriptor(_class4.prototype, "frozen", [_dec16], Object.getOwnPropertyDescriptor(_class4.prototype, "frozen"), _class4.prototype), _applyDecoratedDescriptor(_class4.prototype, "transferable", [_dec17], Object.getOwnPropertyDescriptor(_class4.prototype, "transferable"), _class4.prototype), _applyDecoratedDescriptor(_class4.prototype, "feePayable", [_dec18], Object.getOwnPropertyDescriptor(_class4.prototype, "feePayable"), _class4.prototype)), _class4));
684
+ }
703
685
  class SumBalancesFormatter {
704
686
  #balances;
705
687
  constructor(balances) {
706
688
  this.#balances = balances;
707
- this.fiat = memoize__default["default"](this.fiat);
708
689
  }
709
690
  fiat(currency) {
710
691
  return new FiatSumBalancesFormatter(this.#balances, currency);
@@ -725,3 +706,5 @@ exports.excludeFromFeePayableLocks = excludeFromFeePayableLocks;
725
706
  exports.excludeFromTransferableAmount = excludeFromTransferableAmount;
726
707
  exports.filterMirrorTokens = filterMirrorTokens;
727
708
  exports.includeInTotalExtraAmount = includeInTotalExtraAmount;
709
+ exports.useMetadataCache = useMetadataCache;
710
+ exports.useTypeRegistryCache = useTypeRegistryCache;
@@ -1,13 +1,7 @@
1
1
  import { Dexie } from 'dexie';
2
- import { decorateStorage, StorageKey } from '@polkadot/types';
2
+ import { decorateStorage, StorageKey, Metadata, TypeRegistry } from '@polkadot/types';
3
3
  import anylogger from 'anylogger';
4
4
  import { BigMath, isArrayOf, planckToTokens } from '@talismn/util';
5
- import memoize from 'lodash/memoize';
6
- import { Memoize } from 'typescript-memoize';
7
-
8
- //
9
- // exported
10
- //
11
5
 
12
6
  // TODO: Document default balances module purpose/usage
13
7
  const DefaultBalanceModule = type => ({
@@ -26,7 +20,7 @@ const DefaultBalanceModule = type => ({
26
20
  async fetchEvmChainTokens() {
27
21
  return Promise.resolve({});
28
22
  },
29
- async subscribeBalances(_chainConnectors, _chaindataProvider, _addressesByToken, callback) {
23
+ async subscribeBalances(_, callback) {
30
24
  callback(new Error("Balance subscriptions are not implemented in this module."));
31
25
  return () => {};
32
26
  },
@@ -65,7 +59,7 @@ const db = new TalismanBalancesDatabase();
65
59
 
66
60
  var packageJson = {
67
61
  name: "@talismn/balances",
68
- version: "0.0.0-pr599-20230306082809",
62
+ version: "0.0.0-pr600-20230307005925",
69
63
  author: "Talisman",
70
64
  homepage: "https://talisman.xyz",
71
65
  license: "UNLICENSED",
@@ -98,9 +92,7 @@ var packageJson = {
98
92
  "@talismn/token-rates": "workspace:^",
99
93
  "@talismn/util": "workspace:^",
100
94
  anylogger: "^1.0.11",
101
- dexie: "^3.2.3",
102
- lodash: "^4.17.21",
103
- "typescript-memoize": "^1.1.0"
95
+ dexie: "^3.2.3"
104
96
  },
105
97
  devDependencies: {
106
98
  "@polkadot/types": "^9.10.5",
@@ -131,13 +123,37 @@ var packageJson = {
131
123
 
132
124
  var log = anylogger(packageJson.name);
133
125
 
134
- async function balances(balanceModule, chainConnectors, chaindataProvider, addressesByToken, callback) {
126
+ async function balances(balanceModule, addressesByToken, callback) {
135
127
  // subscription request
136
- if (callback !== undefined) return await balanceModule.subscribeBalances(chainConnectors, chaindataProvider, addressesByToken, callback);
128
+ if (callback !== undefined) return await balanceModule.subscribeBalances(addressesByToken, callback);
137
129
 
138
130
  // one-off request
139
- return await balanceModule.fetchBalances(chainConnectors, chaindataProvider, addressesByToken);
131
+ return await balanceModule.fetchBalances(addressesByToken);
140
132
  }
133
+ const useMetadataCache = () => {
134
+ const metadataCache = new Map();
135
+ const getOrCreateMetadata = (chainId, metadataRpc) => {
136
+ // TODO: Delete cache when metadataRpc is different from last time
137
+ const cached = metadataCache.get(chainId);
138
+ if (cached) return cached;
139
+ const metadata = new Metadata(new TypeRegistry(), metadataRpc);
140
+ metadata.registry.setMetadata(metadata);
141
+ metadataCache.set(chainId, metadata);
142
+ return metadata;
143
+ };
144
+ return {
145
+ getOrCreateMetadata
146
+ };
147
+ };
148
+ const useTypeRegistryCache = () => {
149
+ const {
150
+ getOrCreateMetadata
151
+ } = useMetadataCache();
152
+ const getOrCreateTypeRegistry = (chainId, metadataRpc) => getOrCreateMetadata(chainId, metadataRpc).registry;
153
+ return {
154
+ getOrCreateTypeRegistry
155
+ };
156
+ };
141
157
  const filterMirrorTokens = (balance, i, balances) => {
142
158
  var _balance$token;
143
159
  // TODO: implement a mirrorOf property, which should be set from chaindata
@@ -227,30 +243,6 @@ class StorageHelper {
227
243
  }
228
244
  }
229
245
 
230
- function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
231
- var desc = {};
232
- Object.keys(descriptor).forEach(function (key) {
233
- desc[key] = descriptor[key];
234
- });
235
- desc.enumerable = !!desc.enumerable;
236
- desc.configurable = !!desc.configurable;
237
- if ('value' in desc || desc.initializer) {
238
- desc.writable = true;
239
- }
240
- desc = decorators.slice().reverse().reduce(function (desc, decorator) {
241
- return decorator(target, property, desc) || desc;
242
- }, desc);
243
- if (context && desc.initializer !== void 0) {
244
- desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
245
- desc.initializer = undefined;
246
- }
247
- if (desc.initializer === void 0) {
248
- Object.defineProperty(target, property, desc);
249
- desc = null;
250
- }
251
- return desc;
252
- }
253
-
254
246
  function excludeFromTransferableAmount(locks) {
255
247
  if (typeof locks === "string") return BigInt(locks);
256
248
  if (!Array.isArray(locks)) locks = [locks];
@@ -272,8 +264,6 @@ function includeInTotalExtraAmount(extra) {
272
264
 
273
265
  /** Used by plugins to help define their custom `BalanceType` */
274
266
 
275
- var _dec, _dec2, _dec3, _class, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10, _class2, _dec11, _class3, _dec12, _dec13, _dec14, _dec15, _dec16, _dec17, _dec18, _class4;
276
-
277
267
  /**
278
268
  * Have the importing library define its Token and BalanceJson enums (as a sum type of all plugins) and pass them into some
279
269
  * internal global typescript context, which is then picked up on by this module.
@@ -284,12 +274,12 @@ var _dec, _dec2, _dec3, _class, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10
284
274
  /**
285
275
  * A collection of balances.
286
276
  */
287
- let Balances = (_dec = Memoize(), _dec2 = Memoize(), _dec3 = Memoize(), (_class = class Balances {
277
+ class Balances {
288
278
  //
289
279
  // Properties
290
280
  //
291
281
 
292
- #balances = {};
282
+ #balances = [];
293
283
 
294
284
  //
295
285
  // Methods
@@ -297,7 +287,7 @@ let Balances = (_dec = Memoize(), _dec2 = Memoize(), _dec3 = Memoize(), (_class
297
287
 
298
288
  constructor(balances, hydrate) {
299
289
  // handle Balances (convert to Balance[])
300
- if (balances instanceof Balances) return new Balances([...balances], hydrate);
290
+ if (balances instanceof Balances) return new Balances(balances.each, hydrate);
301
291
 
302
292
  // handle Balance (convert to Balance[])
303
293
  if (balances instanceof Balance) return new Balances([balances], hydrate);
@@ -312,19 +302,19 @@ let Balances = (_dec = Memoize(), _dec2 = Memoize(), _dec3 = Memoize(), (_class
312
302
  if (!isArrayOf(balances, Balance)) return new Balances(balances.map(storage => new Balance(storage)), hydrate);
313
303
 
314
304
  // handle Balance[]
315
- this.#balances = Object.fromEntries(balances.map(balance => [balance.id, balance]));
305
+ this.#balances = balances;
316
306
  if (hydrate !== undefined) this.hydrate(hydrate);
317
307
  }
318
308
 
319
309
  /**
320
310
  * Calling toJSON on a collection of balances will return the underlying BalanceJsonList.
321
311
  */
322
- toJSON = () => Object.fromEntries(Object.entries(this.#balances).map(([id, balance]) => {
312
+ toJSON = () => Object.fromEntries(this.#balances.map(balance => {
323
313
  try {
324
- return [id, balance.toJSON()];
314
+ return [balance.id, balance.toJSON()];
325
315
  } catch (error) {
326
316
  log.error("Failed to convert balance to JSON", error, {
327
- id,
317
+ id: balance.id,
328
318
  balance
329
319
  });
330
320
  return null;
@@ -344,7 +334,7 @@ let Balances = (_dec = Memoize(), _dec2 = Memoize(), _dec3 = Memoize(), (_class
344
334
  */
345
335
  [Symbol.iterator] = () =>
346
336
  // Create an array of the balances in this collection and return the result of its iterator.
347
- Object.values(this.#balances)[Symbol.iterator]();
337
+ this.#balances[Symbol.iterator]();
348
338
 
349
339
  /**
350
340
  * Hydrates all balances in this collection.
@@ -352,7 +342,7 @@ let Balances = (_dec = Memoize(), _dec2 = Memoize(), _dec3 = Memoize(), (_class
352
342
  * @param sources - The sources to hydrate from.
353
343
  */
354
344
  hydrate = sources => {
355
- Object.values(this.#balances).map(balance => balance.hydrate(sources));
345
+ this.#balances.map(balance => balance.hydrate(sources));
356
346
  };
357
347
 
358
348
  /**
@@ -361,7 +351,7 @@ let Balances = (_dec = Memoize(), _dec2 = Memoize(), _dec3 = Memoize(), (_class
361
351
  * @param id - The id of the balance to fetch.
362
352
  * @returns The balance if one exists, or none.
363
353
  */
364
- get = id => this.#balances[id] || null;
354
+ get = id => this.#balances.find(balance => balance.id === id) ?? null;
365
355
 
366
356
  /**
367
357
  * Retrieve balances from this collection by search query.
@@ -394,10 +384,8 @@ let Balances = (_dec = Memoize(), _dec2 = Memoize(), _dec3 = Memoize(), (_class
394
384
  if (balances instanceof Balance) return this.add(new Balances(balances));
395
385
 
396
386
  // merge balances
397
- const mergedBalances = {
398
- ...this.#balances
399
- };
400
- [...balances].forEach(balance => mergedBalances[balance.id] = balance);
387
+ const mergedBalances = Object.fromEntries(this.#balances.map(balance => [balance.id, balance]));
388
+ balances.each.forEach(balance => mergedBalances[balance.id] = balance);
401
389
 
402
390
  // return new balances
403
391
  return new Balances(Object.values(mergedBalances));
@@ -415,18 +403,16 @@ let Balances = (_dec = Memoize(), _dec2 = Memoize(), _dec3 = Memoize(), (_class
415
403
  // handle single id
416
404
  if (!Array.isArray(ids)) return this.remove([ids]);
417
405
 
418
- // merge balances
419
- const removedBalances = {
420
- ...this.#balances
421
- };
422
- ids.forEach(id => delete removedBalances[id]);
423
-
424
- // return new balances
425
- return new Balances(Object.values(removedBalances));
406
+ // merge and return new balances
407
+ return new Balances(this.#balances.filter(balance => !ids.includes(balance.id)));
426
408
  };
427
409
 
428
410
  // TODO: Add some more useful aggregator methods
429
411
 
412
+ get each() {
413
+ return [...this];
414
+ }
415
+
430
416
  /**
431
417
  * Get an array of balances in this collection, sorted by chain sortIndex.
432
418
  *
@@ -435,7 +421,7 @@ let Balances = (_dec = Memoize(), _dec2 = Memoize(), _dec3 = Memoize(), (_class
435
421
  get sorted() {
436
422
  return [...this].sort((a, b) => {
437
423
  var _ref, _ref2;
438
- return (((_ref = a.chain || a.evmNetwork) === null || _ref === void 0 ? void 0 : _ref.sortIndex) || Number.MAX_SAFE_INTEGER) - (((_ref2 = b.chain || b.evmNetwork) === null || _ref2 === void 0 ? void 0 : _ref2.sortIndex) || Number.MAX_SAFE_INTEGER);
424
+ return (((_ref = a.chain || a.evmNetwork) === null || _ref === void 0 ? void 0 : _ref.sortIndex) ?? Number.MAX_SAFE_INTEGER) - (((_ref2 = b.chain || b.evmNetwork) === null || _ref2 === void 0 ? void 0 : _ref2.sortIndex) ?? Number.MAX_SAFE_INTEGER);
439
425
  });
440
426
  }
441
427
 
@@ -459,12 +445,12 @@ let Balances = (_dec = Memoize(), _dec2 = Memoize(), _dec3 = Memoize(), (_class
459
445
  get sum() {
460
446
  return new SumBalancesFormatter(this);
461
447
  }
462
- }, (_applyDecoratedDescriptor(_class.prototype, "sorted", [_dec], Object.getOwnPropertyDescriptor(_class.prototype, "sorted"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "count", [_dec2], Object.getOwnPropertyDescriptor(_class.prototype, "count"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "sum", [_dec3], Object.getOwnPropertyDescriptor(_class.prototype, "sum"), _class.prototype)), _class));
448
+ }
463
449
 
464
450
  /**
465
451
  * An individual balance.
466
452
  */
467
- let Balance = (_dec4 = Memoize(), _dec5 = Memoize(), _dec6 = Memoize(), _dec7 = Memoize(), _dec8 = Memoize(), _dec9 = Memoize(), _dec10 = Memoize(), (_class2 = class Balance {
453
+ class Balance {
468
454
  //
469
455
  // Properties
470
456
  //
@@ -478,7 +464,6 @@ let Balance = (_dec4 = Memoize(), _dec5 = Memoize(), _dec6 = Memoize(), _dec7 =
478
464
  //
479
465
 
480
466
  constructor(storage, hydrate) {
481
- this.#format = memoize(this.#format);
482
467
  this.#storage = storage;
483
468
  if (hydrate !== undefined) this.hydrate(hydrate);
484
469
  }
@@ -612,8 +597,8 @@ let Balance = (_dec4 = Memoize(), _dec5 = Memoize(), _dec6 = Memoize(), _dec7 =
612
597
  // subtract the lock from the free amount (but don't go below 0)
613
598
  return this.#format(BigMath.max(this.free.planck - excludeAmount, BigInt("0")));
614
599
  }
615
- }, (_applyDecoratedDescriptor(_class2.prototype, "total", [_dec4], Object.getOwnPropertyDescriptor(_class2.prototype, "total"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "free", [_dec5], Object.getOwnPropertyDescriptor(_class2.prototype, "free"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "reserved", [_dec6], Object.getOwnPropertyDescriptor(_class2.prototype, "reserved"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "locked", [_dec7], Object.getOwnPropertyDescriptor(_class2.prototype, "locked"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "frozen", [_dec8], Object.getOwnPropertyDescriptor(_class2.prototype, "frozen"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "transferable", [_dec9], Object.getOwnPropertyDescriptor(_class2.prototype, "transferable"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "feePayable", [_dec10], Object.getOwnPropertyDescriptor(_class2.prototype, "feePayable"), _class2.prototype)), _class2));
616
- let BalanceFormatter = (_dec11 = Memoize(), (_class3 = class BalanceFormatter {
600
+ }
601
+ class BalanceFormatter {
617
602
  #planck;
618
603
  #decimals;
619
604
  #fiatRatios;
@@ -621,7 +606,6 @@ let BalanceFormatter = (_dec11 = Memoize(), (_class3 = class BalanceFormatter {
621
606
  this.#planck = typeof planck === "bigint" ? planck.toString() : planck ?? "0";
622
607
  this.#decimals = decimals || 0;
623
608
  this.#fiatRatios = fiatRatios || null;
624
- this.fiat = memoize(this.fiat);
625
609
  }
626
610
  toJSON = () => this.#planck;
627
611
  get planck() {
@@ -636,14 +620,13 @@ let BalanceFormatter = (_dec11 = Memoize(), (_class3 = class BalanceFormatter {
636
620
  if (!ratio) return null;
637
621
  return parseFloat(this.tokens) * ratio;
638
622
  }
639
- }, (_applyDecoratedDescriptor(_class3.prototype, "tokens", [_dec11], Object.getOwnPropertyDescriptor(_class3.prototype, "tokens"), _class3.prototype)), _class3));
640
- let FiatSumBalancesFormatter = (_dec12 = Memoize(), _dec13 = Memoize(), _dec14 = Memoize(), _dec15 = Memoize(), _dec16 = Memoize(), _dec17 = Memoize(), _dec18 = Memoize(), (_class4 = class FiatSumBalancesFormatter {
623
+ }
624
+ class FiatSumBalancesFormatter {
641
625
  #balances;
642
626
  #currency;
643
627
  constructor(balances, currency) {
644
628
  this.#balances = balances;
645
629
  this.#currency = currency;
646
- this.#sum = memoize(this.#sum);
647
630
  }
648
631
  #sum = balanceField => {
649
632
  // a function to get a fiat amount from a balance
@@ -690,16 +673,15 @@ let FiatSumBalancesFormatter = (_dec12 = Memoize(), _dec13 = Memoize(), _dec14 =
690
673
  get feePayable() {
691
674
  return this.#sum("feePayable");
692
675
  }
693
- }, (_applyDecoratedDescriptor(_class4.prototype, "total", [_dec12], Object.getOwnPropertyDescriptor(_class4.prototype, "total"), _class4.prototype), _applyDecoratedDescriptor(_class4.prototype, "free", [_dec13], Object.getOwnPropertyDescriptor(_class4.prototype, "free"), _class4.prototype), _applyDecoratedDescriptor(_class4.prototype, "reserved", [_dec14], Object.getOwnPropertyDescriptor(_class4.prototype, "reserved"), _class4.prototype), _applyDecoratedDescriptor(_class4.prototype, "locked", [_dec15], Object.getOwnPropertyDescriptor(_class4.prototype, "locked"), _class4.prototype), _applyDecoratedDescriptor(_class4.prototype, "frozen", [_dec16], Object.getOwnPropertyDescriptor(_class4.prototype, "frozen"), _class4.prototype), _applyDecoratedDescriptor(_class4.prototype, "transferable", [_dec17], Object.getOwnPropertyDescriptor(_class4.prototype, "transferable"), _class4.prototype), _applyDecoratedDescriptor(_class4.prototype, "feePayable", [_dec18], Object.getOwnPropertyDescriptor(_class4.prototype, "feePayable"), _class4.prototype)), _class4));
676
+ }
694
677
  class SumBalancesFormatter {
695
678
  #balances;
696
679
  constructor(balances) {
697
680
  this.#balances = balances;
698
- this.fiat = memoize(this.fiat);
699
681
  }
700
682
  fiat(currency) {
701
683
  return new FiatSumBalancesFormatter(this.#balances, currency);
702
684
  }
703
685
  }
704
686
 
705
- export { Balance, BalanceFormatter, Balances, DefaultBalanceModule, FiatSumBalancesFormatter, StorageHelper, SumBalancesFormatter, TalismanBalancesDatabase, balances, db, excludeFromFeePayableLocks, excludeFromTransferableAmount, filterMirrorTokens, includeInTotalExtraAmount };
687
+ export { Balance, BalanceFormatter, Balances, DefaultBalanceModule, FiatSumBalancesFormatter, StorageHelper, SumBalancesFormatter, TalismanBalancesDatabase, balances, db, excludeFromFeePayableLocks, excludeFromTransferableAmount, filterMirrorTokens, includeInTotalExtraAmount, useMetadataCache, useTypeRegistryCache };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@talismn/balances",
3
- "version": "0.0.0-pr599-20230306082809",
3
+ "version": "0.0.0-pr600-20230307005925",
4
4
  "author": "Talisman",
5
5
  "homepage": "https://talisman.xyz",
6
6
  "license": "UNLICENSED",
@@ -30,12 +30,10 @@
30
30
  "@talismn/chain-connector": "^0.4.2",
31
31
  "@talismn/chain-connector-evm": "^0.4.2",
32
32
  "@talismn/chaindata-provider": "^0.4.2",
33
- "@talismn/token-rates": "^0.0.0-pr599-20230306082809",
33
+ "@talismn/token-rates": "^0.0.0-pr600-20230307005925",
34
34
  "@talismn/util": "^0.1.7",
35
35
  "anylogger": "^1.0.11",
36
- "dexie": "^3.2.3",
37
- "lodash": "^4.17.21",
38
- "typescript-memoize": "^1.1.0"
36
+ "dexie": "^3.2.3"
39
37
  },
40
38
  "devDependencies": {
41
39
  "@polkadot/types": "^9.10.5",