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

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-20230307002741
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-20230307002741
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-20230307002741",
78
71
  author: "Talisman",
79
72
  homepage: "https://talisman.xyz",
80
73
  license: "UNLICENSED",
@@ -108,8 +101,7 @@ var packageJson = {
108
101
  "@talismn/util": "workspace:^",
109
102
  anylogger: "^1.0.11",
110
103
  dexie: "^3.2.3",
111
- lodash: "^4.17.21",
112
- "typescript-memoize": "^1.1.0"
104
+ lodash: "^4.17.21"
113
105
  },
114
106
  devDependencies: {
115
107
  "@polkadot/types": "^9.10.5",
@@ -140,13 +132,37 @@ var packageJson = {
140
132
 
141
133
  var log = anylogger__default["default"](packageJson.name);
142
134
 
143
- async function balances(balanceModule, chainConnectors, chaindataProvider, addressesByToken, callback) {
135
+ async function balances(balanceModule, addressesByToken, callback) {
144
136
  // subscription request
145
- if (callback !== undefined) return await balanceModule.subscribeBalances(chainConnectors, chaindataProvider, addressesByToken, callback);
137
+ if (callback !== undefined) return await balanceModule.subscribeBalances(addressesByToken, callback);
146
138
 
147
139
  // one-off request
148
- return await balanceModule.fetchBalances(chainConnectors, chaindataProvider, addressesByToken);
140
+ return await balanceModule.fetchBalances(addressesByToken);
149
141
  }
142
+ const useMetadataCache = () => {
143
+ const metadataCache = new Map();
144
+ const getOrCreateMetadata = (chainId, metadataRpc) => {
145
+ // TODO: Delete cache when metadataRpc is different from last time
146
+ const cached = metadataCache.get(chainId);
147
+ if (cached) return cached;
148
+ const metadata = new types.Metadata(new types.TypeRegistry(), metadataRpc);
149
+ metadata.registry.setMetadata(metadata);
150
+ metadataCache.set(chainId, metadata);
151
+ return metadata;
152
+ };
153
+ return {
154
+ getOrCreateMetadata
155
+ };
156
+ };
157
+ const useTypeRegistryCache = () => {
158
+ const {
159
+ getOrCreateMetadata
160
+ } = useMetadataCache();
161
+ const getOrCreateTypeRegistry = (chainId, metadataRpc) => getOrCreateMetadata(chainId, metadataRpc).registry;
162
+ return {
163
+ getOrCreateTypeRegistry
164
+ };
165
+ };
150
166
  const filterMirrorTokens = (balance, i, balances) => {
151
167
  var _balance$token;
152
168
  // TODO: implement a mirrorOf property, which should be set from chaindata
@@ -236,30 +252,6 @@ class StorageHelper {
236
252
  }
237
253
  }
238
254
 
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
255
  function excludeFromTransferableAmount(locks) {
264
256
  if (typeof locks === "string") return BigInt(locks);
265
257
  if (!Array.isArray(locks)) locks = [locks];
@@ -281,8 +273,6 @@ function includeInTotalExtraAmount(extra) {
281
273
 
282
274
  /** Used by plugins to help define their custom `BalanceType` */
283
275
 
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
276
  /**
287
277
  * Have the importing library define its Token and BalanceJson enums (as a sum type of all plugins) and pass them into some
288
278
  * internal global typescript context, which is then picked up on by this module.
@@ -293,12 +283,12 @@ var _dec, _dec2, _dec3, _class, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10
293
283
  /**
294
284
  * A collection of balances.
295
285
  */
296
- let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Memoize(), _dec3 = typescriptMemoize.Memoize(), (_class = class Balances {
286
+ class Balances {
297
287
  //
298
288
  // Properties
299
289
  //
300
290
 
301
- #balances = {};
291
+ #balances = [];
302
292
 
303
293
  //
304
294
  // Methods
@@ -306,7 +296,7 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
306
296
 
307
297
  constructor(balances, hydrate) {
308
298
  // handle Balances (convert to Balance[])
309
- if (balances instanceof Balances) return new Balances([...balances], hydrate);
299
+ if (balances instanceof Balances) return new Balances(balances.each, hydrate);
310
300
 
311
301
  // handle Balance (convert to Balance[])
312
302
  if (balances instanceof Balance) return new Balances([balances], hydrate);
@@ -321,19 +311,19 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
321
311
  if (!util.isArrayOf(balances, Balance)) return new Balances(balances.map(storage => new Balance(storage)), hydrate);
322
312
 
323
313
  // handle Balance[]
324
- this.#balances = Object.fromEntries(balances.map(balance => [balance.id, balance]));
314
+ this.#balances = balances;
325
315
  if (hydrate !== undefined) this.hydrate(hydrate);
326
316
  }
327
317
 
328
318
  /**
329
319
  * Calling toJSON on a collection of balances will return the underlying BalanceJsonList.
330
320
  */
331
- toJSON = () => Object.fromEntries(Object.entries(this.#balances).map(([id, balance]) => {
321
+ toJSON = () => Object.fromEntries(this.#balances.map(balance => {
332
322
  try {
333
- return [id, balance.toJSON()];
323
+ return [balance.id, balance.toJSON()];
334
324
  } catch (error) {
335
325
  log.error("Failed to convert balance to JSON", error, {
336
- id,
326
+ id: balance.id,
337
327
  balance
338
328
  });
339
329
  return null;
@@ -353,7 +343,7 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
353
343
  */
354
344
  [Symbol.iterator] = () =>
355
345
  // Create an array of the balances in this collection and return the result of its iterator.
356
- Object.values(this.#balances)[Symbol.iterator]();
346
+ this.#balances[Symbol.iterator]();
357
347
 
358
348
  /**
359
349
  * Hydrates all balances in this collection.
@@ -361,7 +351,7 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
361
351
  * @param sources - The sources to hydrate from.
362
352
  */
363
353
  hydrate = sources => {
364
- Object.values(this.#balances).map(balance => balance.hydrate(sources));
354
+ this.#balances.map(balance => balance.hydrate(sources));
365
355
  };
366
356
 
367
357
  /**
@@ -370,7 +360,7 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
370
360
  * @param id - The id of the balance to fetch.
371
361
  * @returns The balance if one exists, or none.
372
362
  */
373
- get = id => this.#balances[id] || null;
363
+ get = id => this.#balances.find(balance => balance.id === id) ?? null;
374
364
 
375
365
  /**
376
366
  * Retrieve balances from this collection by search query.
@@ -403,10 +393,8 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
403
393
  if (balances instanceof Balance) return this.add(new Balances(balances));
404
394
 
405
395
  // merge balances
406
- const mergedBalances = {
407
- ...this.#balances
408
- };
409
- [...balances].forEach(balance => mergedBalances[balance.id] = balance);
396
+ const mergedBalances = Object.fromEntries(this.#balances.map(balance => [balance.id, balance]));
397
+ balances.each.forEach(balance => mergedBalances[balance.id] = balance);
410
398
 
411
399
  // return new balances
412
400
  return new Balances(Object.values(mergedBalances));
@@ -424,18 +412,16 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
424
412
  // handle single id
425
413
  if (!Array.isArray(ids)) return this.remove([ids]);
426
414
 
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));
415
+ // merge and return new balances
416
+ return new Balances(this.#balances.filter(balance => !ids.includes(balance.id)));
435
417
  };
436
418
 
437
419
  // TODO: Add some more useful aggregator methods
438
420
 
421
+ get each() {
422
+ return [...this];
423
+ }
424
+
439
425
  /**
440
426
  * Get an array of balances in this collection, sorted by chain sortIndex.
441
427
  *
@@ -444,7 +430,7 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
444
430
  get sorted() {
445
431
  return [...this].sort((a, b) => {
446
432
  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);
433
+ 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
434
  });
449
435
  }
450
436
 
@@ -468,12 +454,12 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
468
454
  get sum() {
469
455
  return new SumBalancesFormatter(this);
470
456
  }
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));
457
+ }
472
458
 
473
459
  /**
474
460
  * An individual balance.
475
461
  */
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 {
462
+ class Balance {
477
463
  //
478
464
  // Properties
479
465
  //
@@ -487,7 +473,6 @@ let Balance = (_dec4 = typescriptMemoize.Memoize(), _dec5 = typescriptMemoize.Me
487
473
  //
488
474
 
489
475
  constructor(storage, hydrate) {
490
- this.#format = memoize__default["default"](this.#format);
491
476
  this.#storage = storage;
492
477
  if (hydrate !== undefined) this.hydrate(hydrate);
493
478
  }
@@ -621,8 +606,8 @@ let Balance = (_dec4 = typescriptMemoize.Memoize(), _dec5 = typescriptMemoize.Me
621
606
  // subtract the lock from the free amount (but don't go below 0)
622
607
  return this.#format(util.BigMath.max(this.free.planck - excludeAmount, BigInt("0")));
623
608
  }
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 {
609
+ }
610
+ class BalanceFormatter {
626
611
  #planck;
627
612
  #decimals;
628
613
  #fiatRatios;
@@ -630,7 +615,6 @@ let BalanceFormatter = (_dec11 = typescriptMemoize.Memoize(), (_class3 = class B
630
615
  this.#planck = typeof planck === "bigint" ? planck.toString() : planck ?? "0";
631
616
  this.#decimals = decimals || 0;
632
617
  this.#fiatRatios = fiatRatios || null;
633
- this.fiat = memoize__default["default"](this.fiat);
634
618
  }
635
619
  toJSON = () => this.#planck;
636
620
  get planck() {
@@ -645,14 +629,13 @@ let BalanceFormatter = (_dec11 = typescriptMemoize.Memoize(), (_class3 = class B
645
629
  if (!ratio) return null;
646
630
  return parseFloat(this.tokens) * ratio;
647
631
  }
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 {
632
+ }
633
+ class FiatSumBalancesFormatter {
650
634
  #balances;
651
635
  #currency;
652
636
  constructor(balances, currency) {
653
637
  this.#balances = balances;
654
638
  this.#currency = currency;
655
- this.#sum = memoize__default["default"](this.#sum);
656
639
  }
657
640
  #sum = balanceField => {
658
641
  // a function to get a fiat amount from a balance
@@ -699,12 +682,11 @@ let FiatSumBalancesFormatter = (_dec12 = typescriptMemoize.Memoize(), _dec13 = t
699
682
  get feePayable() {
700
683
  return this.#sum("feePayable");
701
684
  }
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));
685
+ }
703
686
  class SumBalancesFormatter {
704
687
  #balances;
705
688
  constructor(balances) {
706
689
  this.#balances = balances;
707
- this.fiat = memoize__default["default"](this.fiat);
708
690
  }
709
691
  fiat(currency) {
710
692
  return new FiatSumBalancesFormatter(this.#balances, currency);
@@ -725,3 +707,5 @@ exports.excludeFromFeePayableLocks = excludeFromFeePayableLocks;
725
707
  exports.excludeFromTransferableAmount = excludeFromTransferableAmount;
726
708
  exports.filterMirrorTokens = filterMirrorTokens;
727
709
  exports.includeInTotalExtraAmount = includeInTotalExtraAmount;
710
+ exports.useMetadataCache = useMetadataCache;
711
+ 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-20230307002741",
78
71
  author: "Talisman",
79
72
  homepage: "https://talisman.xyz",
80
73
  license: "UNLICENSED",
@@ -108,8 +101,7 @@ var packageJson = {
108
101
  "@talismn/util": "workspace:^",
109
102
  anylogger: "^1.0.11",
110
103
  dexie: "^3.2.3",
111
- lodash: "^4.17.21",
112
- "typescript-memoize": "^1.1.0"
104
+ lodash: "^4.17.21"
113
105
  },
114
106
  devDependencies: {
115
107
  "@polkadot/types": "^9.10.5",
@@ -140,13 +132,37 @@ var packageJson = {
140
132
 
141
133
  var log = anylogger__default["default"](packageJson.name);
142
134
 
143
- async function balances(balanceModule, chainConnectors, chaindataProvider, addressesByToken, callback) {
135
+ async function balances(balanceModule, addressesByToken, callback) {
144
136
  // subscription request
145
- if (callback !== undefined) return await balanceModule.subscribeBalances(chainConnectors, chaindataProvider, addressesByToken, callback);
137
+ if (callback !== undefined) return await balanceModule.subscribeBalances(addressesByToken, callback);
146
138
 
147
139
  // one-off request
148
- return await balanceModule.fetchBalances(chainConnectors, chaindataProvider, addressesByToken);
140
+ return await balanceModule.fetchBalances(addressesByToken);
149
141
  }
142
+ const useMetadataCache = () => {
143
+ const metadataCache = new Map();
144
+ const getOrCreateMetadata = (chainId, metadataRpc) => {
145
+ // TODO: Delete cache when metadataRpc is different from last time
146
+ const cached = metadataCache.get(chainId);
147
+ if (cached) return cached;
148
+ const metadata = new types.Metadata(new types.TypeRegistry(), metadataRpc);
149
+ metadata.registry.setMetadata(metadata);
150
+ metadataCache.set(chainId, metadata);
151
+ return metadata;
152
+ };
153
+ return {
154
+ getOrCreateMetadata
155
+ };
156
+ };
157
+ const useTypeRegistryCache = () => {
158
+ const {
159
+ getOrCreateMetadata
160
+ } = useMetadataCache();
161
+ const getOrCreateTypeRegistry = (chainId, metadataRpc) => getOrCreateMetadata(chainId, metadataRpc).registry;
162
+ return {
163
+ getOrCreateTypeRegistry
164
+ };
165
+ };
150
166
  const filterMirrorTokens = (balance, i, balances) => {
151
167
  var _balance$token;
152
168
  // TODO: implement a mirrorOf property, which should be set from chaindata
@@ -236,30 +252,6 @@ class StorageHelper {
236
252
  }
237
253
  }
238
254
 
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
255
  function excludeFromTransferableAmount(locks) {
264
256
  if (typeof locks === "string") return BigInt(locks);
265
257
  if (!Array.isArray(locks)) locks = [locks];
@@ -281,8 +273,6 @@ function includeInTotalExtraAmount(extra) {
281
273
 
282
274
  /** Used by plugins to help define their custom `BalanceType` */
283
275
 
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
276
  /**
287
277
  * Have the importing library define its Token and BalanceJson enums (as a sum type of all plugins) and pass them into some
288
278
  * internal global typescript context, which is then picked up on by this module.
@@ -293,12 +283,12 @@ var _dec, _dec2, _dec3, _class, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10
293
283
  /**
294
284
  * A collection of balances.
295
285
  */
296
- let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Memoize(), _dec3 = typescriptMemoize.Memoize(), (_class = class Balances {
286
+ class Balances {
297
287
  //
298
288
  // Properties
299
289
  //
300
290
 
301
- #balances = {};
291
+ #balances = [];
302
292
 
303
293
  //
304
294
  // Methods
@@ -306,7 +296,7 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
306
296
 
307
297
  constructor(balances, hydrate) {
308
298
  // handle Balances (convert to Balance[])
309
- if (balances instanceof Balances) return new Balances([...balances], hydrate);
299
+ if (balances instanceof Balances) return new Balances(balances.each, hydrate);
310
300
 
311
301
  // handle Balance (convert to Balance[])
312
302
  if (balances instanceof Balance) return new Balances([balances], hydrate);
@@ -321,19 +311,19 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
321
311
  if (!util.isArrayOf(balances, Balance)) return new Balances(balances.map(storage => new Balance(storage)), hydrate);
322
312
 
323
313
  // handle Balance[]
324
- this.#balances = Object.fromEntries(balances.map(balance => [balance.id, balance]));
314
+ this.#balances = balances;
325
315
  if (hydrate !== undefined) this.hydrate(hydrate);
326
316
  }
327
317
 
328
318
  /**
329
319
  * Calling toJSON on a collection of balances will return the underlying BalanceJsonList.
330
320
  */
331
- toJSON = () => Object.fromEntries(Object.entries(this.#balances).map(([id, balance]) => {
321
+ toJSON = () => Object.fromEntries(this.#balances.map(balance => {
332
322
  try {
333
- return [id, balance.toJSON()];
323
+ return [balance.id, balance.toJSON()];
334
324
  } catch (error) {
335
325
  log.error("Failed to convert balance to JSON", error, {
336
- id,
326
+ id: balance.id,
337
327
  balance
338
328
  });
339
329
  return null;
@@ -353,7 +343,7 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
353
343
  */
354
344
  [Symbol.iterator] = () =>
355
345
  // Create an array of the balances in this collection and return the result of its iterator.
356
- Object.values(this.#balances)[Symbol.iterator]();
346
+ this.#balances[Symbol.iterator]();
357
347
 
358
348
  /**
359
349
  * Hydrates all balances in this collection.
@@ -361,7 +351,7 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
361
351
  * @param sources - The sources to hydrate from.
362
352
  */
363
353
  hydrate = sources => {
364
- Object.values(this.#balances).map(balance => balance.hydrate(sources));
354
+ this.#balances.map(balance => balance.hydrate(sources));
365
355
  };
366
356
 
367
357
  /**
@@ -370,7 +360,7 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
370
360
  * @param id - The id of the balance to fetch.
371
361
  * @returns The balance if one exists, or none.
372
362
  */
373
- get = id => this.#balances[id] || null;
363
+ get = id => this.#balances.find(balance => balance.id === id) ?? null;
374
364
 
375
365
  /**
376
366
  * Retrieve balances from this collection by search query.
@@ -403,10 +393,8 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
403
393
  if (balances instanceof Balance) return this.add(new Balances(balances));
404
394
 
405
395
  // merge balances
406
- const mergedBalances = {
407
- ...this.#balances
408
- };
409
- [...balances].forEach(balance => mergedBalances[balance.id] = balance);
396
+ const mergedBalances = Object.fromEntries(this.#balances.map(balance => [balance.id, balance]));
397
+ balances.each.forEach(balance => mergedBalances[balance.id] = balance);
410
398
 
411
399
  // return new balances
412
400
  return new Balances(Object.values(mergedBalances));
@@ -424,18 +412,16 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
424
412
  // handle single id
425
413
  if (!Array.isArray(ids)) return this.remove([ids]);
426
414
 
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));
415
+ // merge and return new balances
416
+ return new Balances(this.#balances.filter(balance => !ids.includes(balance.id)));
435
417
  };
436
418
 
437
419
  // TODO: Add some more useful aggregator methods
438
420
 
421
+ get each() {
422
+ return [...this];
423
+ }
424
+
439
425
  /**
440
426
  * Get an array of balances in this collection, sorted by chain sortIndex.
441
427
  *
@@ -444,7 +430,7 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
444
430
  get sorted() {
445
431
  return [...this].sort((a, b) => {
446
432
  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);
433
+ 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
434
  });
449
435
  }
450
436
 
@@ -468,12 +454,12 @@ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Me
468
454
  get sum() {
469
455
  return new SumBalancesFormatter(this);
470
456
  }
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));
457
+ }
472
458
 
473
459
  /**
474
460
  * An individual balance.
475
461
  */
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 {
462
+ class Balance {
477
463
  //
478
464
  // Properties
479
465
  //
@@ -487,7 +473,6 @@ let Balance = (_dec4 = typescriptMemoize.Memoize(), _dec5 = typescriptMemoize.Me
487
473
  //
488
474
 
489
475
  constructor(storage, hydrate) {
490
- this.#format = memoize__default["default"](this.#format);
491
476
  this.#storage = storage;
492
477
  if (hydrate !== undefined) this.hydrate(hydrate);
493
478
  }
@@ -621,8 +606,8 @@ let Balance = (_dec4 = typescriptMemoize.Memoize(), _dec5 = typescriptMemoize.Me
621
606
  // subtract the lock from the free amount (but don't go below 0)
622
607
  return this.#format(util.BigMath.max(this.free.planck - excludeAmount, BigInt("0")));
623
608
  }
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 {
609
+ }
610
+ class BalanceFormatter {
626
611
  #planck;
627
612
  #decimals;
628
613
  #fiatRatios;
@@ -630,7 +615,6 @@ let BalanceFormatter = (_dec11 = typescriptMemoize.Memoize(), (_class3 = class B
630
615
  this.#planck = typeof planck === "bigint" ? planck.toString() : planck ?? "0";
631
616
  this.#decimals = decimals || 0;
632
617
  this.#fiatRatios = fiatRatios || null;
633
- this.fiat = memoize__default["default"](this.fiat);
634
618
  }
635
619
  toJSON = () => this.#planck;
636
620
  get planck() {
@@ -645,14 +629,13 @@ let BalanceFormatter = (_dec11 = typescriptMemoize.Memoize(), (_class3 = class B
645
629
  if (!ratio) return null;
646
630
  return parseFloat(this.tokens) * ratio;
647
631
  }
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 {
632
+ }
633
+ class FiatSumBalancesFormatter {
650
634
  #balances;
651
635
  #currency;
652
636
  constructor(balances, currency) {
653
637
  this.#balances = balances;
654
638
  this.#currency = currency;
655
- this.#sum = memoize__default["default"](this.#sum);
656
639
  }
657
640
  #sum = balanceField => {
658
641
  // a function to get a fiat amount from a balance
@@ -699,12 +682,11 @@ let FiatSumBalancesFormatter = (_dec12 = typescriptMemoize.Memoize(), _dec13 = t
699
682
  get feePayable() {
700
683
  return this.#sum("feePayable");
701
684
  }
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));
685
+ }
703
686
  class SumBalancesFormatter {
704
687
  #balances;
705
688
  constructor(balances) {
706
689
  this.#balances = balances;
707
- this.fiat = memoize__default["default"](this.fiat);
708
690
  }
709
691
  fiat(currency) {
710
692
  return new FiatSumBalancesFormatter(this.#balances, currency);
@@ -725,3 +707,5 @@ exports.excludeFromFeePayableLocks = excludeFromFeePayableLocks;
725
707
  exports.excludeFromTransferableAmount = excludeFromTransferableAmount;
726
708
  exports.filterMirrorTokens = filterMirrorTokens;
727
709
  exports.includeInTotalExtraAmount = includeInTotalExtraAmount;
710
+ exports.useMetadataCache = useMetadataCache;
711
+ 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-20230307002741",
69
63
  author: "Talisman",
70
64
  homepage: "https://talisman.xyz",
71
65
  license: "UNLICENSED",
@@ -99,8 +93,7 @@ var packageJson = {
99
93
  "@talismn/util": "workspace:^",
100
94
  anylogger: "^1.0.11",
101
95
  dexie: "^3.2.3",
102
- lodash: "^4.17.21",
103
- "typescript-memoize": "^1.1.0"
96
+ lodash: "^4.17.21"
104
97
  },
105
98
  devDependencies: {
106
99
  "@polkadot/types": "^9.10.5",
@@ -131,13 +124,37 @@ var packageJson = {
131
124
 
132
125
  var log = anylogger(packageJson.name);
133
126
 
134
- async function balances(balanceModule, chainConnectors, chaindataProvider, addressesByToken, callback) {
127
+ async function balances(balanceModule, addressesByToken, callback) {
135
128
  // subscription request
136
- if (callback !== undefined) return await balanceModule.subscribeBalances(chainConnectors, chaindataProvider, addressesByToken, callback);
129
+ if (callback !== undefined) return await balanceModule.subscribeBalances(addressesByToken, callback);
137
130
 
138
131
  // one-off request
139
- return await balanceModule.fetchBalances(chainConnectors, chaindataProvider, addressesByToken);
132
+ return await balanceModule.fetchBalances(addressesByToken);
140
133
  }
134
+ const useMetadataCache = () => {
135
+ const metadataCache = new Map();
136
+ const getOrCreateMetadata = (chainId, metadataRpc) => {
137
+ // TODO: Delete cache when metadataRpc is different from last time
138
+ const cached = metadataCache.get(chainId);
139
+ if (cached) return cached;
140
+ const metadata = new Metadata(new TypeRegistry(), metadataRpc);
141
+ metadata.registry.setMetadata(metadata);
142
+ metadataCache.set(chainId, metadata);
143
+ return metadata;
144
+ };
145
+ return {
146
+ getOrCreateMetadata
147
+ };
148
+ };
149
+ const useTypeRegistryCache = () => {
150
+ const {
151
+ getOrCreateMetadata
152
+ } = useMetadataCache();
153
+ const getOrCreateTypeRegistry = (chainId, metadataRpc) => getOrCreateMetadata(chainId, metadataRpc).registry;
154
+ return {
155
+ getOrCreateTypeRegistry
156
+ };
157
+ };
141
158
  const filterMirrorTokens = (balance, i, balances) => {
142
159
  var _balance$token;
143
160
  // TODO: implement a mirrorOf property, which should be set from chaindata
@@ -227,30 +244,6 @@ class StorageHelper {
227
244
  }
228
245
  }
229
246
 
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
247
  function excludeFromTransferableAmount(locks) {
255
248
  if (typeof locks === "string") return BigInt(locks);
256
249
  if (!Array.isArray(locks)) locks = [locks];
@@ -272,8 +265,6 @@ function includeInTotalExtraAmount(extra) {
272
265
 
273
266
  /** Used by plugins to help define their custom `BalanceType` */
274
267
 
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
268
  /**
278
269
  * Have the importing library define its Token and BalanceJson enums (as a sum type of all plugins) and pass them into some
279
270
  * internal global typescript context, which is then picked up on by this module.
@@ -284,12 +275,12 @@ var _dec, _dec2, _dec3, _class, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10
284
275
  /**
285
276
  * A collection of balances.
286
277
  */
287
- let Balances = (_dec = Memoize(), _dec2 = Memoize(), _dec3 = Memoize(), (_class = class Balances {
278
+ class Balances {
288
279
  //
289
280
  // Properties
290
281
  //
291
282
 
292
- #balances = {};
283
+ #balances = [];
293
284
 
294
285
  //
295
286
  // Methods
@@ -297,7 +288,7 @@ let Balances = (_dec = Memoize(), _dec2 = Memoize(), _dec3 = Memoize(), (_class
297
288
 
298
289
  constructor(balances, hydrate) {
299
290
  // handle Balances (convert to Balance[])
300
- if (balances instanceof Balances) return new Balances([...balances], hydrate);
291
+ if (balances instanceof Balances) return new Balances(balances.each, hydrate);
301
292
 
302
293
  // handle Balance (convert to Balance[])
303
294
  if (balances instanceof Balance) return new Balances([balances], hydrate);
@@ -312,19 +303,19 @@ let Balances = (_dec = Memoize(), _dec2 = Memoize(), _dec3 = Memoize(), (_class
312
303
  if (!isArrayOf(balances, Balance)) return new Balances(balances.map(storage => new Balance(storage)), hydrate);
313
304
 
314
305
  // handle Balance[]
315
- this.#balances = Object.fromEntries(balances.map(balance => [balance.id, balance]));
306
+ this.#balances = balances;
316
307
  if (hydrate !== undefined) this.hydrate(hydrate);
317
308
  }
318
309
 
319
310
  /**
320
311
  * Calling toJSON on a collection of balances will return the underlying BalanceJsonList.
321
312
  */
322
- toJSON = () => Object.fromEntries(Object.entries(this.#balances).map(([id, balance]) => {
313
+ toJSON = () => Object.fromEntries(this.#balances.map(balance => {
323
314
  try {
324
- return [id, balance.toJSON()];
315
+ return [balance.id, balance.toJSON()];
325
316
  } catch (error) {
326
317
  log.error("Failed to convert balance to JSON", error, {
327
- id,
318
+ id: balance.id,
328
319
  balance
329
320
  });
330
321
  return null;
@@ -344,7 +335,7 @@ let Balances = (_dec = Memoize(), _dec2 = Memoize(), _dec3 = Memoize(), (_class
344
335
  */
345
336
  [Symbol.iterator] = () =>
346
337
  // Create an array of the balances in this collection and return the result of its iterator.
347
- Object.values(this.#balances)[Symbol.iterator]();
338
+ this.#balances[Symbol.iterator]();
348
339
 
349
340
  /**
350
341
  * Hydrates all balances in this collection.
@@ -352,7 +343,7 @@ let Balances = (_dec = Memoize(), _dec2 = Memoize(), _dec3 = Memoize(), (_class
352
343
  * @param sources - The sources to hydrate from.
353
344
  */
354
345
  hydrate = sources => {
355
- Object.values(this.#balances).map(balance => balance.hydrate(sources));
346
+ this.#balances.map(balance => balance.hydrate(sources));
356
347
  };
357
348
 
358
349
  /**
@@ -361,7 +352,7 @@ let Balances = (_dec = Memoize(), _dec2 = Memoize(), _dec3 = Memoize(), (_class
361
352
  * @param id - The id of the balance to fetch.
362
353
  * @returns The balance if one exists, or none.
363
354
  */
364
- get = id => this.#balances[id] || null;
355
+ get = id => this.#balances.find(balance => balance.id === id) ?? null;
365
356
 
366
357
  /**
367
358
  * Retrieve balances from this collection by search query.
@@ -394,10 +385,8 @@ let Balances = (_dec = Memoize(), _dec2 = Memoize(), _dec3 = Memoize(), (_class
394
385
  if (balances instanceof Balance) return this.add(new Balances(balances));
395
386
 
396
387
  // merge balances
397
- const mergedBalances = {
398
- ...this.#balances
399
- };
400
- [...balances].forEach(balance => mergedBalances[balance.id] = balance);
388
+ const mergedBalances = Object.fromEntries(this.#balances.map(balance => [balance.id, balance]));
389
+ balances.each.forEach(balance => mergedBalances[balance.id] = balance);
401
390
 
402
391
  // return new balances
403
392
  return new Balances(Object.values(mergedBalances));
@@ -415,18 +404,16 @@ let Balances = (_dec = Memoize(), _dec2 = Memoize(), _dec3 = Memoize(), (_class
415
404
  // handle single id
416
405
  if (!Array.isArray(ids)) return this.remove([ids]);
417
406
 
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));
407
+ // merge and return new balances
408
+ return new Balances(this.#balances.filter(balance => !ids.includes(balance.id)));
426
409
  };
427
410
 
428
411
  // TODO: Add some more useful aggregator methods
429
412
 
413
+ get each() {
414
+ return [...this];
415
+ }
416
+
430
417
  /**
431
418
  * Get an array of balances in this collection, sorted by chain sortIndex.
432
419
  *
@@ -435,7 +422,7 @@ let Balances = (_dec = Memoize(), _dec2 = Memoize(), _dec3 = Memoize(), (_class
435
422
  get sorted() {
436
423
  return [...this].sort((a, b) => {
437
424
  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);
425
+ 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
426
  });
440
427
  }
441
428
 
@@ -459,12 +446,12 @@ let Balances = (_dec = Memoize(), _dec2 = Memoize(), _dec3 = Memoize(), (_class
459
446
  get sum() {
460
447
  return new SumBalancesFormatter(this);
461
448
  }
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));
449
+ }
463
450
 
464
451
  /**
465
452
  * An individual balance.
466
453
  */
467
- let Balance = (_dec4 = Memoize(), _dec5 = Memoize(), _dec6 = Memoize(), _dec7 = Memoize(), _dec8 = Memoize(), _dec9 = Memoize(), _dec10 = Memoize(), (_class2 = class Balance {
454
+ class Balance {
468
455
  //
469
456
  // Properties
470
457
  //
@@ -478,7 +465,6 @@ let Balance = (_dec4 = Memoize(), _dec5 = Memoize(), _dec6 = Memoize(), _dec7 =
478
465
  //
479
466
 
480
467
  constructor(storage, hydrate) {
481
- this.#format = memoize(this.#format);
482
468
  this.#storage = storage;
483
469
  if (hydrate !== undefined) this.hydrate(hydrate);
484
470
  }
@@ -612,8 +598,8 @@ let Balance = (_dec4 = Memoize(), _dec5 = Memoize(), _dec6 = Memoize(), _dec7 =
612
598
  // subtract the lock from the free amount (but don't go below 0)
613
599
  return this.#format(BigMath.max(this.free.planck - excludeAmount, BigInt("0")));
614
600
  }
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 {
601
+ }
602
+ class BalanceFormatter {
617
603
  #planck;
618
604
  #decimals;
619
605
  #fiatRatios;
@@ -621,7 +607,6 @@ let BalanceFormatter = (_dec11 = Memoize(), (_class3 = class BalanceFormatter {
621
607
  this.#planck = typeof planck === "bigint" ? planck.toString() : planck ?? "0";
622
608
  this.#decimals = decimals || 0;
623
609
  this.#fiatRatios = fiatRatios || null;
624
- this.fiat = memoize(this.fiat);
625
610
  }
626
611
  toJSON = () => this.#planck;
627
612
  get planck() {
@@ -636,14 +621,13 @@ let BalanceFormatter = (_dec11 = Memoize(), (_class3 = class BalanceFormatter {
636
621
  if (!ratio) return null;
637
622
  return parseFloat(this.tokens) * ratio;
638
623
  }
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 {
624
+ }
625
+ class FiatSumBalancesFormatter {
641
626
  #balances;
642
627
  #currency;
643
628
  constructor(balances, currency) {
644
629
  this.#balances = balances;
645
630
  this.#currency = currency;
646
- this.#sum = memoize(this.#sum);
647
631
  }
648
632
  #sum = balanceField => {
649
633
  // a function to get a fiat amount from a balance
@@ -690,16 +674,15 @@ let FiatSumBalancesFormatter = (_dec12 = Memoize(), _dec13 = Memoize(), _dec14 =
690
674
  get feePayable() {
691
675
  return this.#sum("feePayable");
692
676
  }
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));
677
+ }
694
678
  class SumBalancesFormatter {
695
679
  #balances;
696
680
  constructor(balances) {
697
681
  this.#balances = balances;
698
- this.fiat = memoize(this.fiat);
699
682
  }
700
683
  fiat(currency) {
701
684
  return new FiatSumBalancesFormatter(this.#balances, currency);
702
685
  }
703
686
  }
704
687
 
705
- export { Balance, BalanceFormatter, Balances, DefaultBalanceModule, FiatSumBalancesFormatter, StorageHelper, SumBalancesFormatter, TalismanBalancesDatabase, balances, db, excludeFromFeePayableLocks, excludeFromTransferableAmount, filterMirrorTokens, includeInTotalExtraAmount };
688
+ 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-20230307002741",
4
4
  "author": "Talisman",
5
5
  "homepage": "https://talisman.xyz",
6
6
  "license": "UNLICENSED",
@@ -30,12 +30,11 @@
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-20230307002741",
34
34
  "@talismn/util": "^0.1.7",
35
35
  "anylogger": "^1.0.11",
36
36
  "dexie": "^3.2.3",
37
- "lodash": "^4.17.21",
38
- "typescript-memoize": "^1.1.0"
37
+ "lodash": "^4.17.21"
39
38
  },
40
39
  "devDependencies": {
41
40
  "@polkadot/types": "^9.10.5",