@talismn/balances 0.0.0-pr707-20230418101721 → 0.0.0-pr709-20230418123454

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.
@@ -4,13 +4,11 @@ Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var dexie = require('dexie');
6
6
  var types = require('@polkadot/types');
7
- var util = require('@talismn/util');
8
- var groupBy = require('lodash/groupBy');
9
7
  var anylogger = require('anylogger');
8
+ var util = require('@talismn/util');
10
9
 
11
10
  function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
12
11
 
13
- var groupBy__default = /*#__PURE__*/_interopDefault(groupBy);
14
12
  var anylogger__default = /*#__PURE__*/_interopDefault(anylogger);
15
13
 
16
14
  // TODO: Document default balances module purpose/usage
@@ -69,7 +67,7 @@ const db = new TalismanBalancesDatabase();
69
67
 
70
68
  var packageJson = {
71
69
  name: "@talismn/balances",
72
- version: "0.0.0-pr707-20230418101721",
70
+ version: "0.0.0-pr709-20230418123454",
73
71
  author: "Talisman",
74
72
  homepage: "https://talisman.xyz",
75
73
  license: "UNLICENSED",
@@ -96,28 +94,26 @@ var packageJson = {
96
94
  clean: "rm -rf dist && rm -rf .turbo rm -rf node_modules"
97
95
  },
98
96
  dependencies: {
99
- "@talismn/chain-connector": "workspace:*",
100
- "@talismn/chain-connector-evm": "workspace:*",
101
- "@talismn/chaindata-provider": "workspace:*",
102
- "@talismn/token-rates": "workspace:*",
103
- "@talismn/util": "workspace:*",
97
+ "@talismn/chain-connector": "workspace:^",
98
+ "@talismn/chain-connector-evm": "workspace:^",
99
+ "@talismn/chaindata-provider": "workspace:^",
100
+ "@talismn/token-rates": "workspace:^",
101
+ "@talismn/util": "workspace:^",
104
102
  anylogger: "^1.0.11",
105
- dexie: "^3.2.3",
106
- lodash: "4.17.21"
103
+ dexie: "^3.2.3"
107
104
  },
108
105
  devDependencies: {
109
- "@polkadot/types": "^10.1.4",
110
- "@talismn/eslint-config": "workspace:*",
111
- "@talismn/tsconfig": "workspace:*",
106
+ "@polkadot/types": "^9.10.5",
107
+ "@talismn/eslint-config": "workspace:^",
108
+ "@talismn/tsconfig": "workspace:^",
112
109
  "@types/jest": "^27.5.1",
113
- "@types/lodash": "^4.14.180",
114
110
  eslint: "^8.4.0",
115
111
  jest: "^28.1.0",
116
112
  "ts-jest": "^28.0.2",
117
113
  typescript: "^4.6.4"
118
114
  },
119
115
  peerDependencies: {
120
- "@polkadot/types": "10.x"
116
+ "@polkadot/types": "9.x"
121
117
  },
122
118
  preconstruct: {
123
119
  entrypoints: [
@@ -150,14 +146,8 @@ const createTypeRegistryCache = () => {
150
146
  if (cached) return cached;
151
147
  const typeRegistry = new types.TypeRegistry();
152
148
  if (typeof metadataRpc === "string") {
153
- try {
154
- const metadata = new types.Metadata(typeRegistry, metadataRpc);
155
- metadata.registry.setMetadata(metadata);
156
- } catch (cause) {
157
- log.warn(new Error(`Failed to set metadata for chain ${chainId}`, {
158
- cause
159
- }), cause);
160
- }
149
+ const metadata = new types.Metadata(typeRegistry, metadataRpc);
150
+ metadata.registry.setMetadata(metadata);
161
151
  }
162
152
  typeRegistryCache.set(chainId, typeRegistry);
163
153
  return typeRegistry;
@@ -296,77 +286,11 @@ class StorageHelper {
296
286
  }
297
287
  }
298
288
 
299
- /**
300
- * Pass some these into an `RpcStateQueryHelper` in order to easily batch multiple state queries into the one rpc call.
301
- */
302
-
303
- /**
304
- * Used by a variety of balance modules to help batch multiple state queries into the one rpc call.
305
- */
306
- class RpcStateQueryHelper {
307
- #chainConnector;
308
- #queries;
309
- constructor(chainConnector, queries) {
310
- this.#chainConnector = chainConnector;
311
- this.#queries = queries;
312
- }
313
- async subscribe(callback, timeout = false, subscribeMethod = "state_subscribeStorage", responseMethod = "state_storage", unsubscribeMethod = "state_unsubscribeStorage") {
314
- const queriesByChain = groupBy__default["default"](this.#queries, "chainId");
315
- const subscriptions = Object.entries(queriesByChain).map(([chainId, queries]) => {
316
- const params = [queries.map(({
317
- stateKey
318
- }) => stateKey)];
319
- const unsub = this.#chainConnector.subscribe(chainId, subscribeMethod, responseMethod, params, (error, result) => {
320
- error ? callback(error) : callback(null, this.#distributeChangesToQueryDecoders.call(this, chainId, result));
321
- }, timeout);
322
- return () => unsub.then(unsubscribe => unsubscribe(unsubscribeMethod));
323
- });
324
- return () => subscriptions.forEach(unsubscribe => unsubscribe());
325
- }
326
- async fetch(method = "state_queryStorageAt") {
327
- const queriesByChain = groupBy__default["default"](this.#queries, "chainId");
328
- const resultsByChain = await Promise.all(Object.entries(queriesByChain).map(async ([chainId, queries]) => {
329
- const params = [queries.map(({
330
- stateKey
331
- }) => stateKey)];
332
- const result = (await this.#chainConnector.send(chainId, method, params))[0];
333
- return this.#distributeChangesToQueryDecoders.call(this, chainId, result);
334
- }));
335
- return resultsByChain.flatMap(result => result);
336
- }
337
- #distributeChangesToQueryDecoders(chainId, result) {
338
- if (typeof result !== "object" || result === null) return [];
339
- if (!util.hasOwnProperty(result, "changes") || typeof result.changes !== "object") return [];
340
- if (!Array.isArray(result.changes)) return [];
341
- return result.changes.flatMap(([reference, change]) => {
342
- if (typeof reference !== "string") {
343
- log.warn(`Received non-string reference in RPC result: ${reference}`);
344
- return [];
345
- }
346
- if (typeof change !== "string" && change !== null) {
347
- log.warn(`Received non-string and non-null change in RPC result: ${reference} | ${change}`);
348
- return [];
349
- }
350
- const query = this.#queries.find(({
351
- chainId: cId,
352
- stateKey
353
- }) => cId === chainId && stateKey === reference);
354
- if (!query) {
355
- log.warn(`Failed to find query:\n${reference} in\n${this.#queries.map(({
356
- stateKey
357
- }) => stateKey)}`);
358
- return [];
359
- }
360
- return [query.decodeResult(change)];
361
- });
362
- }
363
- }
364
-
365
289
  const BalanceStatusLive = subscriptionId => `live-${subscriptionId}`;
366
290
  function excludeFromTransferableAmount(locks) {
367
291
  if (typeof locks === "string") return BigInt(locks);
368
292
  if (!Array.isArray(locks)) locks = [locks];
369
- return locks.filter(lock => lock.includeInTransferable !== true).map(lock => BigInt(lock.amount)).reduce((max, lock) => util.BigMath.max(max, lock), 0n);
293
+ return locks.filter(lock => lock.includeInTransferable !== true).map(lock => BigInt(lock.amount)).reduce((max, lock) => util.BigMath.max(max, lock), BigInt("0"));
370
294
  }
371
295
  function excludeFromFeePayableLocks(locks) {
372
296
  if (typeof locks === "string") return [];
@@ -377,9 +301,9 @@ function excludeFromFeePayableLocks(locks) {
377
301
  /** A labelled extra amount of a balance */
378
302
 
379
303
  function includeInTotalExtraAmount(extra) {
380
- if (!extra) return 0n;
304
+ if (!extra) return BigInt("0");
381
305
  if (!Array.isArray(extra)) extra = [extra];
382
- return extra.filter(extra => extra.includeInTotal).map(extra => BigInt(extra.amount)).reduce((a, b) => a + b, 0n);
306
+ return extra.filter(extra => extra.includeInTotal).map(extra => BigInt(extra.amount)).reduce((a, b) => a + b, BigInt("0"));
383
307
  }
384
308
 
385
309
  /** Used by plugins to help define their custom `BalanceType` */
@@ -490,27 +414,6 @@ class Balances {
490
414
  return new Balances([...this].filter(filter));
491
415
  };
492
416
 
493
- /**
494
- * Filters this collection to exclude token balances where the token has a `mirrorOf` field
495
- * and another balance exists in this collection for the token specified by the `mirrorOf` field.
496
- */
497
- filterMirrorTokens = () => new Balances([...this].filter(filterMirrorTokens));
498
-
499
- /**
500
- * Filters this collection to only include balances which are not zero.
501
- */
502
- filterNonZero = type => {
503
- const filter = balance => balance[type].planck > 0n;
504
- return this.find(filter);
505
- };
506
- /**
507
- * Filters this collection to only include balances which are not zero AND have a fiat conversion rate.
508
- */
509
- filterNonZeroFiat = (type, currency) => {
510
- const filter = balance => (balance[type].fiat(currency) ?? 0) > 0;
511
- return this.find(filter);
512
- };
513
-
514
417
  /**
515
418
  * Add some balances to this collection.
516
419
  * Added balances take priority over existing balances.
@@ -633,14 +536,13 @@ class Balance {
633
536
  get id() {
634
537
  const {
635
538
  source,
636
- subSource,
637
539
  address,
638
540
  chainId,
639
541
  evmNetworkId,
640
542
  tokenId
641
543
  } = this.#storage;
642
544
  const locationId = chainId !== undefined ? chainId : evmNetworkId;
643
- return [source, address, locationId, tokenId, subSource].filter(Boolean).join("-");
545
+ return `${source}-${address}-${locationId}-${tokenId}`;
644
546
  }
645
547
  get source() {
646
548
  return this.#storage.source;
@@ -689,43 +591,17 @@ class Balance {
689
591
  }
690
592
  /** The non-reserved balance of this token. Includes the frozen amount. Is included in the total. */
691
593
  get free() {
692
- 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, 0n) : BigInt(this.#storage.free?.amount || "0"));
594
+ 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"));
693
595
  }
694
596
  /** The reserved balance of this token. Is included in the total. */
695
597
  get reserved() {
696
- 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, 0n) : BigInt(this.#storage.reserves?.amount || "0"));
697
- }
698
- get reserves() {
699
- return (Array.isArray(this.#storage.reserves) ? this.#storage.reserves : [this.#storage.reserves]).flatMap(reserve => {
700
- if (reserve === undefined) return [];
701
- if (typeof reserve === "string") return {
702
- label: "reserved",
703
- amount: this.#format(reserve)
704
- };
705
- return {
706
- ...reserve,
707
- amount: this.#format(reserve.amount)
708
- };
709
- });
598
+ 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"));
710
599
  }
711
600
  /** The frozen balance of this token. Is included in the free amount. */
712
601
  get locked() {
713
- 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), 0n) : BigInt(this.#storage.locks?.amount || "0"));
714
- }
715
- get locks() {
716
- return (Array.isArray(this.#storage.locks) ? this.#storage.locks : [this.#storage.locks]).flatMap(lock => {
717
- if (lock === undefined) return [];
718
- if (typeof lock === "string") return {
719
- label: "other",
720
- amount: this.#format(lock)
721
- };
722
- return {
723
- ...lock,
724
- amount: this.#format(lock.amount)
725
- };
726
- });
602
+ 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"));
727
603
  }
728
- /** @deprecated Use balance.locked */
604
+ /** @depreacted - use balance.locked */
729
605
  get frozen() {
730
606
  return this.locked;
731
607
  }
@@ -738,7 +614,7 @@ class Balance {
738
614
  const excludeAmount = excludeFromTransferableAmount(this.#storage.locks);
739
615
 
740
616
  // subtract the lock from the free amount (but don't go below 0)
741
- return this.#format(util.BigMath.max(this.free.planck - excludeAmount, 0n));
617
+ return this.#format(util.BigMath.max(this.free.planck - excludeAmount, BigInt("0")));
742
618
  }
743
619
  /** The feePayable balance of this token. Is generally the free amount - the feeFrozen amount. */
744
620
  get feePayable() {
@@ -746,10 +622,10 @@ class Balance {
746
622
  if (!this.#storage.locks) return this.free;
747
623
 
748
624
  // find the largest lock which can't be used to pay tx fees
749
- const excludeAmount = excludeFromFeePayableLocks(this.#storage.locks).map(lock => BigInt(lock.amount)).reduce((max, lock) => util.BigMath.max(max, lock), 0n);
625
+ const excludeAmount = excludeFromFeePayableLocks(this.#storage.locks).map(lock => BigInt(lock.amount)).reduce((max, lock) => util.BigMath.max(max, lock), BigInt("0"));
750
626
 
751
627
  // subtract the lock from the free amount (but don't go below 0)
752
- return this.#format(util.BigMath.max(this.free.planck - excludeAmount, 0n));
628
+ return this.#format(util.BigMath.max(this.free.planck - excludeAmount, BigInt("0")));
753
629
  }
754
630
  }
755
631
  class BalanceFormatter {
@@ -775,52 +651,6 @@ class BalanceFormatter {
775
651
  return parseFloat(this.tokens) * ratio;
776
652
  }
777
653
  }
778
- class PlanckSumBalancesFormatter {
779
- #balances;
780
- constructor(balances) {
781
- this.#balances = balances;
782
- }
783
- #sum = balanceField => {
784
- // a function to get a planck amount from a balance
785
- const planck = balance => balance[balanceField].planck ?? 0n;
786
- return this.#balances.filterMirrorTokens().each.reduce(
787
- // add the total amount to the planck amount of each balance
788
- (total, balance) => total + planck(balance),
789
- // start with a total of 0
790
- 0n);
791
- };
792
-
793
- /**
794
- * The total balance of these tokens. Includes the free and the reserved amount.
795
- */
796
- get total() {
797
- return this.#sum("total");
798
- }
799
- /** The non-reserved balance of these tokens. Includes the frozen amount. Is included in the total. */
800
- get free() {
801
- return this.#sum("free");
802
- }
803
- /** The reserved balance of these tokens. Is included in the total. */
804
- get reserved() {
805
- return this.#sum("reserved");
806
- }
807
- /** The frozen balance of these tokens. Is included in the free amount. */
808
- get locked() {
809
- return this.#sum("locked");
810
- }
811
- /** @deprecated Use balances.locked */
812
- get frozen() {
813
- return this.locked;
814
- }
815
- /** The transferable balance of these tokens. Is generally the free amount - the miscFrozen amount. */
816
- get transferable() {
817
- return this.#sum("transferable");
818
- }
819
- /** The feePayable balance of these tokens. Is generally the free amount - the feeFrozen amount. */
820
- get feePayable() {
821
- return this.#sum("feePayable");
822
- }
823
- }
824
654
  class FiatSumBalancesFormatter {
825
655
  #balances;
826
656
  #currency;
@@ -830,10 +660,15 @@ class FiatSumBalancesFormatter {
830
660
  }
831
661
  #sum = balanceField => {
832
662
  // a function to get a fiat amount from a balance
833
- const fiat = balance => balance[balanceField].fiat(this.#currency) ?? 0;
834
- return this.#balances.filterMirrorTokens().each.reduce(
835
- // add the total amount to the fiat amount of each balance
836
- (total, balance) => total + fiat(balance),
663
+ const fiat = balance => balance[balanceField].fiat(this.#currency) || 0;
664
+
665
+ // a function to add two amounts
666
+ const sum = (a, b) => a + b;
667
+ return [...this.#balances].filter(filterMirrorTokens).reduce((total, balance) => sum(
668
+ // add the total amount...
669
+ total,
670
+ // ...to the fiat amount of each balance
671
+ fiat(balance)),
837
672
  // start with a total of 0
838
673
  0);
839
674
  };
@@ -856,7 +691,7 @@ class FiatSumBalancesFormatter {
856
691
  get locked() {
857
692
  return this.#sum("locked");
858
693
  }
859
- /** @deprecated Use balances.locked */
694
+ /** @deprecated - use balances.locked */
860
695
  get frozen() {
861
696
  return this.locked;
862
697
  }
@@ -874,9 +709,6 @@ class SumBalancesFormatter {
874
709
  constructor(balances) {
875
710
  this.#balances = balances;
876
711
  }
877
- get planck() {
878
- return new PlanckSumBalancesFormatter(this.#balances);
879
- }
880
712
  fiat(currency) {
881
713
  return new FiatSumBalancesFormatter(this.#balances, currency);
882
714
  }
@@ -888,8 +720,6 @@ exports.BalanceStatusLive = BalanceStatusLive;
888
720
  exports.Balances = Balances;
889
721
  exports.DefaultBalanceModule = DefaultBalanceModule;
890
722
  exports.FiatSumBalancesFormatter = FiatSumBalancesFormatter;
891
- exports.PlanckSumBalancesFormatter = PlanckSumBalancesFormatter;
892
- exports.RpcStateQueryHelper = RpcStateQueryHelper;
893
723
  exports.StorageHelper = StorageHelper;
894
724
  exports.SumBalancesFormatter = SumBalancesFormatter;
895
725
  exports.TalismanBalancesDatabase = TalismanBalancesDatabase;