@talismn/balances 0.0.0-pr707-20230418101721 → 0.0.0-pr708-20230418111638

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-pr708-20230418111638",
64
63
  author: "Talisman",
65
64
  homepage: "https://talisman.xyz",
66
65
  license: "UNLICENSED",
@@ -83,32 +82,30 @@ var packageJson = {
83
82
  },
84
83
  scripts: {
85
84
  test: "jest",
86
- lint: "eslint . --max-warnings 0",
85
+ lint: "eslint src --max-warnings 0",
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;
@@ -215,7 +206,11 @@ class StorageHelper {
215
206
  #module;
216
207
  #method;
217
208
  #parameters;
209
+
210
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
218
211
  tags = null;
212
+
213
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
219
214
  constructor(registry, module, method, ...parameters) {
220
215
  this.#registry = registry;
221
216
  this.#module = module;
@@ -249,6 +244,8 @@ class StorageHelper {
249
244
  get parameters() {
250
245
  return this.#parameters;
251
246
  }
247
+
248
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
252
249
  tag(tags) {
253
250
  this.tags = tags;
254
251
  return this;
@@ -287,77 +284,11 @@ class StorageHelper {
287
284
  }
288
285
  }
289
286
 
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
287
  const BalanceStatusLive = subscriptionId => `live-${subscriptionId}`;
357
288
  function excludeFromTransferableAmount(locks) {
358
289
  if (typeof locks === "string") return BigInt(locks);
359
290
  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);
291
+ return locks.filter(lock => lock.includeInTransferable !== true).map(lock => BigInt(lock.amount)).reduce((max, lock) => BigMath.max(max, lock), BigInt("0"));
361
292
  }
362
293
  function excludeFromFeePayableLocks(locks) {
363
294
  if (typeof locks === "string") return [];
@@ -368,9 +299,9 @@ function excludeFromFeePayableLocks(locks) {
368
299
  /** A labelled extra amount of a balance */
369
300
 
370
301
  function includeInTotalExtraAmount(extra) {
371
- if (!extra) return 0n;
302
+ if (!extra) return BigInt("0");
372
303
  if (!Array.isArray(extra)) extra = [extra];
373
- return extra.filter(extra => extra.includeInTotal).map(extra => BigInt(extra.amount)).reduce((a, b) => a + b, 0n);
304
+ return extra.filter(extra => extra.includeInTotal).map(extra => BigInt(extra.amount)).reduce((a, b) => a + b, BigInt("0"));
374
305
  }
375
306
 
376
307
  /** Used by plugins to help define their custom `BalanceType` */
@@ -481,27 +412,6 @@ class Balances {
481
412
  return new Balances([...this].filter(filter));
482
413
  };
483
414
 
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
415
  /**
506
416
  * Add some balances to this collection.
507
417
  * Added balances take priority over existing balances.
@@ -624,14 +534,13 @@ class Balance {
624
534
  get id() {
625
535
  const {
626
536
  source,
627
- subSource,
628
537
  address,
629
538
  chainId,
630
539
  evmNetworkId,
631
540
  tokenId
632
541
  } = this.#storage;
633
542
  const locationId = chainId !== undefined ? chainId : evmNetworkId;
634
- return [source, address, locationId, tokenId, subSource].filter(Boolean).join("-");
543
+ return `${source}-${address}-${locationId}-${tokenId}`;
635
544
  }
636
545
  get source() {
637
546
  return this.#storage.source;
@@ -680,43 +589,17 @@ class Balance {
680
589
  }
681
590
  /** The non-reserved balance of this token. Includes the frozen amount. Is included in the total. */
682
591
  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"));
592
+ 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
593
  }
685
594
  /** The reserved balance of this token. Is included in the total. */
686
595
  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
- });
596
+ 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
597
  }
702
598
  /** The frozen balance of this token. Is included in the free amount. */
703
599
  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
- });
600
+ 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
601
  }
719
- /** @deprecated Use balance.locked */
602
+ /** @depreacted - use balance.locked */
720
603
  get frozen() {
721
604
  return this.locked;
722
605
  }
@@ -729,7 +612,7 @@ class Balance {
729
612
  const excludeAmount = excludeFromTransferableAmount(this.#storage.locks);
730
613
 
731
614
  // subtract the lock from the free amount (but don't go below 0)
732
- return this.#format(BigMath.max(this.free.planck - excludeAmount, 0n));
615
+ return this.#format(BigMath.max(this.free.planck - excludeAmount, BigInt("0")));
733
616
  }
734
617
  /** The feePayable balance of this token. Is generally the free amount - the feeFrozen amount. */
735
618
  get feePayable() {
@@ -737,10 +620,10 @@ class Balance {
737
620
  if (!this.#storage.locks) return this.free;
738
621
 
739
622
  // 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);
623
+ const excludeAmount = excludeFromFeePayableLocks(this.#storage.locks).map(lock => BigInt(lock.amount)).reduce((max, lock) => BigMath.max(max, lock), BigInt("0"));
741
624
 
742
625
  // subtract the lock from the free amount (but don't go below 0)
743
- return this.#format(BigMath.max(this.free.planck - excludeAmount, 0n));
626
+ return this.#format(BigMath.max(this.free.planck - excludeAmount, BigInt("0")));
744
627
  }
745
628
  }
746
629
  class BalanceFormatter {
@@ -766,52 +649,6 @@ class BalanceFormatter {
766
649
  return parseFloat(this.tokens) * ratio;
767
650
  }
768
651
  }
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
652
  class FiatSumBalancesFormatter {
816
653
  #balances;
817
654
  #currency;
@@ -821,10 +658,15 @@ class FiatSumBalancesFormatter {
821
658
  }
822
659
  #sum = balanceField => {
823
660
  // 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),
661
+ const fiat = balance => balance[balanceField].fiat(this.#currency) || 0;
662
+
663
+ // a function to add two amounts
664
+ const sum = (a, b) => a + b;
665
+ return [...this.#balances].filter(filterMirrorTokens).reduce((total, balance) => sum(
666
+ // add the total amount...
667
+ total,
668
+ // ...to the fiat amount of each balance
669
+ fiat(balance)),
828
670
  // start with a total of 0
829
671
  0);
830
672
  };
@@ -847,7 +689,7 @@ class FiatSumBalancesFormatter {
847
689
  get locked() {
848
690
  return this.#sum("locked");
849
691
  }
850
- /** @deprecated Use balances.locked */
692
+ /** @deprecated - use balances.locked */
851
693
  get frozen() {
852
694
  return this.locked;
853
695
  }
@@ -865,12 +707,9 @@ class SumBalancesFormatter {
865
707
  constructor(balances) {
866
708
  this.#balances = balances;
867
709
  }
868
- get planck() {
869
- return new PlanckSumBalancesFormatter(this.#balances);
870
- }
871
710
  fiat(currency) {
872
711
  return new FiatSumBalancesFormatter(this.#balances, currency);
873
712
  }
874
713
  }
875
714
 
876
- export { Balance, BalanceFormatter, BalanceStatusLive, Balances, DefaultBalanceModule, FiatSumBalancesFormatter, PlanckSumBalancesFormatter, RpcStateQueryHelper, StorageHelper, SumBalancesFormatter, TalismanBalancesDatabase, balances, createSubscriptionId, createTypeRegistryCache, db, deleteSubscriptionId, deriveStatuses, excludeFromFeePayableLocks, excludeFromTransferableAmount, filterMirrorTokens, getValidSubscriptionIds, includeInTotalExtraAmount };
715
+ 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-pr708-20230418111638",
4
4
  "author": "Talisman",
5
5
  "homepage": "https://talisman.xyz",
6
6
  "license": "UNLICENSED",
@@ -23,32 +23,30 @@
23
23
  },
24
24
  "scripts": {
25
25
  "test": "jest",
26
- "lint": "eslint . --max-warnings 0",
26
+ "lint": "eslint src --max-warnings 0",
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-pr708-20230418111638",
31
+ "@talismn/chain-connector-evm": "^0.0.0-pr708-20230418111638",
32
+ "@talismn/chaindata-provider": "^0.0.0-pr708-20230418111638",
33
+ "@talismn/token-rates": "^0.0.0-pr708-20230418111638",
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": [