@talismn/balances 0.0.0-pr710-20230418132646 → 0.0.0-pr716-20230419132506

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,7 +1,8 @@
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';
3
5
  import anylogger from 'anylogger';
4
- import { BigMath, isArrayOf, planckToTokens } from '@talismn/util';
5
6
 
6
7
  // TODO: Document default balances module purpose/usage
7
8
  const DefaultBalanceModule = type => ({
@@ -59,7 +60,7 @@ const db = new TalismanBalancesDatabase();
59
60
 
60
61
  var packageJson = {
61
62
  name: "@talismn/balances",
62
- version: "0.0.0-pr710-20230418132646",
63
+ version: "0.0.0-pr716-20230419132506",
63
64
  author: "Talisman",
64
65
  homepage: "https://talisman.xyz",
65
66
  license: "UNLICENSED",
@@ -82,30 +83,32 @@ var packageJson = {
82
83
  },
83
84
  scripts: {
84
85
  test: "jest",
85
- lint: "eslint . --max-warnings 0",
86
+ lint: "eslint src --max-warnings 0",
86
87
  clean: "rm -rf dist && rm -rf .turbo rm -rf node_modules"
87
88
  },
88
89
  dependencies: {
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:^",
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:*",
94
95
  anylogger: "^1.0.11",
95
- dexie: "^3.2.3"
96
+ dexie: "^3.2.3",
97
+ lodash: "4.17.21"
96
98
  },
97
99
  devDependencies: {
98
- "@polkadot/types": "^9.10.5",
99
- "@talismn/eslint-config": "workspace:^",
100
- "@talismn/tsconfig": "workspace:^",
100
+ "@polkadot/types": "^10.1.4",
101
+ "@talismn/eslint-config": "workspace:*",
102
+ "@talismn/tsconfig": "workspace:*",
101
103
  "@types/jest": "^27.5.1",
104
+ "@types/lodash": "^4.14.180",
102
105
  eslint: "^8.4.0",
103
106
  jest: "^28.1.0",
104
107
  "ts-jest": "^28.0.2",
105
108
  typescript: "^4.6.4"
106
109
  },
107
110
  peerDependencies: {
108
- "@polkadot/types": "9.x"
111
+ "@polkadot/types": "10.x"
109
112
  },
110
113
  preconstruct: {
111
114
  entrypoints: [
@@ -138,8 +141,14 @@ const createTypeRegistryCache = () => {
138
141
  if (cached) return cached;
139
142
  const typeRegistry = new TypeRegistry();
140
143
  if (typeof metadataRpc === "string") {
141
- const metadata = new Metadata(typeRegistry, metadataRpc);
142
- metadata.registry.setMetadata(metadata);
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
+ }
143
152
  }
144
153
  typeRegistryCache.set(chainId, typeRegistry);
145
154
  return typeRegistry;
@@ -206,7 +215,11 @@ class StorageHelper {
206
215
  #module;
207
216
  #method;
208
217
  #parameters;
218
+
219
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
209
220
  tags = null;
221
+
222
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
210
223
  constructor(registry, module, method, ...parameters) {
211
224
  this.#registry = registry;
212
225
  this.#module = module;
@@ -240,6 +253,8 @@ class StorageHelper {
240
253
  get parameters() {
241
254
  return this.#parameters;
242
255
  }
256
+
257
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
243
258
  tag(tags) {
244
259
  this.tags = tags;
245
260
  return this;
@@ -278,11 +293,77 @@ class StorageHelper {
278
293
  }
279
294
  }
280
295
 
296
+ /**
297
+ * Pass some these into an `RpcStateQueryHelper` in order to easily batch multiple state queries into the one rpc call.
298
+ */
299
+
300
+ /**
301
+ * Used by a variety of balance modules to help batch multiple state queries into the one rpc call.
302
+ */
303
+ class RpcStateQueryHelper {
304
+ #chainConnector;
305
+ #queries;
306
+ constructor(chainConnector, queries) {
307
+ this.#chainConnector = chainConnector;
308
+ this.#queries = queries;
309
+ }
310
+ async subscribe(callback, timeout = false, subscribeMethod = "state_subscribeStorage", responseMethod = "state_storage", unsubscribeMethod = "state_unsubscribeStorage") {
311
+ const queriesByChain = groupBy(this.#queries, "chainId");
312
+ const subscriptions = Object.entries(queriesByChain).map(([chainId, queries]) => {
313
+ const params = [queries.map(({
314
+ stateKey
315
+ }) => stateKey)];
316
+ const unsub = this.#chainConnector.subscribe(chainId, subscribeMethod, responseMethod, params, (error, result) => {
317
+ error ? callback(error) : callback(null, this.#distributeChangesToQueryDecoders.call(this, chainId, result));
318
+ }, timeout);
319
+ return () => unsub.then(unsubscribe => unsubscribe(unsubscribeMethod));
320
+ });
321
+ return () => subscriptions.forEach(unsubscribe => unsubscribe());
322
+ }
323
+ async fetch(method = "state_queryStorageAt") {
324
+ const queriesByChain = groupBy(this.#queries, "chainId");
325
+ const resultsByChain = await Promise.all(Object.entries(queriesByChain).map(async ([chainId, queries]) => {
326
+ const params = [queries.map(({
327
+ stateKey
328
+ }) => stateKey)];
329
+ const result = (await this.#chainConnector.send(chainId, method, params))[0];
330
+ return this.#distributeChangesToQueryDecoders.call(this, chainId, result);
331
+ }));
332
+ return resultsByChain.flatMap(result => result);
333
+ }
334
+ #distributeChangesToQueryDecoders(chainId, result) {
335
+ if (typeof result !== "object" || result === null) return [];
336
+ if (!hasOwnProperty(result, "changes") || typeof result.changes !== "object") return [];
337
+ if (!Array.isArray(result.changes)) return [];
338
+ return result.changes.flatMap(([reference, change]) => {
339
+ if (typeof reference !== "string") {
340
+ log.warn(`Received non-string reference in RPC result: ${reference}`);
341
+ return [];
342
+ }
343
+ if (typeof change !== "string" && change !== null) {
344
+ log.warn(`Received non-string and non-null change in RPC result: ${reference} | ${change}`);
345
+ return [];
346
+ }
347
+ const query = this.#queries.find(({
348
+ chainId: cId,
349
+ stateKey
350
+ }) => cId === chainId && stateKey === reference);
351
+ if (!query) {
352
+ log.warn(`Failed to find query:\n${reference} in\n${this.#queries.map(({
353
+ stateKey
354
+ }) => stateKey)}`);
355
+ return [];
356
+ }
357
+ return [query.decodeResult(change)];
358
+ });
359
+ }
360
+ }
361
+
281
362
  const BalanceStatusLive = subscriptionId => `live-${subscriptionId}`;
282
363
  function excludeFromTransferableAmount(locks) {
283
364
  if (typeof locks === "string") return BigInt(locks);
284
365
  if (!Array.isArray(locks)) locks = [locks];
285
- return locks.filter(lock => lock.includeInTransferable !== true).map(lock => BigInt(lock.amount)).reduce((max, lock) => BigMath.max(max, lock), BigInt("0"));
366
+ return locks.filter(lock => lock.includeInTransferable !== true).map(lock => BigInt(lock.amount)).reduce((max, lock) => BigMath.max(max, lock), 0n);
286
367
  }
287
368
  function excludeFromFeePayableLocks(locks) {
288
369
  if (typeof locks === "string") return [];
@@ -293,9 +374,9 @@ function excludeFromFeePayableLocks(locks) {
293
374
  /** A labelled extra amount of a balance */
294
375
 
295
376
  function includeInTotalExtraAmount(extra) {
296
- if (!extra) return BigInt("0");
377
+ if (!extra) return 0n;
297
378
  if (!Array.isArray(extra)) extra = [extra];
298
- return extra.filter(extra => extra.includeInTotal).map(extra => BigInt(extra.amount)).reduce((a, b) => a + b, BigInt("0"));
379
+ return extra.filter(extra => extra.includeInTotal).map(extra => BigInt(extra.amount)).reduce((a, b) => a + b, 0n);
299
380
  }
300
381
 
301
382
  /** Used by plugins to help define their custom `BalanceType` */
@@ -406,6 +487,27 @@ class Balances {
406
487
  return new Balances([...this].filter(filter));
407
488
  };
408
489
 
490
+ /**
491
+ * Filters this collection to exclude token balances where the token has a `mirrorOf` field
492
+ * and another balance exists in this collection for the token specified by the `mirrorOf` field.
493
+ */
494
+ filterMirrorTokens = () => new Balances([...this].filter(filterMirrorTokens));
495
+
496
+ /**
497
+ * Filters this collection to only include balances which are not zero.
498
+ */
499
+ filterNonZero = type => {
500
+ const filter = balance => balance[type].planck > 0n;
501
+ return this.find(filter);
502
+ };
503
+ /**
504
+ * Filters this collection to only include balances which are not zero AND have a fiat conversion rate.
505
+ */
506
+ filterNonZeroFiat = (type, currency) => {
507
+ const filter = balance => (balance[type].fiat(currency) ?? 0) > 0;
508
+ return this.find(filter);
509
+ };
510
+
409
511
  /**
410
512
  * Add some balances to this collection.
411
513
  * Added balances take priority over existing balances.
@@ -528,13 +630,14 @@ class Balance {
528
630
  get id() {
529
631
  const {
530
632
  source,
633
+ subSource,
531
634
  address,
532
635
  chainId,
533
636
  evmNetworkId,
534
637
  tokenId
535
638
  } = this.#storage;
536
639
  const locationId = chainId !== undefined ? chainId : evmNetworkId;
537
- return `${source}-${address}-${locationId}-${tokenId}`;
640
+ return [source, address, locationId, tokenId, subSource].filter(Boolean).join("-");
538
641
  }
539
642
  get source() {
540
643
  return this.#storage.source;
@@ -583,17 +686,43 @@ class Balance {
583
686
  }
584
687
  /** The non-reserved balance of this token. Includes the frozen amount. Is included in the total. */
585
688
  get free() {
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"));
689
+ 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"));
587
690
  }
588
691
  /** The reserved balance of this token. Is included in the total. */
589
692
  get reserved() {
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"));
693
+ 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"));
694
+ }
695
+ get reserves() {
696
+ return (Array.isArray(this.#storage.reserves) ? this.#storage.reserves : [this.#storage.reserves]).flatMap(reserve => {
697
+ if (reserve === undefined) return [];
698
+ if (typeof reserve === "string") return {
699
+ label: "reserved",
700
+ amount: this.#format(reserve)
701
+ };
702
+ return {
703
+ ...reserve,
704
+ amount: this.#format(reserve.amount)
705
+ };
706
+ });
591
707
  }
592
708
  /** The frozen balance of this token. Is included in the free amount. */
593
709
  get locked() {
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"));
710
+ 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"));
711
+ }
712
+ get locks() {
713
+ return (Array.isArray(this.#storage.locks) ? this.#storage.locks : [this.#storage.locks]).flatMap(lock => {
714
+ if (lock === undefined) return [];
715
+ if (typeof lock === "string") return {
716
+ label: "other",
717
+ amount: this.#format(lock)
718
+ };
719
+ return {
720
+ ...lock,
721
+ amount: this.#format(lock.amount)
722
+ };
723
+ });
595
724
  }
596
- /** @depreacted - use balance.locked */
725
+ /** @deprecated Use balance.locked */
597
726
  get frozen() {
598
727
  return this.locked;
599
728
  }
@@ -606,7 +735,7 @@ class Balance {
606
735
  const excludeAmount = excludeFromTransferableAmount(this.#storage.locks);
607
736
 
608
737
  // subtract the lock from the free amount (but don't go below 0)
609
- return this.#format(BigMath.max(this.free.planck - excludeAmount, BigInt("0")));
738
+ return this.#format(BigMath.max(this.free.planck - excludeAmount, 0n));
610
739
  }
611
740
  /** The feePayable balance of this token. Is generally the free amount - the feeFrozen amount. */
612
741
  get feePayable() {
@@ -614,10 +743,10 @@ class Balance {
614
743
  if (!this.#storage.locks) return this.free;
615
744
 
616
745
  // find the largest lock which can't be used to pay tx fees
617
- const excludeAmount = excludeFromFeePayableLocks(this.#storage.locks).map(lock => BigInt(lock.amount)).reduce((max, lock) => BigMath.max(max, lock), BigInt("0"));
746
+ const excludeAmount = excludeFromFeePayableLocks(this.#storage.locks).map(lock => BigInt(lock.amount)).reduce((max, lock) => BigMath.max(max, lock), 0n);
618
747
 
619
748
  // subtract the lock from the free amount (but don't go below 0)
620
- return this.#format(BigMath.max(this.free.planck - excludeAmount, BigInt("0")));
749
+ return this.#format(BigMath.max(this.free.planck - excludeAmount, 0n));
621
750
  }
622
751
  }
623
752
  class BalanceFormatter {
@@ -643,6 +772,52 @@ class BalanceFormatter {
643
772
  return parseFloat(this.tokens) * ratio;
644
773
  }
645
774
  }
775
+ class PlanckSumBalancesFormatter {
776
+ #balances;
777
+ constructor(balances) {
778
+ this.#balances = balances;
779
+ }
780
+ #sum = balanceField => {
781
+ // a function to get a planck amount from a balance
782
+ const planck = balance => balance[balanceField].planck ?? 0n;
783
+ return this.#balances.filterMirrorTokens().each.reduce(
784
+ // add the total amount to the planck amount of each balance
785
+ (total, balance) => total + planck(balance),
786
+ // start with a total of 0
787
+ 0n);
788
+ };
789
+
790
+ /**
791
+ * The total balance of these tokens. Includes the free and the reserved amount.
792
+ */
793
+ get total() {
794
+ return this.#sum("total");
795
+ }
796
+ /** The non-reserved balance of these tokens. Includes the frozen amount. Is included in the total. */
797
+ get free() {
798
+ return this.#sum("free");
799
+ }
800
+ /** The reserved balance of these tokens. Is included in the total. */
801
+ get reserved() {
802
+ return this.#sum("reserved");
803
+ }
804
+ /** The frozen balance of these tokens. Is included in the free amount. */
805
+ get locked() {
806
+ return this.#sum("locked");
807
+ }
808
+ /** @deprecated Use balances.locked */
809
+ get frozen() {
810
+ return this.locked;
811
+ }
812
+ /** The transferable balance of these tokens. Is generally the free amount - the miscFrozen amount. */
813
+ get transferable() {
814
+ return this.#sum("transferable");
815
+ }
816
+ /** The feePayable balance of these tokens. Is generally the free amount - the feeFrozen amount. */
817
+ get feePayable() {
818
+ return this.#sum("feePayable");
819
+ }
820
+ }
646
821
  class FiatSumBalancesFormatter {
647
822
  #balances;
648
823
  #currency;
@@ -652,15 +827,10 @@ class FiatSumBalancesFormatter {
652
827
  }
653
828
  #sum = balanceField => {
654
829
  // 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)),
830
+ const fiat = balance => balance[balanceField].fiat(this.#currency) ?? 0;
831
+ return this.#balances.filterMirrorTokens().each.reduce(
832
+ // add the total amount to the fiat amount of each balance
833
+ (total, balance) => total + fiat(balance),
664
834
  // start with a total of 0
665
835
  0);
666
836
  };
@@ -683,7 +853,7 @@ class FiatSumBalancesFormatter {
683
853
  get locked() {
684
854
  return this.#sum("locked");
685
855
  }
686
- /** @deprecated - use balances.locked */
856
+ /** @deprecated Use balances.locked */
687
857
  get frozen() {
688
858
  return this.locked;
689
859
  }
@@ -701,9 +871,12 @@ class SumBalancesFormatter {
701
871
  constructor(balances) {
702
872
  this.#balances = balances;
703
873
  }
874
+ get planck() {
875
+ return new PlanckSumBalancesFormatter(this.#balances);
876
+ }
704
877
  fiat(currency) {
705
878
  return new FiatSumBalancesFormatter(this.#balances, currency);
706
879
  }
707
880
  }
708
881
 
709
- export { Balance, BalanceFormatter, BalanceStatusLive, Balances, DefaultBalanceModule, FiatSumBalancesFormatter, StorageHelper, SumBalancesFormatter, TalismanBalancesDatabase, balances, createSubscriptionId, createTypeRegistryCache, db, deleteSubscriptionId, deriveStatuses, excludeFromFeePayableLocks, excludeFromTransferableAmount, filterMirrorTokens, getValidSubscriptionIds, includeInTotalExtraAmount };
882
+ export { Balance, BalanceFormatter, BalanceStatusLive, Balances, DefaultBalanceModule, FiatSumBalancesFormatter, PlanckSumBalancesFormatter, RpcStateQueryHelper, 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-pr710-20230418132646",
3
+ "version": "0.0.0-pr716-20230419132506",
4
4
  "author": "Talisman",
5
5
  "homepage": "https://talisman.xyz",
6
6
  "license": "UNLICENSED",
@@ -23,30 +23,32 @@
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-pr710-20230418132646",
31
- "@talismn/chain-connector-evm": "^0.0.0-pr710-20230418132646",
32
- "@talismn/chaindata-provider": "^0.0.0-pr710-20230418132646",
33
- "@talismn/token-rates": "^0.0.0-pr710-20230418132646",
34
- "@talismn/util": "^0.1.8",
30
+ "@talismn/chain-connector": "0.0.0-pr716-20230419132506",
31
+ "@talismn/chain-connector-evm": "0.0.0-pr716-20230419132506",
32
+ "@talismn/chaindata-provider": "0.0.0-pr716-20230419132506",
33
+ "@talismn/token-rates": "0.0.0-pr716-20230419132506",
34
+ "@talismn/util": "0.0.0-pr716-20230419132506",
35
35
  "anylogger": "^1.0.11",
36
- "dexie": "^3.2.3"
36
+ "dexie": "^3.2.3",
37
+ "lodash": "4.17.21"
37
38
  },
38
39
  "devDependencies": {
39
- "@polkadot/types": "^9.10.5",
40
- "@talismn/eslint-config": "^0.0.1",
41
- "@talismn/tsconfig": "^0.0.2",
40
+ "@polkadot/types": "^10.1.4",
41
+ "@talismn/eslint-config": "0.0.0-pr716-20230419132506",
42
+ "@talismn/tsconfig": "0.0.2",
42
43
  "@types/jest": "^27.5.1",
44
+ "@types/lodash": "^4.14.180",
43
45
  "eslint": "^8.4.0",
44
46
  "jest": "^28.1.0",
45
47
  "ts-jest": "^28.0.2",
46
48
  "typescript": "^4.6.4"
47
49
  },
48
50
  "peerDependencies": {
49
- "@polkadot/types": "9.x"
51
+ "@polkadot/types": "10.x"
50
52
  },
51
53
  "preconstruct": {
52
54
  "entrypoints": [