@talismn/balances 0.2.3 → 0.3.1

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 +31 -0
  2. package/dist/{BalanceModule.d.ts → declarations/src/BalanceModule.d.ts} +7 -7
  3. package/dist/{TalismanBalancesDatabase.d.ts → declarations/src/TalismanBalancesDatabase.d.ts} +0 -0
  4. package/dist/{helpers.d.ts → declarations/src/helpers.d.ts} +17 -1
  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} +0 -0
  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 +12 -12
  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 +705 -0
  15. package/dist/talismn-balances.cjs.js +7 -0
  16. package/dist/talismn-balances.cjs.prod.js +705 -0
  17. package/dist/talismn-balances.esm.js +683 -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 -3
  25. package/dist/BalanceModule.js +0 -29
  26. package/dist/TalismanBalancesDatabase.js +0 -23
  27. package/dist/helpers.js +0 -11
  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 -470
  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,705 @@
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.3.1",
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
+ // TODO implement a mirrorOf property, which should be set from chaindata
146
+ const mirrorOf = balance.token?.mirrorOf;
147
+ return !mirrorOf || !balances.find(b => b.tokenId === mirrorOf);
148
+ };
149
+
150
+ /**
151
+ * Used by a variety of balance modules to help encode and decode substrate state calls.
152
+ */
153
+ class StorageHelper {
154
+ #registry;
155
+ #storageKey;
156
+ #module;
157
+ #method;
158
+ #parameters;
159
+ tags = null;
160
+ constructor(registry, module, method, ...parameters) {
161
+ this.#registry = registry;
162
+ this.#module = module;
163
+ this.#method = method;
164
+ this.#parameters = parameters;
165
+ const _metadataVersion = 0; // is not used inside the decorateStorage function
166
+ let query;
167
+ try {
168
+ query = types.decorateStorage(registry, registry.metadata, _metadataVersion);
169
+ } catch (error) {
170
+ log.debug(`Failed to decorate storage: ${error.message}`);
171
+ this.#storageKey = null;
172
+ }
173
+ try {
174
+ if (!query) throw new Error(`decoratedStorage unavailable`);
175
+ this.#storageKey = new types.StorageKey(registry, parameters ? [query[module][method], parameters] : query[module][method]);
176
+ } catch (error) {
177
+ log.debug(`Failed to create storageKey ${module || "unknown"}.${method || "unknown"}: ${error.message}`);
178
+ this.#storageKey = null;
179
+ }
180
+ }
181
+ get stateKey() {
182
+ return this.#storageKey?.toHex();
183
+ }
184
+ get module() {
185
+ return this.#module;
186
+ }
187
+ get method() {
188
+ return this.#method;
189
+ }
190
+ get parameters() {
191
+ return this.#parameters;
192
+ }
193
+ tag(tags) {
194
+ this.tags = tags;
195
+ return this;
196
+ }
197
+ decode(input) {
198
+ if (!this.#storageKey) return;
199
+ return this.#decodeStorageScaleResponse(this.#registry, this.#storageKey, input);
200
+ }
201
+ #decodeStorageScaleResponse(typeRegistry, storageKey, input) {
202
+ if (input === undefined || input === null) return;
203
+ const type = storageKey.outputType || "Raw";
204
+ const meta = storageKey.meta || {
205
+ fallback: undefined,
206
+ modifier: {
207
+ isOptional: true
208
+ },
209
+ type: {
210
+ asMap: {
211
+ linked: {
212
+ isTrue: false
213
+ }
214
+ },
215
+ isMap: false
216
+ }
217
+ };
218
+ try {
219
+ return typeRegistry.createTypeUnsafe(type, [meta.modifier.isOptional ? typeRegistry.createTypeUnsafe(type, [input], {
220
+ isPedantic: true
221
+ }) : input], {
222
+ isOptional: meta.modifier.isOptional,
223
+ isPedantic: !meta.modifier.isOptional
224
+ });
225
+ } catch (error) {
226
+ throw new Error(`Unable to decode storage ${storageKey.section || "unknown"}.${storageKey.method || "unknown"}: ${error.message}`);
227
+ }
228
+ }
229
+ }
230
+
231
+ function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
232
+ var desc = {};
233
+ Object.keys(descriptor).forEach(function (key) {
234
+ desc[key] = descriptor[key];
235
+ });
236
+ desc.enumerable = !!desc.enumerable;
237
+ desc.configurable = !!desc.configurable;
238
+ if ('value' in desc || desc.initializer) {
239
+ desc.writable = true;
240
+ }
241
+ desc = decorators.slice().reverse().reduce(function (desc, decorator) {
242
+ return decorator(target, property, desc) || desc;
243
+ }, desc);
244
+ if (context && desc.initializer !== void 0) {
245
+ desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
246
+ desc.initializer = undefined;
247
+ }
248
+ if (desc.initializer === void 0) {
249
+ Object.defineProperty(target, property, desc);
250
+ desc = null;
251
+ }
252
+ return desc;
253
+ }
254
+
255
+ function excludeFromTransferableAmount(locks) {
256
+ if (typeof locks === "string") return BigInt(locks);
257
+ if (!Array.isArray(locks)) locks = [locks];
258
+ return locks.filter(lock => lock.includeInTransferable !== true).map(lock => BigInt(lock.amount)).reduce((max, lock) => util.BigMath.max(max, lock), BigInt("0"));
259
+ }
260
+ function excludeFromFeePayableLocks(locks) {
261
+ if (typeof locks === "string") return [];
262
+ if (!Array.isArray(locks)) locks = [locks];
263
+ return locks.filter(lock => lock.excludeFromFeePayable);
264
+ }
265
+
266
+ /** A labelled extra amount of a balance */
267
+
268
+ function includeInTotalExtraAmount(extra) {
269
+ if (!extra) return BigInt("0");
270
+ if (!Array.isArray(extra)) extra = [extra];
271
+ return extra.filter(extra => extra.includeInTotal).map(extra => BigInt(extra.amount)).reduce((a, b) => a + b, BigInt("0"));
272
+ }
273
+
274
+ /** Used by plugins to help define their custom `BalanceType` */
275
+
276
+ var _dec, _dec2, _dec3, _class, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10, _class2, _dec11, _class3, _dec12, _dec13, _dec14, _dec15, _dec16, _dec17, _dec18, _class4;
277
+
278
+ /**
279
+ * Have the importing library define its Token and BalanceJson enums (as a sum type of all plugins) and pass them into some
280
+ * internal global typescript context, which is then picked up on by this module.
281
+ */
282
+
283
+ /** A utility type used to extract the underlying `BalanceType` of a specific source from a generalised `BalanceJson` */
284
+
285
+ /**
286
+ * A collection of balances.
287
+ */
288
+ let Balances = (_dec = typescriptMemoize.Memoize(), _dec2 = typescriptMemoize.Memoize(), _dec3 = typescriptMemoize.Memoize(), (_class = class Balances {
289
+ //
290
+ // Properties
291
+ //
292
+
293
+ #balances = {};
294
+
295
+ //
296
+ // Methods
297
+ //
298
+
299
+ constructor(balances, hydrate) {
300
+ // handle Balances (convert to Balance[])
301
+ if (balances instanceof Balances) return new Balances([...balances], hydrate);
302
+
303
+ // handle Balance (convert to Balance[])
304
+ if (balances instanceof Balance) return new Balances([balances], hydrate);
305
+
306
+ // handle BalanceJsonList (the only remaining non-array type of balances) (convert to BalanceJson[])
307
+ if (!Array.isArray(balances)) return new Balances(Object.values(balances), hydrate);
308
+
309
+ // handle no balances
310
+ if (balances.length === 0) return this;
311
+
312
+ // handle BalanceJson[]
313
+ if (!util.isArrayOf(balances, Balance)) return new Balances(balances.map(storage => new Balance(storage)), hydrate);
314
+
315
+ // handle Balance[]
316
+ this.#balances = Object.fromEntries(balances.map(balance => [balance.id, balance]));
317
+ if (hydrate !== undefined) this.hydrate(hydrate);
318
+ }
319
+
320
+ /**
321
+ * Calling toJSON on a collection of balances will return the underlying BalanceJsonList.
322
+ */
323
+ toJSON = () => Object.fromEntries(Object.entries(this.#balances).map(([id, balance]) => {
324
+ try {
325
+ return [id, balance.toJSON()];
326
+ } catch (error) {
327
+ log.error("Failed to convert balance to JSON", error, {
328
+ id,
329
+ balance
330
+ });
331
+ return null;
332
+ }
333
+ }).filter(Array.isArray));
334
+
335
+ /**
336
+ * Allows the collection to be iterated over.
337
+ *
338
+ * @example
339
+ * [...balances].forEach(balance => { // do something // })
340
+ *
341
+ * @example
342
+ * for (const balance of balances) {
343
+ * // do something
344
+ * }
345
+ */
346
+ [Symbol.iterator] = () =>
347
+ // Create an array of the balances in this collection and return the result of its iterator.
348
+ Object.values(this.#balances)[Symbol.iterator]();
349
+
350
+ /**
351
+ * Hydrates all balances in this collection.
352
+ *
353
+ * @param sources - The sources to hydrate from.
354
+ */
355
+ hydrate = sources => {
356
+ Object.values(this.#balances).map(balance => balance.hydrate(sources));
357
+ };
358
+
359
+ /**
360
+ * Retrieve a balance from this collection by id.
361
+ *
362
+ * @param id - The id of the balance to fetch.
363
+ * @returns The balance if one exists, or none.
364
+ */
365
+ get = id => this.#balances[id] || null;
366
+
367
+ /**
368
+ * Retrieve balances from this collection by search query.
369
+ *
370
+ * @param query - The search query.
371
+ * @returns All balances which match the query.
372
+ */
373
+ find = query => {
374
+ // construct filter
375
+ const orQueries = (Array.isArray(query) ? query : [query]).map(query => typeof query === "function" ? query : Object.entries(query));
376
+
377
+ // filter balances
378
+ const filter = balance => orQueries.some(query => typeof query === "function" ? query(balance) : query.every(([key, value]) => balance[key] === value));
379
+
380
+ // return filter matches
381
+ return new Balances([...this].filter(filter));
382
+ };
383
+
384
+ /**
385
+ * Add some balances to this collection.
386
+ * Added balances take priority over existing balances.
387
+ * The aggregation of the two collections is returned.
388
+ * The original collection is not mutated.
389
+ *
390
+ * @param balances - Either a balance or collection of balances to add.
391
+ * @returns The new collection of balances.
392
+ */
393
+ add = balances => {
394
+ // handle single balance
395
+ if (balances instanceof Balance) return this.add(new Balances(balances));
396
+
397
+ // merge balances
398
+ const mergedBalances = {
399
+ ...this.#balances
400
+ };
401
+ [...balances].forEach(balance => mergedBalances[balance.id] = balance);
402
+
403
+ // return new balances
404
+ return new Balances(Object.values(mergedBalances));
405
+ };
406
+
407
+ /**
408
+ * Remove balances from this collection by id.
409
+ * A new collection without these balances is returned.
410
+ * The original collection is not mutated.
411
+ *
412
+ * @param ids - The id(s) of the balances to remove.
413
+ * @returns The new collection of balances.
414
+ */
415
+ remove = ids => {
416
+ // handle single id
417
+ if (!Array.isArray(ids)) return this.remove([ids]);
418
+
419
+ // merge balances
420
+ const removedBalances = {
421
+ ...this.#balances
422
+ };
423
+ ids.forEach(id => delete removedBalances[id]);
424
+
425
+ // return new balances
426
+ return new Balances(Object.values(removedBalances));
427
+ };
428
+
429
+ // TODO: Add some more useful aggregator methods
430
+
431
+ /**
432
+ * Get an array of balances in this collection, sorted by chain sortIndex.
433
+ *
434
+ * @returns A sorted array of the balances in this collection.
435
+ */
436
+ get sorted() {
437
+ return [...this].sort((a, b) => ((a.chain || a.evmNetwork)?.sortIndex || Number.MAX_SAFE_INTEGER) - ((b.chain || b.evmNetwork)?.sortIndex || Number.MAX_SAFE_INTEGER));
438
+ }
439
+
440
+ /**
441
+ * Get the number of balances in this collection.
442
+ *
443
+ * @returns The number of balances in this collection.
444
+ */
445
+ get count() {
446
+ return [...this].length;
447
+ }
448
+
449
+ /**
450
+ * Get the summed value of balances in this collection.
451
+ * TODO: Sum up token amounts AND fiat amounts
452
+ *
453
+ * @example
454
+ * // Get the sum of all transferable balances in usd.
455
+ * balances.sum.fiat('usd').transferable
456
+ */
457
+ get sum() {
458
+ return new SumBalancesFormatter(this);
459
+ }
460
+ }, (_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));
461
+
462
+ /**
463
+ * An individual balance.
464
+ */
465
+ 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 {
466
+ //
467
+ // Properties
468
+ //
469
+
470
+ /** The underlying data for this balance */
471
+ #storage;
472
+ #db = null;
473
+
474
+ //
475
+ // Methods
476
+ //
477
+
478
+ constructor(storage, hydrate) {
479
+ this.#format = memoize__default["default"](this.#format);
480
+ this.#storage = storage;
481
+ if (hydrate !== undefined) this.hydrate(hydrate);
482
+ }
483
+ toJSON = () => this.#storage;
484
+ isSource = source => this.#storage.source === source;
485
+ // // TODO: Fix this method, the types don't work with our plugin architecture.
486
+ // // Specifically, the `BalanceJson` type is compiled down to `IBalance` in the following way:
487
+ // //
488
+ // // toJSON: () => BalanceJson // works
489
+ // // isSource: (source: BalanceSource) => boolean // works
490
+ // // asSource: <P extends string>(source: P) => NarrowBalanceType<IBalance, P> | null // Doesn't work! IBalance should just be BalanceJson!
491
+ // //
492
+ // // `IBalance` won't match the type of `BalanceSource` after `PluginBalanceTypes` has been extended by balance plugins.
493
+ // // As a result, typescript will think that the returned #storage is not a BalanceJson.
494
+ // asSource = <P extends BalanceSource>(source: P): NarrowBalanceType<BalanceJson, P> | null => {
495
+ // if (this.#storage.source === source) return this.#storage as NarrowBalanceType<BalanceJson, P>
496
+ // return null
497
+ // }
498
+
499
+ hydrate = hydrate => {
500
+ if (hydrate !== undefined) this.#db = hydrate;
501
+ };
502
+ #format = balance => new BalanceFormatter(typeof balance === "bigint" ? balance.toString() : balance, this.decimals || undefined, this.#db?.tokenRates && this.#db.tokenRates[this.tokenId]);
503
+
504
+ //
505
+ // Accessors
506
+ //
507
+
508
+ get id() {
509
+ const {
510
+ source,
511
+ address,
512
+ chainId,
513
+ evmNetworkId,
514
+ tokenId
515
+ } = this.#storage;
516
+ const locationId = chainId !== undefined ? chainId : evmNetworkId;
517
+ return `${source}-${address}-${locationId}-${tokenId}`;
518
+ }
519
+ get source() {
520
+ return this.#storage.source;
521
+ }
522
+ get status() {
523
+ return this.#storage.status;
524
+ }
525
+ get address() {
526
+ return this.#storage.address;
527
+ }
528
+ get chainId() {
529
+ return this.#storage.chainId;
530
+ }
531
+ get chain() {
532
+ return this.#db?.chains && this.chainId && this.#db?.chains[this.chainId] || null;
533
+ }
534
+ get evmNetworkId() {
535
+ return this.#storage.evmNetworkId;
536
+ }
537
+ get evmNetwork() {
538
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
539
+ return this.#db?.evmNetworks && this.#db?.evmNetworks[this.evmNetworkId] || null;
540
+ }
541
+ get tokenId() {
542
+ return this.#storage.tokenId;
543
+ }
544
+ get token() {
545
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
546
+ return this.#db?.tokens && this.#db?.tokens[this.tokenId] || null;
547
+ }
548
+ get decimals() {
549
+ return this.token?.decimals || null;
550
+ }
551
+ get rates() {
552
+ return this.#db?.tokenRates && this.#db.tokenRates[this.tokenId] || null;
553
+ }
554
+
555
+ /**
556
+ * The total balance of this token.
557
+ * Includes the free and the reserved amount.
558
+ * The balance will be reaped if this goes below the existential deposit.
559
+ */
560
+ get total() {
561
+ const extra = includeInTotalExtraAmount(this.#storage.extra);
562
+ return this.#format(this.free.planck + this.reserved.planck + extra);
563
+ }
564
+ /** The non-reserved balance of this token. Includes the frozen amount. Is included in the total. */
565
+ get free() {
566
+ 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?.amount || "0"));
567
+ }
568
+ /** The reserved balance of this token. Is included in the total. */
569
+ get reserved() {
570
+ 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.reserves?.amount || "0"));
571
+ }
572
+ /** The frozen balance of this token. Is included in the free amount. */
573
+ get locked() {
574
+ 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?.amount || "0"));
575
+ }
576
+ /** @depreacted - use balance.locked */
577
+ get frozen() {
578
+ return this.locked;
579
+ }
580
+ /** The transferable balance of this token. Is generally the free amount - the miscFrozen amount. */
581
+ get transferable() {
582
+ // if no locks exist, transferable is equal to the free amount
583
+ if (!this.#storage.locks) return this.free;
584
+
585
+ // find the largest lock (but ignore any locks which are marked as `includeInTransferable`)
586
+ const excludeAmount = excludeFromTransferableAmount(this.#storage.locks);
587
+
588
+ // subtract the lock from the free amount (but don't go below 0)
589
+ return this.#format(util.BigMath.max(this.free.planck - excludeAmount, BigInt("0")));
590
+ }
591
+ /** The feePayable balance of this token. Is generally the free amount - the feeFrozen amount. */
592
+ get feePayable() {
593
+ // if no locks exist, feePayable is equal to the free amount
594
+ if (!this.#storage.locks) return this.free;
595
+
596
+ // find the largest lock which can't be used to pay tx fees
597
+ const excludeAmount = excludeFromFeePayableLocks(this.#storage.locks).map(lock => BigInt(lock.amount)).reduce((max, lock) => util.BigMath.max(max, lock), BigInt("0"));
598
+
599
+ // subtract the lock from the free amount (but don't go below 0)
600
+ return this.#format(util.BigMath.max(this.free.planck - excludeAmount, BigInt("0")));
601
+ }
602
+ }, (_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));
603
+ let BalanceFormatter = (_dec11 = typescriptMemoize.Memoize(), (_class3 = class BalanceFormatter {
604
+ #planck;
605
+ #decimals;
606
+ #fiatRatios;
607
+ constructor(planck, decimals, fiatRatios) {
608
+ this.#planck = typeof planck === "bigint" ? planck.toString() : planck ?? "0";
609
+ this.#decimals = decimals || 0;
610
+ this.#fiatRatios = fiatRatios || null;
611
+ this.fiat = memoize__default["default"](this.fiat);
612
+ }
613
+ toJSON = () => this.#planck;
614
+ get planck() {
615
+ return BigInt(this.#planck);
616
+ }
617
+ get tokens() {
618
+ return util.planckToTokens(this.#planck, this.#decimals);
619
+ }
620
+ fiat(currency) {
621
+ if (!this.#fiatRatios) return null;
622
+ const ratio = this.#fiatRatios[currency];
623
+ if (!ratio) return null;
624
+ return parseFloat(this.tokens) * ratio;
625
+ }
626
+ }, (_applyDecoratedDescriptor(_class3.prototype, "tokens", [_dec11], Object.getOwnPropertyDescriptor(_class3.prototype, "tokens"), _class3.prototype)), _class3));
627
+ 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 {
628
+ #balances;
629
+ #currency;
630
+ constructor(balances, currency) {
631
+ this.#balances = balances;
632
+ this.#currency = currency;
633
+ this.#sum = memoize__default["default"](this.#sum);
634
+ }
635
+ #sum = balanceField => {
636
+ // a function to get a fiat amount from a balance
637
+ const fiat = balance => balance[balanceField].fiat(this.#currency) || 0;
638
+
639
+ // a function to add two amounts
640
+ const sum = (a, b) => a + b;
641
+ return [...this.#balances].filter(filterMirrorTokens).reduce((total, balance) => sum(
642
+ // add the total amount...
643
+ total,
644
+ // ...to the fiat amount of each balance
645
+ fiat(balance)),
646
+ // start with a total of 0
647
+ 0);
648
+ };
649
+
650
+ /**
651
+ * The total balance of these tokens. Includes the free and the reserved amount.
652
+ */
653
+ get total() {
654
+ return this.#sum("total");
655
+ }
656
+ /** The non-reserved balance of these tokens. Includes the frozen amount. Is included in the total. */
657
+ get free() {
658
+ return this.#sum("free");
659
+ }
660
+ /** The reserved balance of these tokens. Is included in the total. */
661
+ get reserved() {
662
+ return this.#sum("reserved");
663
+ }
664
+ /** The frozen balance of these tokens. Is included in the free amount. */
665
+ get locked() {
666
+ return this.#sum("locked");
667
+ }
668
+ /** @deprecated - use balances.locked */
669
+ get frozen() {
670
+ return this.locked;
671
+ }
672
+ /** The transferable balance of these tokens. Is generally the free amount - the miscFrozen amount. */
673
+ get transferable() {
674
+ return this.#sum("transferable");
675
+ }
676
+ /** The feePayable balance of these tokens. Is generally the free amount - the feeFrozen amount. */
677
+ get feePayable() {
678
+ return this.#sum("feePayable");
679
+ }
680
+ }, (_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));
681
+ class SumBalancesFormatter {
682
+ #balances;
683
+ constructor(balances) {
684
+ this.#balances = balances;
685
+ this.fiat = memoize__default["default"](this.fiat);
686
+ }
687
+ fiat(currency) {
688
+ return new FiatSumBalancesFormatter(this.#balances, currency);
689
+ }
690
+ }
691
+
692
+ exports.Balance = Balance;
693
+ exports.BalanceFormatter = BalanceFormatter;
694
+ exports.Balances = Balances;
695
+ exports.DefaultBalanceModule = DefaultBalanceModule;
696
+ exports.FiatSumBalancesFormatter = FiatSumBalancesFormatter;
697
+ exports.StorageHelper = StorageHelper;
698
+ exports.SumBalancesFormatter = SumBalancesFormatter;
699
+ exports.TalismanBalancesDatabase = TalismanBalancesDatabase;
700
+ exports.balances = balances;
701
+ exports.db = db;
702
+ exports.excludeFromFeePayableLocks = excludeFromFeePayableLocks;
703
+ exports.excludeFromTransferableAmount = excludeFromTransferableAmount;
704
+ exports.filterMirrorTokens = filterMirrorTokens;
705
+ exports.includeInTotalExtraAmount = includeInTotalExtraAmount;