@talismn/balances 3.1.3 → 3.1.5

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.
package/dist/index.d.mts CHANGED
@@ -415,9 +415,9 @@ export declare class Balance {
415
415
  coingeckoId?: string | undefined;
416
416
  noDiscovery?: boolean | undefined;
417
417
  mirrorOf?: string | undefined;
418
- type: "substrate-psp22";
419
- platform: "polkadot";
420
- contractAddress: string;
418
+ type: "evm-erc20";
419
+ platform: "ethereum";
420
+ contractAddress: `0x${string}`;
421
421
  } | {
422
422
  id: string;
423
423
  networkId: string;
@@ -429,12 +429,8 @@ export declare class Balance {
429
429
  coingeckoId?: string | undefined;
430
430
  noDiscovery?: boolean | undefined;
431
431
  mirrorOf?: string | undefined;
432
- type: "substrate-foreignassets";
433
- platform: "polkadot";
434
- onChainId: string;
435
- isFrozen?: boolean | undefined;
436
- isSufficient: boolean;
437
- existentialDeposit: string;
432
+ type: "evm-native";
433
+ platform: "ethereum";
438
434
  } | {
439
435
  id: string;
440
436
  networkId: string;
@@ -446,12 +442,18 @@ export declare class Balance {
446
442
  coingeckoId?: string | undefined;
447
443
  noDiscovery?: boolean | undefined;
448
444
  mirrorOf?: string | undefined;
449
- type: "substrate-dtao";
450
- platform: "polkadot";
451
- netuid: number;
452
- subnetName?: string | undefined;
453
- hotkey?: string | undefined;
454
- isTransferable: boolean;
445
+ type: "evm-uniswapv2";
446
+ platform: "ethereum";
447
+ contractAddress: `0x${string}`;
448
+ isCustom?: boolean | undefined;
449
+ symbol0: string;
450
+ symbol1: string;
451
+ decimals0: number;
452
+ decimals1: number;
453
+ tokenAddress0: `0x${string}`;
454
+ tokenAddress1: `0x${string}`;
455
+ coingeckoId0?: string | undefined;
456
+ coingeckoId1?: string | undefined;
455
457
  } | {
456
458
  id: string;
457
459
  networkId: string;
@@ -463,9 +465,12 @@ export declare class Balance {
463
465
  coingeckoId?: string | undefined;
464
466
  noDiscovery?: boolean | undefined;
465
467
  mirrorOf?: string | undefined;
466
- type: "evm-erc20";
467
- platform: "ethereum";
468
- contractAddress: `0x${string}`;
468
+ type: "substrate-assets";
469
+ platform: "polkadot";
470
+ assetId: string;
471
+ isFrozen?: boolean | undefined;
472
+ isSufficient: boolean;
473
+ existentialDeposit: string;
469
474
  } | {
470
475
  id: string;
471
476
  networkId: string;
@@ -477,8 +482,12 @@ export declare class Balance {
477
482
  coingeckoId?: string | undefined;
478
483
  noDiscovery?: boolean | undefined;
479
484
  mirrorOf?: string | undefined;
480
- type: "evm-native";
481
- platform: "ethereum";
485
+ type: "substrate-dtao";
486
+ platform: "polkadot";
487
+ netuid: number;
488
+ subnetName?: string | undefined;
489
+ hotkey?: string | undefined;
490
+ isTransferable: boolean;
482
491
  } | {
483
492
  id: string;
484
493
  networkId: string;
@@ -490,18 +499,12 @@ export declare class Balance {
490
499
  coingeckoId?: string | undefined;
491
500
  noDiscovery?: boolean | undefined;
492
501
  mirrorOf?: string | undefined;
493
- type: "evm-uniswapv2";
494
- platform: "ethereum";
495
- contractAddress: `0x${string}`;
496
- isCustom?: boolean | undefined;
497
- symbol0: string;
498
- symbol1: string;
499
- decimals0: number;
500
- decimals1: number;
501
- tokenAddress0: `0x${string}`;
502
- tokenAddress1: `0x${string}`;
503
- coingeckoId0?: string | undefined;
504
- coingeckoId1?: string | undefined;
502
+ type: "substrate-foreignassets";
503
+ platform: "polkadot";
504
+ onChainId: string;
505
+ isFrozen?: boolean | undefined;
506
+ isSufficient: boolean;
507
+ existentialDeposit: string;
505
508
  } | {
506
509
  id: string;
507
510
  networkId: string;
@@ -513,11 +516,8 @@ export declare class Balance {
513
516
  coingeckoId?: string | undefined;
514
517
  noDiscovery?: boolean | undefined;
515
518
  mirrorOf?: string | undefined;
516
- type: "substrate-assets";
519
+ type: "substrate-native";
517
520
  platform: "polkadot";
518
- assetId: string;
519
- isFrozen?: boolean | undefined;
520
- isSufficient: boolean;
521
521
  existentialDeposit: string;
522
522
  } | {
523
523
  id: string;
@@ -530,9 +530,9 @@ export declare class Balance {
530
530
  coingeckoId?: string | undefined;
531
531
  noDiscovery?: boolean | undefined;
532
532
  mirrorOf?: string | undefined;
533
- type: "substrate-native";
533
+ type: "substrate-psp22";
534
534
  platform: "polkadot";
535
- existentialDeposit: string;
535
+ contractAddress: string;
536
536
  } | {
537
537
  id: string;
538
538
  networkId: string;
package/dist/index.js CHANGED
@@ -3987,6 +3987,43 @@ const findDTaoRootStakeHold = (balance) => {
3987
3987
  }
3988
3988
  return null;
3989
3989
  };
3990
+ const hasRootStakeHoldStorage = (unifiedMetadata) => hasStorageItems(unifiedMetadata, "SubtensorModule", ["RootStakeUnlockInterval", "LastColdkeyHotkeyStakeBlock"]);
3991
+ /**
3992
+ * How long a `RootStakeUnlockInterval` read is reused. The chain has no extrinsic that sets
3993
+ * it: it changes with a runtime upgrade, which brings new metadata and so a new cache entry,
3994
+ * or through root's `set_storage`, which this bounds.
3995
+ */
3996
+ const UNLOCK_INTERVAL_CACHE_MS = 6e5;
3997
+ /** cached reads by network, per parsed runtime metadata */
3998
+ const unlockIntervalCache = /* @__PURE__ */ new WeakMap();
3999
+ /**
4000
+ * The chain's `RootStakeUnlockInterval`: how many blocks root stake stays held after the
4001
+ * pair's last root stake operation. 0 (disabled) unless governance enables it, either by
4002
+ * setting the storage entry or with a runtime default that leaves it unset (metadata
4003
+ * fallback). Null on chains without root stake holds.
4004
+ *
4005
+ * Read at most once per `UNLOCK_INTERVAL_CACHE_MS` for each runtime, so that the 6s balance
4006
+ * polls don't spend a request on a value that hardly ever changes.
4007
+ */
4008
+ const fetchRootStakeUnlockInterval = async (connector, networkId, metadataRpc, at) => {
4009
+ const { unifiedMetadata, builder } = parseMetadataRpcCached(metadataRpc);
4010
+ if (!hasRootStakeHoldStorage(unifiedMetadata)) return null;
4011
+ const byNetwork = unlockIntervalCache.get(builder) ?? /* @__PURE__ */ new Map();
4012
+ unlockIntervalCache.set(builder, byNetwork);
4013
+ const cached = byNetwork.get(networkId);
4014
+ if (cached && Date.now() - cached.readAt < UNLOCK_INTERVAL_CACHE_MS) return cached.interval;
4015
+ try {
4016
+ const interval = await fetchUnlockInterval(connector, networkId, unifiedMetadata, builder, at);
4017
+ byNetwork.set(networkId, {
4018
+ interval,
4019
+ readAt: Date.now()
4020
+ });
4021
+ return interval;
4022
+ } catch (cause) {
4023
+ log_default.warn(`Failed to fetch root stake unlock interval on ${networkId}`, { cause });
4024
+ throw cause;
4025
+ }
4026
+ };
3990
4027
  /**
3991
4028
  * Fetches active root-stake hold windows (spec 441): when `RootStakeUnlockInterval` is
3992
4029
  * non-zero, root stake cannot leave root (remove/move/swap/transfer) until `interval`
@@ -3994,17 +4031,15 @@ const findDTaoRootStakeHold = (balance) => {
3994
4031
  * Pairs already past their window are omitted — a returned hold means the pair's root
3995
4032
  * stake is currently unremovable.
3996
4033
  *
3997
- * The interval is 0 (disabled) unless governance enables it — either by setting the
3998
- * storage entry or via a runtime default that leaves it unset (metadata fallback). The
3999
- * per-pair queries only run when it is non-zero.
4034
+ * The per-pair queries only run when the interval (`fetchRootStakeUnlockInterval`, cached)
4035
+ * is non-zero.
4000
4036
  */
4001
4037
  const fetchRootStakeHolds = async (connector, networkId, metadataRpc, rootPairs, at) => {
4002
4038
  if (!rootPairs.length) return [];
4003
- const { unifiedMetadata, builder } = parseMetadataRpcCached(metadataRpc);
4004
- if (!hasStorageItems(unifiedMetadata, "SubtensorModule", ["RootStakeUnlockInterval", "LastColdkeyHotkeyStakeBlock"])) return [];
4039
+ const interval = await fetchRootStakeUnlockInterval(connector, networkId, metadataRpc, at);
4040
+ if (!interval) return [];
4041
+ const { builder } = parseMetadataRpcCached(metadataRpc);
4005
4042
  try {
4006
- const interval = await fetchUnlockInterval(connector, networkId, unifiedMetadata, builder, at);
4007
- if (interval === 0n) return [];
4008
4043
  const { currentBlock, lastStakeBlocks } = await fetchLastStakeBlocks(connector, networkId, builder, rootPairs, at);
4009
4044
  return lastStakeBlocks.flatMap(({ address, hotkey, lastStakeBlock }) => {
4010
4045
  if (lastStakeBlock === 0n) return [];
@@ -4090,7 +4125,12 @@ const fetchLastStakeBlocks = async (connector, networkId, builder, rootPairs, at
4090
4125
  };
4091
4126
  };
4092
4127
  // src/modules/substrate-dtao/fetchBalances.ts
4093
- const fetchBalances$5 = async ({ networkId, tokensWithAddresses, connector, miniMetadata, signal }) => {
4128
+ const fetchBalances$5 = (args) => fetchBalancesAt(args);
4129
+ /**
4130
+ * Fetches the balances as of block `at`, or as of the best block when `at` is not given.
4131
+ * Every read of the fetch is pinned to that one block.
4132
+ */
4133
+ const fetchBalancesAt = async ({ networkId, tokensWithAddresses, connector, miniMetadata, signal }, at) => {
4094
4134
  if (!tokensWithAddresses.length) return {
4095
4135
  success: [],
4096
4136
  errors: []
@@ -4130,10 +4170,16 @@ const fetchBalances$5 = async ({ networkId, tokensWithAddresses, connector, mini
4130
4170
  };
4131
4171
  }
4132
4172
  const addresses = (0, lodash_es.uniq)(balanceDefs.map((def) => def.address));
4173
+ const metadataRpc = miniMetadata.data;
4133
4174
  try {
4134
- const { builder } = parseMetadataRpcCached(miniMetadata.data);
4135
- const at = await fetchBestBlockHash(connector, networkId);
4136
- const stakeInfos = await fetchRuntimeCallResult(connector, networkId, builder, "StakeInfoRuntimeApi", "get_stake_info_for_coldkeys", [addresses], at);
4175
+ const { builder } = parseMetadataRpcCached(metadataRpc);
4176
+ const blockHash = await (at ?? fetchBestBlockHash(connector, networkId));
4177
+ const [stakeInfos, convictionLocks, basketClaims] = await Promise.all([
4178
+ fetchRuntimeCallResult(connector, networkId, builder, "StakeInfoRuntimeApi", "get_stake_info_for_coldkeys", [addresses], blockHash),
4179
+ fetchConvictionLocks(connector, networkId, metadataRpc, addresses, blockHash),
4180
+ fetchBasketClaims(connector, networkId, metadataRpc, addresses, blockHash),
4181
+ fetchRootStakeUnlockInterval(connector, networkId, metadataRpc, blockHash).catch(() => null)
4182
+ ]);
4137
4183
  const rootPairs = [];
4138
4184
  const seenRootPairs = /* @__PURE__ */ new Set();
4139
4185
  for (const [address, stakes] of stakeInfos) for (const stake of stakes) {
@@ -4146,15 +4192,7 @@ const fetchBalances$5 = async ({ networkId, tokensWithAddresses, connector, mini
4146
4192
  hotkey: stake.hotkey
4147
4193
  });
4148
4194
  }
4149
- const [convictionLocks, basketClaims, rootStakeHolds] = miniMetadata.data ? await Promise.all([
4150
- fetchConvictionLocks(connector, networkId, miniMetadata.data, addresses, at),
4151
- fetchBasketClaims(connector, networkId, miniMetadata.data, addresses, at),
4152
- fetchRootStakeHolds(connector, networkId, miniMetadata.data, rootPairs, at)
4153
- ]) : [
4154
- [],
4155
- [],
4156
- []
4157
- ];
4195
+ const rootStakeHolds = await fetchRootStakeHolds(connector, networkId, metadataRpc, rootPairs, blockHash);
4158
4196
  const upsertBalance = (acc, address, tokenId, balance) => {
4159
4197
  const key = `${address}:${tokenId}`;
4160
4198
  const recordedBalance = acc[key];
@@ -4515,6 +4553,10 @@ const isEffectivelyEqualDTaoBalance = (previous, next) => {
4515
4553
  return result.equivalence;
4516
4554
  };
4517
4555
  // src/modules/substrate-dtao/subscribeBalances.ts
4556
+ /**
4557
+ * Half of Bittensor's 12s block time, so a new block is read within 6s of being produced.
4558
+ * A poll that finds the same best block as the last good poll ends after that one request.
4559
+ */
4518
4560
  const SUBSCRIPTION_INTERVAL = 6e3;
4519
4561
  const subscribeBalances$5 = ({ networkId, tokensWithAddresses, connector, miniMetadata }) => {
4520
4562
  if (!tokensWithAddresses.length) return (0, rxjs.of)({
@@ -4524,21 +4566,32 @@ const subscribeBalances$5 = ({ networkId, tokensWithAddresses, connector, miniMe
4524
4566
  const balanceDefs = getBalanceDefs(tokensWithAddresses);
4525
4567
  return new rxjs.Observable((subscriber) => {
4526
4568
  const abortController = new AbortController();
4569
+ /** the block the last poll read without errors */
4570
+ let lastGoodBlockHash = null;
4527
4571
  const poll = async () => {
4528
4572
  try {
4529
4573
  if (abortController.signal.aborted) return;
4530
- const balances = await fetchBalances$5({
4574
+ const bestBlock = fetchBestBlockHash(connector, networkId);
4575
+ const blockHash = await bestBlock.catch(() => void 0);
4576
+ if (abortController.signal.aborted) return;
4577
+ if (blockHash && blockHash === lastGoodBlockHash) {
4578
+ setTimeout(poll, SUBSCRIPTION_INTERVAL);
4579
+ return;
4580
+ }
4581
+ const balances = await fetchBalancesAt({
4531
4582
  networkId,
4532
4583
  tokensWithAddresses,
4533
4584
  connector,
4534
4585
  miniMetadata,
4535
4586
  signal: abortController.signal
4536
- });
4587
+ }, blockHash ?? bestBlock);
4537
4588
  if (abortController.signal.aborted) return;
4589
+ lastGoodBlockHash = balances.errors.length ? null : blockHash ?? null;
4538
4590
  (0, _talismn_util.reportJsActivity)(`poll ${MODULE_TYPE$5} ${networkId} (${balances.success.length})`);
4539
4591
  subscriber.next(balances);
4540
4592
  } catch (error) {
4541
4593
  if (abortController.signal.aborted) return;
4594
+ lastGoodBlockHash = null;
4542
4595
  log_default.error("Error", {
4543
4596
  module: MODULE_TYPE$5,
4544
4597
  networkId,