@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.
@@ -1,8 +1,7 @@
1
1
  import { Dexie } from 'dexie';
2
2
  import { decorateStorage, StorageKey, TypeRegistry, Metadata } from '@polkadot/types';
3
- import { hasOwnProperty, BigMath, isArrayOf, planckToTokens } from '@talismn/util';
4
- import groupBy from 'lodash/groupBy';
5
3
  import anylogger from 'anylogger';
4
+ import { BigMath, isArrayOf, planckToTokens } from '@talismn/util';
6
5
 
7
6
  // TODO: Document default balances module purpose/usage
8
7
  const DefaultBalanceModule = type => ({
@@ -60,7 +59,7 @@ const db = new TalismanBalancesDatabase();
60
59
 
61
60
  var packageJson = {
62
61
  name: "@talismn/balances",
63
- version: "0.0.0-pr707-20230418101721",
62
+ version: "0.0.0-pr709-20230418123454",
64
63
  author: "Talisman",
65
64
  homepage: "https://talisman.xyz",
66
65
  license: "UNLICENSED",
@@ -87,28 +86,26 @@ var packageJson = {
87
86
  clean: "rm -rf dist && rm -rf .turbo rm -rf node_modules"
88
87
  },
89
88
  dependencies: {
90
- "@talismn/chain-connector": "workspace:*",
91
- "@talismn/chain-connector-evm": "workspace:*",
92
- "@talismn/chaindata-provider": "workspace:*",
93
- "@talismn/token-rates": "workspace:*",
94
- "@talismn/util": "workspace:*",
89
+ "@talismn/chain-connector": "workspace:^",
90
+ "@talismn/chain-connector-evm": "workspace:^",
91
+ "@talismn/chaindata-provider": "workspace:^",
92
+ "@talismn/token-rates": "workspace:^",
93
+ "@talismn/util": "workspace:^",
95
94
  anylogger: "^1.0.11",
96
- dexie: "^3.2.3",
97
- lodash: "4.17.21"
95
+ dexie: "^3.2.3"
98
96
  },
99
97
  devDependencies: {
100
- "@polkadot/types": "^10.1.4",
101
- "@talismn/eslint-config": "workspace:*",
102
- "@talismn/tsconfig": "workspace:*",
98
+ "@polkadot/types": "^9.10.5",
99
+ "@talismn/eslint-config": "workspace:^",
100
+ "@talismn/tsconfig": "workspace:^",
103
101
  "@types/jest": "^27.5.1",
104
- "@types/lodash": "^4.14.180",
105
102
  eslint: "^8.4.0",
106
103
  jest: "^28.1.0",
107
104
  "ts-jest": "^28.0.2",
108
105
  typescript: "^4.6.4"
109
106
  },
110
107
  peerDependencies: {
111
- "@polkadot/types": "10.x"
108
+ "@polkadot/types": "9.x"
112
109
  },
113
110
  preconstruct: {
114
111
  entrypoints: [
@@ -141,14 +138,8 @@ const createTypeRegistryCache = () => {
141
138
  if (cached) return cached;
142
139
  const typeRegistry = new TypeRegistry();
143
140
  if (typeof metadataRpc === "string") {
144
- try {
145
- const metadata = new Metadata(typeRegistry, metadataRpc);
146
- metadata.registry.setMetadata(metadata);
147
- } catch (cause) {
148
- log.warn(new Error(`Failed to set metadata for chain ${chainId}`, {
149
- cause
150
- }), cause);
151
- }
141
+ const metadata = new Metadata(typeRegistry, metadataRpc);
142
+ metadata.registry.setMetadata(metadata);
152
143
  }
153
144
  typeRegistryCache.set(chainId, typeRegistry);
154
145
  return typeRegistry;
@@ -287,77 +278,11 @@ class StorageHelper {
287
278
  }
288
279
  }
289
280
 
290
- /**
291
- * Pass some these into an `RpcStateQueryHelper` in order to easily batch multiple state queries into the one rpc call.
292
- */
293
-
294
- /**
295
- * Used by a variety of balance modules to help batch multiple state queries into the one rpc call.
296
- */
297
- class RpcStateQueryHelper {
298
- #chainConnector;
299
- #queries;
300
- constructor(chainConnector, queries) {
301
- this.#chainConnector = chainConnector;
302
- this.#queries = queries;
303
- }
304
- async subscribe(callback, timeout = false, subscribeMethod = "state_subscribeStorage", responseMethod = "state_storage", unsubscribeMethod = "state_unsubscribeStorage") {
305
- const queriesByChain = groupBy(this.#queries, "chainId");
306
- const subscriptions = Object.entries(queriesByChain).map(([chainId, queries]) => {
307
- const params = [queries.map(({
308
- stateKey
309
- }) => stateKey)];
310
- const unsub = this.#chainConnector.subscribe(chainId, subscribeMethod, responseMethod, params, (error, result) => {
311
- error ? callback(error) : callback(null, this.#distributeChangesToQueryDecoders.call(this, chainId, result));
312
- }, timeout);
313
- return () => unsub.then(unsubscribe => unsubscribe(unsubscribeMethod));
314
- });
315
- return () => subscriptions.forEach(unsubscribe => unsubscribe());
316
- }
317
- async fetch(method = "state_queryStorageAt") {
318
- const queriesByChain = groupBy(this.#queries, "chainId");
319
- const resultsByChain = await Promise.all(Object.entries(queriesByChain).map(async ([chainId, queries]) => {
320
- const params = [queries.map(({
321
- stateKey
322
- }) => stateKey)];
323
- const result = (await this.#chainConnector.send(chainId, method, params))[0];
324
- return this.#distributeChangesToQueryDecoders.call(this, chainId, result);
325
- }));
326
- return resultsByChain.flatMap(result => result);
327
- }
328
- #distributeChangesToQueryDecoders(chainId, result) {
329
- if (typeof result !== "object" || result === null) return [];
330
- if (!hasOwnProperty(result, "changes") || typeof result.changes !== "object") return [];
331
- if (!Array.isArray(result.changes)) return [];
332
- return result.changes.flatMap(([reference, change]) => {
333
- if (typeof reference !== "string") {
334
- log.warn(`Received non-string reference in RPC result: ${reference}`);
335
- return [];
336
- }
337
- if (typeof change !== "string" && change !== null) {
338
- log.warn(`Received non-string and non-null change in RPC result: ${reference} | ${change}`);
339
- return [];
340
- }
341
- const query = this.#queries.find(({
342
- chainId: cId,
343
- stateKey
344
- }) => cId === chainId && stateKey === reference);
345
- if (!query) {
346
- log.warn(`Failed to find query:\n${reference} in\n${this.#queries.map(({
347
- stateKey
348
- }) => stateKey)}`);
349
- return [];
350
- }
351
- return [query.decodeResult(change)];
352
- });
353
- }
354
- }
355
-
356
281
  const BalanceStatusLive = subscriptionId => `live-${subscriptionId}`;
357
282
  function excludeFromTransferableAmount(locks) {
358
283
  if (typeof locks === "string") return BigInt(locks);
359
284
  if (!Array.isArray(locks)) locks = [locks];
360
- return locks.filter(lock => lock.includeInTransferable !== true).map(lock => BigInt(lock.amount)).reduce((max, lock) => BigMath.max(max, lock), 0n);
285
+ return locks.filter(lock => lock.includeInTransferable !== true).map(lock => BigInt(lock.amount)).reduce((max, lock) => BigMath.max(max, lock), BigInt("0"));
361
286
  }
362
287
  function excludeFromFeePayableLocks(locks) {
363
288
  if (typeof locks === "string") return [];
@@ -368,9 +293,9 @@ function excludeFromFeePayableLocks(locks) {
368
293
  /** A labelled extra amount of a balance */
369
294
 
370
295
  function includeInTotalExtraAmount(extra) {
371
- if (!extra) return 0n;
296
+ if (!extra) return BigInt("0");
372
297
  if (!Array.isArray(extra)) extra = [extra];
373
- return extra.filter(extra => extra.includeInTotal).map(extra => BigInt(extra.amount)).reduce((a, b) => a + b, 0n);
298
+ return extra.filter(extra => extra.includeInTotal).map(extra => BigInt(extra.amount)).reduce((a, b) => a + b, BigInt("0"));
374
299
  }
375
300
 
376
301
  /** Used by plugins to help define their custom `BalanceType` */
@@ -481,27 +406,6 @@ class Balances {
481
406
  return new Balances([...this].filter(filter));
482
407
  };
483
408
 
484
- /**
485
- * Filters this collection to exclude token balances where the token has a `mirrorOf` field
486
- * and another balance exists in this collection for the token specified by the `mirrorOf` field.
487
- */
488
- filterMirrorTokens = () => new Balances([...this].filter(filterMirrorTokens));
489
-
490
- /**
491
- * Filters this collection to only include balances which are not zero.
492
- */
493
- filterNonZero = type => {
494
- const filter = balance => balance[type].planck > 0n;
495
- return this.find(filter);
496
- };
497
- /**
498
- * Filters this collection to only include balances which are not zero AND have a fiat conversion rate.
499
- */
500
- filterNonZeroFiat = (type, currency) => {
501
- const filter = balance => (balance[type].fiat(currency) ?? 0) > 0;
502
- return this.find(filter);
503
- };
504
-
505
409
  /**
506
410
  * Add some balances to this collection.
507
411
  * Added balances take priority over existing balances.
@@ -624,14 +528,13 @@ class Balance {
624
528
  get id() {
625
529
  const {
626
530
  source,
627
- subSource,
628
531
  address,
629
532
  chainId,
630
533
  evmNetworkId,
631
534
  tokenId
632
535
  } = this.#storage;
633
536
  const locationId = chainId !== undefined ? chainId : evmNetworkId;
634
- return [source, address, locationId, tokenId, subSource].filter(Boolean).join("-");
537
+ return `${source}-${address}-${locationId}-${tokenId}`;
635
538
  }
636
539
  get source() {
637
540
  return this.#storage.source;
@@ -680,43 +583,17 @@ class Balance {
680
583
  }
681
584
  /** The non-reserved balance of this token. Includes the frozen amount. Is included in the total. */
682
585
  get free() {
683
- 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"));
586
+ 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"));
684
587
  }
685
588
  /** The reserved balance of this token. Is included in the total. */
686
589
  get reserved() {
687
- 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"));
688
- }
689
- get reserves() {
690
- return (Array.isArray(this.#storage.reserves) ? this.#storage.reserves : [this.#storage.reserves]).flatMap(reserve => {
691
- if (reserve === undefined) return [];
692
- if (typeof reserve === "string") return {
693
- label: "reserved",
694
- amount: this.#format(reserve)
695
- };
696
- return {
697
- ...reserve,
698
- amount: this.#format(reserve.amount)
699
- };
700
- });
590
+ 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"));
701
591
  }
702
592
  /** The frozen balance of this token. Is included in the free amount. */
703
593
  get locked() {
704
- 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) => BigMath.max(a, b), 0n) : BigInt(this.#storage.locks?.amount || "0"));
705
- }
706
- get locks() {
707
- return (Array.isArray(this.#storage.locks) ? this.#storage.locks : [this.#storage.locks]).flatMap(lock => {
708
- if (lock === undefined) return [];
709
- if (typeof lock === "string") return {
710
- label: "other",
711
- amount: this.#format(lock)
712
- };
713
- return {
714
- ...lock,
715
- amount: this.#format(lock.amount)
716
- };
717
- });
594
+ 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) => BigMath.max(a, b), BigInt("0")) : BigInt(this.#storage.locks?.amount || "0"));
718
595
  }
719
- /** @deprecated Use balance.locked */
596
+ /** @depreacted - use balance.locked */
720
597
  get frozen() {
721
598
  return this.locked;
722
599
  }
@@ -729,7 +606,7 @@ class Balance {
729
606
  const excludeAmount = excludeFromTransferableAmount(this.#storage.locks);
730
607
 
731
608
  // subtract the lock from the free amount (but don't go below 0)
732
- return this.#format(BigMath.max(this.free.planck - excludeAmount, 0n));
609
+ return this.#format(BigMath.max(this.free.planck - excludeAmount, BigInt("0")));
733
610
  }
734
611
  /** The feePayable balance of this token. Is generally the free amount - the feeFrozen amount. */
735
612
  get feePayable() {
@@ -737,10 +614,10 @@ class Balance {
737
614
  if (!this.#storage.locks) return this.free;
738
615
 
739
616
  // find the largest lock which can't be used to pay tx fees
740
- const excludeAmount = excludeFromFeePayableLocks(this.#storage.locks).map(lock => BigInt(lock.amount)).reduce((max, lock) => BigMath.max(max, lock), 0n);
617
+ const excludeAmount = excludeFromFeePayableLocks(this.#storage.locks).map(lock => BigInt(lock.amount)).reduce((max, lock) => BigMath.max(max, lock), BigInt("0"));
741
618
 
742
619
  // subtract the lock from the free amount (but don't go below 0)
743
- return this.#format(BigMath.max(this.free.planck - excludeAmount, 0n));
620
+ return this.#format(BigMath.max(this.free.planck - excludeAmount, BigInt("0")));
744
621
  }
745
622
  }
746
623
  class BalanceFormatter {
@@ -766,52 +643,6 @@ class BalanceFormatter {
766
643
  return parseFloat(this.tokens) * ratio;
767
644
  }
768
645
  }
769
- class PlanckSumBalancesFormatter {
770
- #balances;
771
- constructor(balances) {
772
- this.#balances = balances;
773
- }
774
- #sum = balanceField => {
775
- // a function to get a planck amount from a balance
776
- const planck = balance => balance[balanceField].planck ?? 0n;
777
- return this.#balances.filterMirrorTokens().each.reduce(
778
- // add the total amount to the planck amount of each balance
779
- (total, balance) => total + planck(balance),
780
- // start with a total of 0
781
- 0n);
782
- };
783
-
784
- /**
785
- * The total balance of these tokens. Includes the free and the reserved amount.
786
- */
787
- get total() {
788
- return this.#sum("total");
789
- }
790
- /** The non-reserved balance of these tokens. Includes the frozen amount. Is included in the total. */
791
- get free() {
792
- return this.#sum("free");
793
- }
794
- /** The reserved balance of these tokens. Is included in the total. */
795
- get reserved() {
796
- return this.#sum("reserved");
797
- }
798
- /** The frozen balance of these tokens. Is included in the free amount. */
799
- get locked() {
800
- return this.#sum("locked");
801
- }
802
- /** @deprecated Use balances.locked */
803
- get frozen() {
804
- return this.locked;
805
- }
806
- /** The transferable balance of these tokens. Is generally the free amount - the miscFrozen amount. */
807
- get transferable() {
808
- return this.#sum("transferable");
809
- }
810
- /** The feePayable balance of these tokens. Is generally the free amount - the feeFrozen amount. */
811
- get feePayable() {
812
- return this.#sum("feePayable");
813
- }
814
- }
815
646
  class FiatSumBalancesFormatter {
816
647
  #balances;
817
648
  #currency;
@@ -821,10 +652,15 @@ class FiatSumBalancesFormatter {
821
652
  }
822
653
  #sum = balanceField => {
823
654
  // a function to get a fiat amount from a balance
824
- const fiat = balance => balance[balanceField].fiat(this.#currency) ?? 0;
825
- return this.#balances.filterMirrorTokens().each.reduce(
826
- // add the total amount to the fiat amount of each balance
827
- (total, balance) => total + fiat(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)),
828
664
  // start with a total of 0
829
665
  0);
830
666
  };
@@ -847,7 +683,7 @@ class FiatSumBalancesFormatter {
847
683
  get locked() {
848
684
  return this.#sum("locked");
849
685
  }
850
- /** @deprecated Use balances.locked */
686
+ /** @deprecated - use balances.locked */
851
687
  get frozen() {
852
688
  return this.locked;
853
689
  }
@@ -865,12 +701,9 @@ class SumBalancesFormatter {
865
701
  constructor(balances) {
866
702
  this.#balances = balances;
867
703
  }
868
- get planck() {
869
- return new PlanckSumBalancesFormatter(this.#balances);
870
- }
871
704
  fiat(currency) {
872
705
  return new FiatSumBalancesFormatter(this.#balances, currency);
873
706
  }
874
707
  }
875
708
 
876
- export { Balance, BalanceFormatter, BalanceStatusLive, Balances, DefaultBalanceModule, FiatSumBalancesFormatter, PlanckSumBalancesFormatter, RpcStateQueryHelper, StorageHelper, SumBalancesFormatter, TalismanBalancesDatabase, balances, createSubscriptionId, createTypeRegistryCache, db, deleteSubscriptionId, deriveStatuses, excludeFromFeePayableLocks, excludeFromTransferableAmount, filterMirrorTokens, getValidSubscriptionIds, includeInTotalExtraAmount };
709
+ export { Balance, BalanceFormatter, BalanceStatusLive, Balances, DefaultBalanceModule, FiatSumBalancesFormatter, StorageHelper, SumBalancesFormatter, TalismanBalancesDatabase, balances, createSubscriptionId, createTypeRegistryCache, db, deleteSubscriptionId, deriveStatuses, excludeFromFeePayableLocks, excludeFromTransferableAmount, filterMirrorTokens, getValidSubscriptionIds, includeInTotalExtraAmount };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@talismn/balances",
3
- "version": "0.0.0-pr707-20230418101721",
3
+ "version": "0.0.0-pr709-20230418123454",
4
4
  "author": "Talisman",
5
5
  "homepage": "https://talisman.xyz",
6
6
  "license": "UNLICENSED",
@@ -27,28 +27,26 @@
27
27
  "clean": "rm -rf dist && rm -rf .turbo rm -rf node_modules"
28
28
  },
29
29
  "dependencies": {
30
- "@talismn/chain-connector": "0.0.0-pr707-20230418101721",
31
- "@talismn/chain-connector-evm": "0.0.0-pr707-20230418101721",
32
- "@talismn/chaindata-provider": "0.0.0-pr707-20230418101721",
33
- "@talismn/token-rates": "0.0.0-pr707-20230418101721",
34
- "@talismn/util": "0.0.0-pr707-20230418101721",
30
+ "@talismn/chain-connector": "^0.0.0-pr709-20230418123454",
31
+ "@talismn/chain-connector-evm": "^0.0.0-pr709-20230418123454",
32
+ "@talismn/chaindata-provider": "^0.0.0-pr709-20230418123454",
33
+ "@talismn/token-rates": "^0.0.0-pr709-20230418123454",
34
+ "@talismn/util": "^0.1.8",
35
35
  "anylogger": "^1.0.11",
36
- "dexie": "^3.2.3",
37
- "lodash": "4.17.21"
36
+ "dexie": "^3.2.3"
38
37
  },
39
38
  "devDependencies": {
40
- "@polkadot/types": "^10.1.4",
41
- "@talismn/eslint-config": "0.0.1",
42
- "@talismn/tsconfig": "0.0.2",
39
+ "@polkadot/types": "^9.10.5",
40
+ "@talismn/eslint-config": "^0.0.1",
41
+ "@talismn/tsconfig": "^0.0.2",
43
42
  "@types/jest": "^27.5.1",
44
- "@types/lodash": "^4.14.180",
45
43
  "eslint": "^8.4.0",
46
44
  "jest": "^28.1.0",
47
45
  "ts-jest": "^28.0.2",
48
46
  "typescript": "^4.6.4"
49
47
  },
50
48
  "peerDependencies": {
51
- "@polkadot/types": "10.x"
49
+ "@polkadot/types": "9.x"
52
50
  },
53
51
  "preconstruct": {
54
52
  "entrypoints": [