@talismn/balances 0.0.0-pr465-20230126032920 → 0.0.0-pr472-20230201082459

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.
Files changed (36) hide show
  1. package/CHANGELOG.md +20 -3
  2. package/dist/{BalanceModule.d.ts → declarations/src/BalanceModule.d.ts} +5 -5
  3. package/dist/{TalismanBalancesDatabase.d.ts → declarations/src/TalismanBalancesDatabase.d.ts} +0 -0
  4. package/dist/{helpers.d.ts → declarations/src/helpers.d.ts} +0 -0
  5. package/dist/{index.d.ts → declarations/src/index.d.ts} +0 -0
  6. package/dist/{log.d.ts → declarations/src/log.d.ts} +0 -0
  7. package/dist/{plugins.d.ts → declarations/src/plugins.d.ts} +4 -1
  8. package/dist/declarations/src/types/addresses.d.ts +4 -0
  9. package/dist/{types → declarations/src/types}/balances.d.ts +4 -4
  10. package/dist/{types → declarations/src/types}/balancetypes.d.ts +16 -13
  11. package/dist/{types → declarations/src/types}/index.d.ts +0 -0
  12. package/dist/{types → declarations/src/types}/subscriptions.d.ts +1 -1
  13. package/dist/talismn-balances.cjs.d.ts +1 -0
  14. package/dist/talismn-balances.cjs.dev.js +723 -0
  15. package/dist/talismn-balances.cjs.js +7 -0
  16. package/dist/talismn-balances.cjs.prod.js +723 -0
  17. package/dist/talismn-balances.esm.js +701 -0
  18. package/package.json +20 -15
  19. package/plugins/dist/talismn-balances-plugins.cjs.d.ts +1 -0
  20. package/plugins/dist/talismn-balances-plugins.cjs.dev.js +2 -0
  21. package/plugins/dist/talismn-balances-plugins.cjs.js +7 -0
  22. package/plugins/dist/talismn-balances-plugins.cjs.prod.js +2 -0
  23. package/plugins/dist/talismn-balances-plugins.esm.js +1 -0
  24. package/plugins/package.json +2 -2
  25. package/dist/BalanceModule.js +0 -29
  26. package/dist/TalismanBalancesDatabase.js +0 -23
  27. package/dist/helpers.js +0 -99
  28. package/dist/index.js +0 -31
  29. package/dist/log.js +0 -10
  30. package/dist/plugins.js +0 -2
  31. package/dist/types/addresses.d.ts +0 -4
  32. package/dist/types/addresses.js +0 -2
  33. package/dist/types/balances.js +0 -471
  34. package/dist/types/balancetypes.js +0 -34
  35. package/dist/types/index.js +0 -20
  36. package/dist/types/subscriptions.js +0 -2
@@ -0,0 +1,723 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var dexie = require('dexie');
6
+ var types = require('@polkadot/types');
7
+ var anylogger = require('anylogger');
8
+ var util = require('@talismn/util');
9
+ var memoize = require('lodash/memoize');
10
+ var typescriptMemoize = require('typescript-memoize');
11
+
12
+ function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
13
+
14
+ var anylogger__default = /*#__PURE__*/_interopDefault(anylogger);
15
+ var memoize__default = /*#__PURE__*/_interopDefault(memoize);
16
+
17
+ //
18
+ // exported
19
+ //
20
+
21
+ // TODO: Document default balances module purpose/usage
22
+ const DefaultBalanceModule = type => ({
23
+ get type() {
24
+ return type;
25
+ },
26
+ async fetchSubstrateChainMeta() {
27
+ return null;
28
+ },
29
+ async fetchEvmChainMeta() {
30
+ return null;
31
+ },
32
+ async fetchSubstrateChainTokens() {
33
+ return Promise.resolve({});
34
+ },
35
+ async fetchEvmChainTokens() {
36
+ return Promise.resolve({});
37
+ },
38
+ async subscribeBalances(_chainConnectors, _chaindataProvider, _addressesByToken, callback) {
39
+ callback(new Error("Balance subscriptions are not implemented in this module."));
40
+ return () => {};
41
+ },
42
+ async fetchBalances() {
43
+ throw new Error("Balance fetching is not implemented in this module.");
44
+ }
45
+ });
46
+
47
+ //
48
+ // internal
49
+ //
50
+
51
+ class TalismanBalancesDatabase extends dexie.Dexie {
52
+ constructor() {
53
+ super("TalismanBalances");
54
+
55
+ // https://dexie.org/docs/Tutorial/Design#database-versioning
56
+ this.version(1).stores({
57
+ // You only need to specify properties that you wish to index.
58
+ // The object store will allow any properties on your stored objects but you can only query them by indexed properties
59
+ // https://dexie.org/docs/API-Reference#declare-database
60
+ //
61
+ // Never index properties containing images, movies or large (huge) strings. Store them in IndexedDB, yes! but just don’t index them!
62
+ // https://dexie.org/docs/Version/Version.stores()#warning
63
+ balances: "id, source, status, address, tokenId"
64
+ });
65
+
66
+ // this.on("ready", async () => {})
67
+ }
68
+ }
69
+
70
+ const db = new TalismanBalancesDatabase();
71
+
72
+ var packageJson = {
73
+ name: "@talismn/balances",
74
+ version: "0.0.0-pr472-20230201082459",
75
+ author: "Talisman",
76
+ homepage: "https://talisman.xyz",
77
+ license: "UNLICENSED",
78
+ publishConfig: {
79
+ access: "public"
80
+ },
81
+ repository: {
82
+ directory: "packages/balances",
83
+ type: "git",
84
+ url: "https://github.com/talismansociety/talisman.git"
85
+ },
86
+ main: "dist/talismn-balances.cjs.js",
87
+ module: "dist/talismn-balances.esm.js",
88
+ files: [
89
+ "/dist",
90
+ "/plugins"
91
+ ],
92
+ engines: {
93
+ node: ">=14"
94
+ },
95
+ scripts: {
96
+ test: "jest",
97
+ lint: "eslint . --max-warnings 0",
98
+ clean: "rm -rf dist && rm -rf .turbo rm -rf node_modules"
99
+ },
100
+ dependencies: {
101
+ "@polkadot/types": "9.10.5",
102
+ "@talismn/chain-connector": "workspace:^",
103
+ "@talismn/chain-connector-evm": "workspace:^",
104
+ "@talismn/chaindata-provider": "workspace:^",
105
+ "@talismn/token-rates": "workspace:^",
106
+ "@talismn/util": "workspace:^",
107
+ anylogger: "^1.0.11",
108
+ dexie: "^3.2.2",
109
+ lodash: "^4.17.21",
110
+ "typescript-memoize": "^1.1.0"
111
+ },
112
+ devDependencies: {
113
+ "@talismn/eslint-config": "workspace:^",
114
+ "@talismn/tsconfig": "workspace:^",
115
+ "@types/jest": "^27.5.1",
116
+ eslint: "^8.4.0",
117
+ jest: "^28.1.0",
118
+ "ts-jest": "^28.0.2",
119
+ typescript: "^4.6.4"
120
+ },
121
+ preconstruct: {
122
+ entrypoints: [
123
+ "index.ts",
124
+ "plugins.ts"
125
+ ]
126
+ },
127
+ eslintConfig: {
128
+ root: true,
129
+ "extends": [
130
+ "@talismn/eslint-config/base"
131
+ ]
132
+ }
133
+ };
134
+
135
+ var log = anylogger__default["default"](packageJson.name);
136
+
137
+ async function balances(balanceModule, chainConnectors, chaindataProvider, addressesByToken, callback) {
138
+ // subscription request
139
+ if (callback !== undefined) return await balanceModule.subscribeBalances(chainConnectors, chaindataProvider, addressesByToken, callback);
140
+
141
+ // one-off request
142
+ return await balanceModule.fetchBalances(chainConnectors, chaindataProvider, addressesByToken);
143
+ }
144
+ const filterMirrorTokens = (balance, i, balances) => {
145
+ var _balance$token;
146
+ // TODO implement a mirrorOf property, which should be set from chaindata
147
+ const mirrorOf = (_balance$token = balance.token) === null || _balance$token === void 0 ? void 0 : _balance$token.mirrorOf;
148
+ return !mirrorOf || !balances.find(b => b.tokenId === mirrorOf);
149
+ };
150
+
151
+ /**
152
+ * Used by a variety of balance modules to help encode and decode substrate state calls.
153
+ */
154
+ class StorageHelper {
155
+ #registry;
156
+ #storageKey;
157
+ #module;
158
+ #method;
159
+ #parameters;
160
+ tags = null;
161
+ constructor(registry, module, method, ...parameters) {
162
+ this.#registry = registry;
163
+ this.#module = module;
164
+ this.#method = method;
165
+ this.#parameters = parameters;
166
+ const _metadataVersion = 0; // is not used inside the decorateStorage function
167
+ let query;
168
+ try {
169
+ query = types.decorateStorage(registry, registry.metadata, _metadataVersion);
170
+ } catch (error) {
171
+ log.debug(`Failed to decorate storage: ${error.message}`);
172
+ this.#storageKey = null;
173
+ }
174
+ try {
175
+ if (!query) throw new Error(`decoratedStorage unavailable`);
176
+ this.#storageKey = new types.StorageKey(registry, parameters ? [query[module][method], parameters] : query[module][method]);
177
+ } catch (error) {
178
+ log.debug(`Failed to create storageKey ${module || "unknown"}.${method || "unknown"}: ${error.message}`);
179
+ this.#storageKey = null;
180
+ }
181
+ }
182
+ get stateKey() {
183
+ var _this$storageKey;
184
+ return (_this$storageKey = this.#storageKey) === null || _this$storageKey === void 0 ? void 0 : _this$storageKey.toHex();
185
+ }
186
+ get module() {
187
+ return this.#module;
188
+ }
189
+ get method() {
190
+ return this.#method;
191
+ }
192
+ get parameters() {
193
+ return this.#parameters;
194
+ }
195
+ tag(tags) {
196
+ this.tags = tags;
197
+ return this;
198
+ }
199
+ decode(input) {
200
+ if (!this.#storageKey) return;
201
+ return this.#decodeStorageScaleResponse(this.#registry, this.#storageKey, input);
202
+ }
203
+ #decodeStorageScaleResponse(typeRegistry, storageKey, input) {
204
+ if (input === undefined || input === null) return;
205
+ const type = storageKey.outputType || "Raw";
206
+ const meta = storageKey.meta || {
207
+ fallback: undefined,
208
+ modifier: {
209
+ isOptional: true
210
+ },
211
+ type: {
212
+ asMap: {
213
+ linked: {
214
+ isTrue: false
215
+ }
216
+ },
217
+ isMap: false
218
+ }
219
+ };
220
+ try {
221
+ return typeRegistry.createTypeUnsafe(type, [meta.modifier.isOptional ? typeRegistry.createTypeUnsafe(type, [input], {
222
+ isPedantic: true
223
+ }) : input], {
224
+ isOptional: meta.modifier.isOptional,
225
+ isPedantic: !meta.modifier.isOptional
226
+ });
227
+ } catch (error) {
228
+ throw new Error(`Unable to decode storage ${storageKey.section || "unknown"}.${storageKey.method || "unknown"}: ${error.message}`);
229
+ }
230
+ }
231
+ }
232
+
233
+ function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
234
+ var desc = {};
235
+ Object.keys(descriptor).forEach(function (key) {
236
+ desc[key] = descriptor[key];
237
+ });
238
+ desc.enumerable = !!desc.enumerable;
239
+ desc.configurable = !!desc.configurable;
240
+ if ('value' in desc || desc.initializer) {
241
+ desc.writable = true;
242
+ }
243
+ desc = decorators.slice().reverse().reduce(function (desc, decorator) {
244
+ return decorator(target, property, desc) || desc;
245
+ }, desc);
246
+ if (context && desc.initializer !== void 0) {
247
+ desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
248
+ desc.initializer = undefined;
249
+ }
250
+ if (desc.initializer === void 0) {
251
+ Object.defineProperty(target, property, desc);
252
+ desc = null;
253
+ }
254
+ return desc;
255
+ }
256
+
257
+ // import { PluginBalanceTypes } from "../plugins"
258
+
259
+ function excludeFromTransferableAmount(locks) {
260
+ if (typeof locks === "string") return BigInt(locks);
261
+ if (!Array.isArray(locks)) locks = [locks];
262
+ return locks.filter(lock => lock.includeInTransferable !== true).map(lock => BigInt(lock.amount)).reduce((max, lock) => util.BigMath.max(max, lock), BigInt("0"));
263
+ }
264
+ function excludeFromFeePayableLocks(locks) {
265
+ if (typeof locks === "string") return [];
266
+ if (!Array.isArray(locks)) locks = [locks];
267
+ return locks.filter(lock => lock.excludeFromFeePayable);
268
+ }
269
+
270
+ /** A labelled extra amount of a balance */
271
+
272
+ function includeInTotalExtraAmount(extra) {
273
+ if (!extra) return BigInt("0");
274
+ if (!Array.isArray(extra)) extra = [extra];
275
+ return extra.filter(extra => extra.includeInTotal).map(extra => BigInt(extra.amount)).reduce((a, b) => a + b, BigInt("0"));
276
+ }
277
+
278
+ /** Used by plugins to help define their custom `BalanceType` */
279
+
280
+ var _dec, _dec2, _dec3, _class, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10, _class2, _dec11, _class3, _dec12, _dec13, _dec14, _dec15, _dec16, _dec17, _dec18, _class4;
281
+
282
+ /**
283
+ * Have the importing library define its Token and BalanceJson enums (as a sum type of all plugins) and pass them into some
284
+ * internal global typescript context, which is then picked up on by this module.
285
+ */
286
+
287
+ /** A utility type used to extract the underlying `BalanceType` of a specific source from a generalised `BalanceJson` */
288
+
289
+ /**
290
+ * A collection of balances.
291
+ */
292
+ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Memoize(), _dec3 = typescriptMemoize.Memoize(), (_class = class Balances {
293
+ //
294
+ // Properties
295
+ //
296
+
297
+ #balances = {};
298
+
299
+ //
300
+ // Methods
301
+ //
302
+
303
+ constructor(balances, hydrate) {
304
+ // handle Balances (convert to Balance[])
305
+ if (balances instanceof Balances) return new Balances([...balances], hydrate);
306
+
307
+ // handle Balance (convert to Balance[])
308
+ if (balances instanceof Balance) return new Balances([balances], hydrate);
309
+
310
+ // handle BalanceJsonList (the only remaining non-array type of balances) (convert to BalanceJson[])
311
+ if (!Array.isArray(balances)) return new Balances(Object.values(balances), hydrate);
312
+
313
+ // handle no balances
314
+ if (balances.length === 0) return this;
315
+
316
+ // handle BalanceJson[]
317
+ if (!util.isArrayOf(balances, Balance)) return new Balances(balances.map(storage => new Balance(storage)), hydrate);
318
+
319
+ // handle Balance[]
320
+ this.#balances = Object.fromEntries(balances.map(balance => [balance.id, balance]));
321
+ if (hydrate !== undefined) this.hydrate(hydrate);
322
+ }
323
+
324
+ /**
325
+ * Calling toJSON on a collection of balances will return the underlying BalanceJsonList.
326
+ */
327
+ toJSON = () => Object.fromEntries(Object.entries(this.#balances).map(([id, balance]) => {
328
+ try {
329
+ return [id, balance.toJSON()];
330
+ } catch (error) {
331
+ log.error("Failed to convert balance to JSON", error, {
332
+ id,
333
+ balance
334
+ });
335
+ return null;
336
+ }
337
+ }).filter(Array.isArray));
338
+
339
+ /**
340
+ * Allows the collection to be iterated over.
341
+ *
342
+ * @example
343
+ * [...balances].forEach(balance => { // do something // })
344
+ *
345
+ * @example
346
+ * for (const balance of balances) {
347
+ * // do something
348
+ * }
349
+ */
350
+ [Symbol.iterator] = () =>
351
+ // Create an array of the balances in this collection and return the result of its iterator.
352
+ Object.values(this.#balances)[Symbol.iterator]();
353
+
354
+ /**
355
+ * Hydrates all balances in this collection.
356
+ *
357
+ * @param sources - The sources to hydrate from.
358
+ */
359
+ hydrate = sources => {
360
+ Object.values(this.#balances).map(balance => balance.hydrate(sources));
361
+ };
362
+
363
+ /**
364
+ * Retrieve a balance from this collection by id.
365
+ *
366
+ * @param id - The id of the balance to fetch.
367
+ * @returns The balance if one exists, or none.
368
+ */
369
+ get = id => this.#balances[id] || null;
370
+
371
+ /**
372
+ * Retrieve balances from this collection by search query.
373
+ *
374
+ * @param query - The search query.
375
+ * @returns All balances which match the query.
376
+ */
377
+ find = query => {
378
+ // construct filter
379
+ const orQueries = (Array.isArray(query) ? query : [query]).map(query => typeof query === "function" ? query : Object.entries(query));
380
+
381
+ // filter balances
382
+ const filter = balance => orQueries.some(query => typeof query === "function" ? query(balance) : query.every(([key, value]) => balance[key] === value));
383
+
384
+ // return filter matches
385
+ return new Balances([...this].filter(filter));
386
+ };
387
+
388
+ /**
389
+ * Add some balances to this collection.
390
+ * Added balances take priority over existing balances.
391
+ * The aggregation of the two collections is returned.
392
+ * The original collection is not mutated.
393
+ *
394
+ * @param balances - Either a balance or collection of balances to add.
395
+ * @returns The new collection of balances.
396
+ */
397
+ add = balances => {
398
+ // handle single balance
399
+ if (balances instanceof Balance) return this.add(new Balances(balances));
400
+
401
+ // merge balances
402
+ const mergedBalances = {
403
+ ...this.#balances
404
+ };
405
+ [...balances].forEach(balance => mergedBalances[balance.id] = balance);
406
+
407
+ // return new balances
408
+ return new Balances(Object.values(mergedBalances));
409
+ };
410
+
411
+ /**
412
+ * Remove balances from this collection by id.
413
+ * A new collection without these balances is returned.
414
+ * The original collection is not mutated.
415
+ *
416
+ * @param ids - The id(s) of the balances to remove.
417
+ * @returns The new collection of balances.
418
+ */
419
+ remove = ids => {
420
+ // handle single id
421
+ if (!Array.isArray(ids)) return this.remove([ids]);
422
+
423
+ // merge balances
424
+ const removedBalances = {
425
+ ...this.#balances
426
+ };
427
+ ids.forEach(id => delete removedBalances[id]);
428
+
429
+ // return new balances
430
+ return new Balances(Object.values(removedBalances));
431
+ };
432
+
433
+ // TODO: Add some more useful aggregator methods
434
+
435
+ /**
436
+ * Get an array of balances in this collection, sorted by chain sortIndex.
437
+ *
438
+ * @returns A sorted array of the balances in this collection.
439
+ */
440
+ get sorted() {
441
+ return [...this].sort((a, b) => {
442
+ var _ref, _ref2;
443
+ 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);
444
+ });
445
+ }
446
+
447
+ /**
448
+ * Get the number of balances in this collection.
449
+ *
450
+ * @returns The number of balances in this collection.
451
+ */
452
+ get count() {
453
+ return [...this].length;
454
+ }
455
+
456
+ /**
457
+ * Get the summed value of balances in this collection.
458
+ * TODO: Sum up token amounts AND fiat amounts
459
+ *
460
+ * @example
461
+ * // Get the sum of all transferable balances in usd.
462
+ * balances.sum.fiat('usd').transferable
463
+ */
464
+ get sum() {
465
+ return new SumBalancesFormatter(this);
466
+ }
467
+ }, (_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));
468
+
469
+ /**
470
+ * An individual balance.
471
+ */
472
+ 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 {
473
+ //
474
+ // Properties
475
+ //
476
+
477
+ /** The underlying data for this balance */
478
+ #storage;
479
+ #db = null;
480
+
481
+ //
482
+ // Methods
483
+ //
484
+
485
+ constructor(storage, hydrate) {
486
+ this.#format = memoize__default["default"](this.#format);
487
+ this.#storage = storage;
488
+ if (hydrate !== undefined) this.hydrate(hydrate);
489
+ }
490
+ toJSON = () => this.#storage;
491
+ isSource = source => this.#storage.source === source;
492
+ // // TODO: Fix this method, the types don't work with our plugin architecture.
493
+ // // Specifically, the `BalanceJson` type is compiled down to `IBalance` in the following way:
494
+ // //
495
+ // // toJSON: () => BalanceJson // works
496
+ // // isSource: (source: BalanceSource) => boolean // works
497
+ // // asSource: <P extends string>(source: P) => NarrowBalanceType<IBalance, P> | null // Doesn't work! IBalance should just be BalanceJson!
498
+ // //
499
+ // // `IBalance` won't match the type of `BalanceSource` after `PluginBalanceTypes` has been extended by balance plugins.
500
+ // // As a result, typescript will think that the returned #storage is not a BalanceJson.
501
+ // asSource = <P extends BalanceSource>(source: P): NarrowBalanceType<BalanceJson, P> | null => {
502
+ // if (this.#storage.source === source) return this.#storage as NarrowBalanceType<BalanceJson, P>
503
+ // return null
504
+ // }
505
+
506
+ hydrate = hydrate => {
507
+ if (hydrate !== undefined) this.#db = hydrate;
508
+ };
509
+ #format = balance => {
510
+ var _this$db;
511
+ return new BalanceFormatter(typeof balance === "bigint" ? balance.toString() : balance, this.decimals || undefined, ((_this$db = this.#db) === null || _this$db === void 0 ? void 0 : _this$db.tokenRates) && this.#db.tokenRates[this.tokenId]);
512
+ };
513
+
514
+ //
515
+ // Accessors
516
+ //
517
+
518
+ get id() {
519
+ const {
520
+ source,
521
+ address,
522
+ chainId,
523
+ evmNetworkId,
524
+ tokenId
525
+ } = this.#storage;
526
+ const locationId = chainId !== undefined ? chainId : evmNetworkId;
527
+ return `${source}-${address}-${locationId}-${tokenId}`;
528
+ }
529
+ get source() {
530
+ return this.#storage.source;
531
+ }
532
+ get status() {
533
+ return this.#storage.status;
534
+ }
535
+ get address() {
536
+ return this.#storage.address;
537
+ }
538
+ get chainId() {
539
+ return this.#storage.chainId;
540
+ }
541
+ get chain() {
542
+ var _this$db2, _this$db3;
543
+ return ((_this$db2 = this.#db) === null || _this$db2 === void 0 ? void 0 : _this$db2.chains) && this.chainId && ((_this$db3 = this.#db) === null || _this$db3 === void 0 ? void 0 : _this$db3.chains[this.chainId]) || null;
544
+ }
545
+ get evmNetworkId() {
546
+ return this.#storage.evmNetworkId;
547
+ }
548
+ get evmNetwork() {
549
+ var _this$db4, _this$db5;
550
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
551
+ return ((_this$db4 = this.#db) === null || _this$db4 === void 0 ? void 0 : _this$db4.evmNetworks) && ((_this$db5 = this.#db) === null || _this$db5 === void 0 ? void 0 : _this$db5.evmNetworks[this.evmNetworkId]) || null;
552
+ }
553
+ get tokenId() {
554
+ return this.#storage.tokenId;
555
+ }
556
+ get token() {
557
+ var _this$db6, _this$db7;
558
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
559
+ return ((_this$db6 = this.#db) === null || _this$db6 === void 0 ? void 0 : _this$db6.tokens) && ((_this$db7 = this.#db) === null || _this$db7 === void 0 ? void 0 : _this$db7.tokens[this.tokenId]) || null;
560
+ }
561
+ get decimals() {
562
+ var _this$token;
563
+ return ((_this$token = this.token) === null || _this$token === void 0 ? void 0 : _this$token.decimals) || null;
564
+ }
565
+ get rates() {
566
+ var _this$db8;
567
+ return ((_this$db8 = this.#db) === null || _this$db8 === void 0 ? void 0 : _this$db8.tokenRates) && this.#db.tokenRates[this.tokenId] || null;
568
+ }
569
+
570
+ /**
571
+ * The total balance of this token.
572
+ * Includes the free and the reserved amount.
573
+ * The balance will be reaped if this goes below the existential deposit.
574
+ */
575
+ get total() {
576
+ const extra = includeInTotalExtraAmount(this.#storage.extra);
577
+ return this.#format(this.free.planck + this.reserved.planck + extra);
578
+ }
579
+ /** The non-reserved balance of this token. Includes the frozen amount. Is included in the total. */
580
+ get free() {
581
+ var _this$storage$free;
582
+ return this.#format(typeof this.#storage.free === "string" ? BigInt(this.#storage.free) : Array.isArray(this.#storage.free) ? this.#storage.free.map(reserve => BigInt(reserve.amount)).reduce((a, b) => a + b, BigInt("0")) : BigInt(((_this$storage$free = this.#storage.free) === null || _this$storage$free === void 0 ? void 0 : _this$storage$free.amount) || "0"));
583
+ }
584
+ /** The reserved balance of this token. Is included in the total. */
585
+ get reserved() {
586
+ var _this$storage$reserve;
587
+ return this.#format(typeof this.#storage.reserves === "string" ? BigInt(this.#storage.reserves) : Array.isArray(this.#storage.reserves) ? this.#storage.reserves.map(reserve => BigInt(reserve.amount)).reduce((a, b) => a + b, BigInt("0")) : BigInt(((_this$storage$reserve = this.#storage.reserves) === null || _this$storage$reserve === void 0 ? void 0 : _this$storage$reserve.amount) || "0"));
588
+ }
589
+ /** The frozen balance of this token. Is included in the free amount. */
590
+ get locked() {
591
+ var _this$storage$locks;
592
+ return this.#format(typeof this.#storage.locks === "string" ? BigInt(this.#storage.locks) : Array.isArray(this.#storage.locks) ? this.#storage.locks.map(lock => BigInt(lock.amount)).reduce((a, b) => util.BigMath.max(a, b), BigInt("0")) : BigInt(((_this$storage$locks = this.#storage.locks) === null || _this$storage$locks === void 0 ? void 0 : _this$storage$locks.amount) || "0"));
593
+ }
594
+ /** @depreacted - use balance.locked */
595
+ get frozen() {
596
+ return this.locked;
597
+ }
598
+ /** The transferable balance of this token. Is generally the free amount - the miscFrozen amount. */
599
+ get transferable() {
600
+ // if no locks exist, transferable is equal to the free amount
601
+ if (!this.#storage.locks) return this.free;
602
+
603
+ // find the largest lock (but ignore any locks which are marked as `includeInTransferable`)
604
+ const excludeAmount = excludeFromTransferableAmount(this.#storage.locks);
605
+
606
+ // subtract the lock from the free amount (but don't go below 0)
607
+ return this.#format(util.BigMath.max(this.free.planck - excludeAmount, BigInt("0")));
608
+ }
609
+ /** The feePayable balance of this token. Is generally the free amount - the feeFrozen amount. */
610
+ get feePayable() {
611
+ // if no locks exist, feePayable is equal to the free amount
612
+ if (!this.#storage.locks) return this.free;
613
+
614
+ // find the largest lock which can't be used to pay tx fees
615
+ const excludeAmount = excludeFromFeePayableLocks(this.#storage.locks).map(lock => BigInt(lock.amount)).reduce((max, lock) => util.BigMath.max(max, lock), BigInt("0"));
616
+
617
+ // subtract the lock from the free amount (but don't go below 0)
618
+ return this.#format(util.BigMath.max(this.free.planck - excludeAmount, BigInt("0")));
619
+ }
620
+ }, (_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));
621
+ let BalanceFormatter = (_dec11 = typescriptMemoize.Memoize(), (_class3 = class BalanceFormatter {
622
+ #planck;
623
+ #decimals;
624
+ #fiatRatios;
625
+ constructor(planck, decimals, fiatRatios) {
626
+ this.#planck = typeof planck === "bigint" ? planck.toString() : planck ?? "0";
627
+ this.#decimals = decimals || 0;
628
+ this.#fiatRatios = fiatRatios || null;
629
+ this.fiat = memoize__default["default"](this.fiat);
630
+ }
631
+ toJSON = () => this.#planck;
632
+ get planck() {
633
+ return BigInt(this.#planck);
634
+ }
635
+ get tokens() {
636
+ return util.planckToTokens(this.#planck, this.#decimals);
637
+ }
638
+ fiat(currency) {
639
+ if (!this.#fiatRatios) return null;
640
+ const ratio = this.#fiatRatios[currency];
641
+ if (!ratio) return null;
642
+ return parseFloat(this.tokens) * ratio;
643
+ }
644
+ }, (_applyDecoratedDescriptor(_class3.prototype, "tokens", [_dec11], Object.getOwnPropertyDescriptor(_class3.prototype, "tokens"), _class3.prototype)), _class3));
645
+ 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 {
646
+ #balances;
647
+ #currency;
648
+ constructor(balances, currency) {
649
+ this.#balances = balances;
650
+ this.#currency = currency;
651
+ this.#sum = memoize__default["default"](this.#sum);
652
+ }
653
+ #sum = balanceField => {
654
+ // a function to get a fiat amount from a balance
655
+ const fiat = balance => balance[balanceField].fiat(this.#currency) || 0;
656
+
657
+ // a function to add two amounts
658
+ const sum = (a, b) => a + b;
659
+ return [...this.#balances].filter(filterMirrorTokens).reduce((total, balance) => sum(
660
+ // add the total amount...
661
+ total,
662
+ // ...to the fiat amount of each balance
663
+ fiat(balance)),
664
+ // start with a total of 0
665
+ 0);
666
+ };
667
+
668
+ /**
669
+ * The total balance of these tokens. Includes the free and the reserved amount.
670
+ */
671
+ get total() {
672
+ return this.#sum("total");
673
+ }
674
+ /** The non-reserved balance of these tokens. Includes the frozen amount. Is included in the total. */
675
+ get free() {
676
+ return this.#sum("free");
677
+ }
678
+ /** The reserved balance of these tokens. Is included in the total. */
679
+ get reserved() {
680
+ return this.#sum("reserved");
681
+ }
682
+ /** The frozen balance of these tokens. Is included in the free amount. */
683
+ get locked() {
684
+ return this.#sum("locked");
685
+ }
686
+ /** @deprecated - use balances.locked */
687
+ get frozen() {
688
+ return this.locked;
689
+ }
690
+ /** The transferable balance of these tokens. Is generally the free amount - the miscFrozen amount. */
691
+ get transferable() {
692
+ return this.#sum("transferable");
693
+ }
694
+ /** The feePayable balance of these tokens. Is generally the free amount - the feeFrozen amount. */
695
+ get feePayable() {
696
+ return this.#sum("feePayable");
697
+ }
698
+ }, (_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));
699
+ class SumBalancesFormatter {
700
+ #balances;
701
+ constructor(balances) {
702
+ this.#balances = balances;
703
+ this.fiat = memoize__default["default"](this.fiat);
704
+ }
705
+ fiat(currency) {
706
+ return new FiatSumBalancesFormatter(this.#balances, currency);
707
+ }
708
+ }
709
+
710
+ exports.Balance = Balance;
711
+ exports.BalanceFormatter = BalanceFormatter;
712
+ exports.Balances = Balances;
713
+ exports.DefaultBalanceModule = DefaultBalanceModule;
714
+ exports.FiatSumBalancesFormatter = FiatSumBalancesFormatter;
715
+ exports.StorageHelper = StorageHelper;
716
+ exports.SumBalancesFormatter = SumBalancesFormatter;
717
+ exports.TalismanBalancesDatabase = TalismanBalancesDatabase;
718
+ exports.balances = balances;
719
+ exports.db = db;
720
+ exports.excludeFromFeePayableLocks = excludeFromFeePayableLocks;
721
+ exports.excludeFromTransferableAmount = excludeFromTransferableAmount;
722
+ exports.filterMirrorTokens = filterMirrorTokens;
723
+ exports.includeInTotalExtraAmount = includeInTotalExtraAmount;