@talismn/balances 0.0.0-pr2075-20250710052843 → 0.0.0-pr2075-20250710071608

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,5 @@
1
1
  export * from "./fetchRuntimeCallResult";
2
2
  export * from "./errors";
3
- export * from "./hasConstantValue";
4
- export * from "./getContantValue";
5
- export * from "./tryGetConstantValue";
6
3
  export * from "./types";
7
4
  export * from "./utils";
8
5
  export * from "./rpcQueryPack";
@@ -2,3 +2,5 @@ import { UnifiedMetadata } from "@talismn/scale";
2
2
  export declare const hasStorageItem: (metadata: UnifiedMetadata, palletName: string, itemName: string) => boolean;
3
3
  export declare const hasStorageItems: (metadata: UnifiedMetadata, palletName: string, itemNames: string[]) => boolean;
4
4
  export declare const hasRuntimeApi: (metadata: UnifiedMetadata, apiName: string, method: string) => boolean;
5
+ export declare const getConstantValue: <T>(metadataRpc: `0x${string}`, pallet: string, constant: string) => T;
6
+ export declare const tryGetConstantValue: <T>(metadataRpc: `0x${string}`, pallet: string, constant: string) => T | null;
@@ -1286,19 +1286,6 @@ const getUniswapV2PairContractData = async (client, contractAddress) => {
1286
1286
  };
1287
1287
  };
1288
1288
 
1289
- // const TokenCacheSchema = EvmUniswapV2TokenSchema.pick({
1290
- // id: true,
1291
- // symbol: true,
1292
- // decimals: true,
1293
- // name: true,
1294
- // tokenAddress0: true,
1295
- // tokenAddress1: true,
1296
- // decimals0: true,
1297
- // decimals1: true,
1298
- // symbol0: true,
1299
- // symbol1: true,
1300
- // })
1301
-
1302
1289
  const TokenCacheSchema = z__default.default.discriminatedUnion("isValid", [z__default.default.strictObject({
1303
1290
  id: chaindataProvider.EvmUniswapV2TokenSchema.shape.id,
1304
1291
  isValid: z__default.default.literal(true),
@@ -1534,6 +1521,21 @@ const fetchRuntimeCallResult = async (connector, networkId, metadataRpc, apiName
1534
1521
  return call.value.dec(hex);
1535
1522
  };
1536
1523
 
1524
+ const hasStorageItem = (metadata, palletName, itemName) => {
1525
+ const pallet = metadata.pallets.find(p => p.name === palletName);
1526
+ if (!pallet || !pallet.storage) return false;
1527
+ return pallet.storage.items.some(item => item.name === itemName);
1528
+ };
1529
+ const hasStorageItems = (metadata, palletName, itemNames) => {
1530
+ const pallet = metadata.pallets.find(p => p.name === palletName);
1531
+ if (!pallet || !pallet.storage) return false;
1532
+ return itemNames.every(itemName => pallet.storage?.items.some(item => item.name === itemName));
1533
+ };
1534
+ const hasRuntimeApi = (metadata, apiName, method) => {
1535
+ const api = metadata.apis.find(api => api.name === apiName);
1536
+ if (!api || !api.methods) return false;
1537
+ return api.methods.some(m => m.name === method);
1538
+ };
1537
1539
  const getConstantValue = (metadataRpc, pallet, constant) => {
1538
1540
  const {
1539
1541
  unifiedMetadata,
@@ -1548,7 +1550,6 @@ const getConstantValue = (metadataRpc, pallet, constant) => {
1548
1550
  if (!encodedValue) throw new Error(`Constant ${pallet}.${constant} not found`);
1549
1551
  return codec.dec(encodedValue);
1550
1552
  };
1551
-
1552
1553
  const tryGetConstantValue = (metadataRpc, pallet, constant) => {
1553
1554
  const {
1554
1555
  unifiedMetadata,
@@ -1564,22 +1565,6 @@ const tryGetConstantValue = (metadataRpc, pallet, constant) => {
1564
1565
  return codec.dec(encodedValue);
1565
1566
  };
1566
1567
 
1567
- const hasStorageItem = (metadata, palletName, itemName) => {
1568
- const pallet = metadata.pallets.find(p => p.name === palletName);
1569
- if (!pallet || !pallet.storage) return false;
1570
- return pallet.storage.items.some(item => item.name === itemName);
1571
- };
1572
- const hasStorageItems = (metadata, palletName, itemNames) => {
1573
- const pallet = metadata.pallets.find(p => p.name === palletName);
1574
- if (!pallet || !pallet.storage) return false;
1575
- return itemNames.every(itemName => pallet.storage?.items.some(item => item.name === itemName));
1576
- };
1577
- const hasRuntimeApi = (metadata, apiName, method) => {
1578
- const api = metadata.apis.find(api => api.name === apiName);
1579
- if (!api || !api.methods) return false;
1580
- return api.methods.some(m => m.name === method);
1581
- };
1582
-
1583
1568
  const buildNetworkStorageCoders = (chainId, miniMetadata, coders) => {
1584
1569
  if (!miniMetadata.data) return null;
1585
1570
  const metadata = scale.unifyMetadata(scale.decAnyMetadata(miniMetadata.data));
@@ -3757,41 +3742,6 @@ const buildBaseQueries = (networkId, balanceDefs, miniMetadata) => {
3757
3742
  };
3758
3743
  }).filter(util.isNotNil);
3759
3744
  };
3760
-
3761
- // AccountInfo is the state_storage data format for nativeToken balances
3762
- // Theory: new chains will be at least on metadata v14, and so we won't need to hardcode their AccountInfo type.
3763
- // But for chains we want to support which aren't on metadata v14, hardcode them here:
3764
- // If the chain upgrades to metadata v14, this override will be ignored :)
3765
- // const RegularAccountInfoFallback = Struct({
3766
- // nonce: u32,
3767
- // consumers: u32,
3768
- // providers: u32,
3769
- // sufficients: u32,
3770
- // data: Struct({ free: u128, reserved: u128, miscFrozen: u128, feeFrozen: u128 }),
3771
- // })
3772
- // const NoSufficientsAccountInfoFallback = Struct({
3773
- // nonce: u32,
3774
- // consumers: u32,
3775
- // providers: u32,
3776
- // data: Struct({ free: u128, reserved: u128, miscFrozen: u128, feeFrozen: u128 }),
3777
- // })
3778
- // const AccountInfoOverrides: Record<
3779
- // string,
3780
- // typeof RegularAccountInfoFallback | typeof NoSufficientsAccountInfoFallback | undefined
3781
- // > = {
3782
- // // crown-sterlin is not yet on metadata v14
3783
- // "crown-sterling": NoSufficientsAccountInfoFallback,
3784
-
3785
- // // crust is not yet on metadata v14
3786
- // "crust": NoSufficientsAccountInfoFallback,
3787
-
3788
- // // kulupu is not yet on metadata v14
3789
- // "kulupu": RegularAccountInfoFallback,
3790
-
3791
- // // nftmart is not yet on metadata v14
3792
- // "nftmart": RegularAccountInfoFallback,
3793
- // }
3794
-
3795
3745
  const decodeBaseResult = (coder, value, networkId) => {
3796
3746
  /** NOTE: This type is only a hint for typescript, the chain can actually return whatever it wants to */
3797
3747
 
@@ -3842,15 +3792,6 @@ const decodeLocksResult = (coder, value, networkId) => {
3842
3792
  amount: (lock?.amount ?? 0n).toString()
3843
3793
  })) ?? [];
3844
3794
  return locksQueryLocks;
3845
-
3846
- // // locked values should be replaced entirely, not merged or appended
3847
- // const nonLockValues = balanceJson.values.filter(
3848
- // (v) => v.source !== "substrate-native-locks",
3849
- // )
3850
- // balanceJson.values = nonLockValues.concat(locksQueryLocks)
3851
-
3852
- // // fix any double-counting between Balances.Locks (for staking locks) and Staking.Ledger (for unbonding locks)
3853
- // balanceJson.values = updateStakingLocksUsingUnbondingLocks(balanceJson.values)
3854
3795
  };
3855
3796
  const decodeFreezesResult = (coder, value, networkId) => {
3856
3797
  /** NOTE: This type is only a hint for typescript, the chain can actually return whatever it wants to */
@@ -3863,14 +3804,6 @@ const decodeFreezesResult = (coder, value, networkId) => {
3863
3804
  amount: lock?.amount?.toString?.() ?? "0"
3864
3805
  })) ?? [];
3865
3806
  return freezesValues;
3866
-
3867
- // // freezes values should be replaced entirely, not merged or appended
3868
- // const nonFreezesValues = balanceJson.values.filter(
3869
- // (v) => v.source !== "substrate-native-freezes",
3870
- // )
3871
- // balanceJson.values = nonFreezesValues.concat(freezesQueryLocks)
3872
-
3873
- // return balanceJson
3874
3807
  };
3875
3808
  const decodeHoldsResult = (coder, value, networkId) => {
3876
3809
  /** NOTE: This type is only a hint for typescript, the chain can actually return whatever it wants to */
@@ -3889,14 +3822,6 @@ const decodeHoldsResult = (coder, value, networkId) => {
3889
3822
  }
3890
3823
  })) ?? [];
3891
3824
  return holdsValues;
3892
-
3893
- // // values should be replaced entirely, not merged or appended
3894
- // const nonHoldsValues = balanceJson.values.filter(
3895
- // (v) => v.source !== "substrate-native-holds",
3896
- // )
3897
- // balanceJson.values = nonHoldsValues.concat(holdsQueryLocks)
3898
-
3899
- // return balanceJson
3900
3825
  };
3901
3826
  const decodeStakingLedgerResult = (coder, value, networkId) => {
3902
3827
  /** NOTE: This type is only a hint for typescript, the chain can actually return whatever it wants to */
@@ -3911,29 +3836,6 @@ const decodeStakingLedgerResult = (coder, value, networkId) => {
3911
3836
  amount: totalUnlocking.toString()
3912
3837
  }];
3913
3838
  return stakingLedgerResults;
3914
-
3915
- // if (totalUnlocking <= 0n) unbondingQueryLocks = []
3916
- // else {
3917
- // unbondingQueryLocks = [
3918
- // {
3919
- // type: "locked",
3920
- // source: "substrate-native-unbonding",
3921
- // label: "Unbonding",
3922
- // amount: totalUnlocking.toString(),
3923
- // },
3924
- // ]
3925
- // }
3926
-
3927
- // // unbonding values should be replaced entirely, not merged or appended
3928
- // const nonUnbondingValues = balanceJson.values.filter(
3929
- // (v) => v.source !== "substrate-native-unbonding",
3930
- // )
3931
- // balanceJson.values = nonUnbondingValues.concat(unbondingQueryLocks)
3932
-
3933
- // // fix any double-counting between Balances.Locks (for staking locks) and Staking.Ledger (for unbonding locks)
3934
- // balanceJson.values = updateStakingLocksUsingUnbondingLocks(balanceJson.values)
3935
-
3936
- // return balanceJson
3937
3839
  };
3938
3840
  const decodePoolMemberResult = (coder, value, networkId) => {
3939
3841
  /** NOTE: This type is only a hint for typescript, the chain can actually return whatever it wants to */
@@ -3960,109 +3862,6 @@ const decodePoolMemberResult = (coder, value, networkId) => {
3960
3862
  };
3961
3863
  };
3962
3864
 
3963
- // const getBaseQuery = (
3964
- // networkId: string,
3965
- // address: string,
3966
- // coder: ScaleStorageCoder,
3967
- // ): RpcStateQuery<Array<AmountWithLabel<string>>> | null => {
3968
- // // For chains which are using metadata < v14
3969
- // const getFallbackStateKey = () => {
3970
- // const addressBytes = decodeAnyAddress(address) // TODO replace with modern api, this is slow
3971
- // const addressHash = blake2Concat(addressBytes).replace(/^0x/, "")
3972
- // const moduleHash = "26aa394eea5630e07c48ae0c9558cef7" // util_crypto.xxhashAsHex("System", 128);
3973
- // const storageHash = "b99d880ec681799c0cf30e8886371da9" // util_crypto.xxhashAsHex("Account", 128);
3974
- // const moduleStorageHash = `${moduleHash}${storageHash}` // System.Account is the state_storage key prefix for nativeToken balances
3975
- // return `0x${moduleStorageHash}${addressHash}`
3976
- // }
3977
-
3978
- // // const scaleCoder = chainStorageCoders.get(chainId)?.base
3979
- // // NOTE: Only use fallback key when `scaleCoder` is not defined
3980
- // // i.e. when chain doesn't have metadata v14/v15
3981
- // const stateKey = coder
3982
- // ? encodeStateKey(coder, `Invalid address in ${networkId} base query ${address}`, address)
3983
- // : getFallbackStateKey()
3984
- // if (!stateKey) return null
3985
-
3986
- // const decodeResult = (change: string | null) => {
3987
- // // BEGIN: Handle chains which use metadata < v14
3988
- // let oldChainBalance = null
3989
- // if (!coder) {
3990
- // const scaleAccountInfo = AccountInfoOverrides[networkId]
3991
- // if (scaleAccountInfo === undefined) {
3992
- // // chain metadata version is < 15 and we also don't have an override hardcoded in
3993
- // // the best way to handle this case: log a warning and return an empty balance
3994
- // log.debug(
3995
- // `Native token on chain ${networkId} has no balance type for decoding. Defaulting to a balance of 0 (zero).`,
3996
- // )
3997
- // return []
3998
- // }
3999
-
4000
- // try {
4001
- // // eslint-disable-next-line no-var
4002
- // oldChainBalance = change === null ? null : scaleAccountInfo.dec(change)
4003
- // } catch (error) {
4004
- // log.warn(
4005
- // `Failed to create pre-metadataV14 balance type for native on chain ${networkId}: ${error?.toString()}`,
4006
- // )
4007
- // return []
4008
- // }
4009
- // }
4010
- // // END: Handle chains which use metadata < v14
4011
-
4012
- // /** NOTE: This type is only a hint for typescript, the chain can actually return whatever it wants to */
4013
- // type DecodedType = {
4014
- // data?: {
4015
- // flags?: bigint
4016
- // free?: bigint
4017
- // frozen?: bigint
4018
- // reserved?: bigint
4019
-
4020
- // // deprecated fields (they only show up on old chains)
4021
- // feeFrozen?: bigint
4022
- // miscFrozen?: bigint
4023
- // }
4024
- // }
4025
- // const decoded =
4026
- // decodeScale<DecodedType>(
4027
- // coder,
4028
- // change,
4029
- // `Failed to decode base native balance on chain ${networkId}`,
4030
- // ) ?? oldChainBalance
4031
-
4032
- // const free = (decoded?.data?.free ?? 0n).toString()
4033
- // const reserved = (decoded?.data?.reserved ?? 0n).toString()
4034
- // const miscLock = (
4035
- // (decoded?.data?.miscFrozen ?? 0n) +
4036
- // // new chains don't split their `frozen` amount into `feeFrozen` and `miscFrozen`.
4037
- // // for these chains, we'll use the `frozen` amount as `miscFrozen`.
4038
- // ((decoded?.data as DecodedType["data"])?.frozen ?? 0n)
4039
- // ).toString()
4040
- // const feesLock = (decoded?.data?.feeFrozen ?? 0n).toString()
4041
-
4042
- // // even if these values are 0, we still need to add them to the balanceJson.values array
4043
- // // so that the balance pool can handle newly zeroed balances
4044
- // // const existingValues = Object.fromEntries(
4045
- // // balanceJson.values.map((v) => [getValueId(v), v]),
4046
- // // )
4047
- // const newValues: AmountWithLabel<string>[] = [
4048
- // { type: "free", label: "free", amount: free.toString() },
4049
- // { type: "reserved", label: "reserved", amount: reserved.toString() },
4050
- // { type: "locked", label: "misc", amount: miscLock.toString() },
4051
- // { type: "locked", label: "fees", amount: feesLock.toString() },
4052
- // ]
4053
-
4054
- // return newValues
4055
-
4056
- // // const newValuesObj = Object.fromEntries(newValues.map((v) => [getValueId(v), v]))
4057
-
4058
- // // balanceJson.values = Object.values({ ...existingValues, ...newValuesObj })
4059
-
4060
- // // return balanceJson
4061
- // }
4062
-
4063
- // return { chainId: networkId, stateKey, decodeResult }
4064
- // }
4065
-
4066
3865
  /**
4067
3866
  * Each nominationPool in the nominationPools pallet has access to some accountIds which have no
4068
3867
  * associated private key. Instead, they are derived from this function.
@@ -4110,7 +3909,9 @@ const buildNomPoolQueries = (networkId, partialBalances, miniMetadata) => {
4110
3909
  }) => total + BigInt(amount ?? "0"), 0n);
4111
3910
  return {
4112
3911
  ...balance,
4113
- values: [...(balance.values ?? []), {
3912
+ values: [...(balance.values?.filter(({
3913
+ source
3914
+ }) => source !== "nompools-staking") ?? []), {
4114
3915
  source: "nompools-staking",
4115
3916
  type: "nompool",
4116
3917
  label: "nompools-staking",
@@ -4240,7 +4041,9 @@ const fetchBalances$2 = async ({
4240
4041
  const subtensorBalancesByAddress = await rxjs.firstValueFrom(subtensorBalances$);
4241
4042
  for (const [address, subtensorBalances] of Object.entries(subtensorBalancesByAddress)) {
4242
4043
  const balance = balances.find(b => b.address === address);
4243
- if (balance?.values) balance.values.push(...subtensorBalances);
4044
+ if (balance?.values) balance.values = [...balance.values.filter(({
4045
+ source
4046
+ }) => source !== "subtensor-staking"), ...subtensorBalances];
4244
4047
  }
4245
4048
  return {
4246
4049
  success: balances,
@@ -4354,13 +4157,9 @@ const getMiniMetadata$2 = ({
4354
4157
  }, {
4355
4158
  pallet: "Staking",
4356
4159
  items: ["Ledger"]
4357
- },
4358
- // TotalColdkeyStake is used until v.2.2.1, then it is replaced by StakingHotkeys+Stake
4359
- // Need to keep TotalColdkeyStake for a while so chaindata keeps including it in miniMetadatas, so it doesnt break old versions of the wallet
4360
- // TODO: Since chaindata v4 this is safe to now delete
4361
- {
4160
+ }, {
4362
4161
  pallet: "SubtensorModule",
4363
- items: ["TotalColdkeyStake", "StakingHotkeys", "Stake"]
4162
+ items: ["StakingHotkeys", "Stake"]
4364
4163
  }], [{
4365
4164
  runtimeApi: "StakeInfoRuntimeApi",
4366
4165
  methods: ["get_stake_info_for_coldkey"]
@@ -4492,7 +4291,9 @@ const subscribeBalances$2 = ({
4492
4291
  // add subtensor balances to base balances
4493
4292
  for (const [address, subtensorBalances] of lodashEs.toPairs(subtensorBalancesByAddress)) {
4494
4293
  const balance = baseBalances.find(b => b.address === address);
4495
- if (balance?.values) balance.values.push(...subtensorBalances);
4294
+ if (balance?.values) balance.values = [...balance.values.filter(({
4295
+ source
4296
+ }) => source !== "subtensor-staking"), ...subtensorBalances];
4496
4297
  }
4497
4298
  return {
4498
4299
  success: baseBalances,
@@ -6347,8 +6148,10 @@ const getMetadataRpc = async (chainConnector, networkId) => {
6347
6148
  if (CACHE$1.has(networkId)) return CACHE$1.get(networkId);
6348
6149
  const pResult = sapi.fetchBestMetadata((method, params, isCacheable) => chainConnector.send(networkId, method, params, isCacheable, {
6349
6150
  expectErrors: true
6350
- }), true // allow fallback to 14 as modules dont use any v15 or v16 specifics yet
6351
- );
6151
+ }),
6152
+ // do not allow fallback to v14 unless unavailable.
6153
+ // substrate-native and substrate-hydration need v15 metadata for runtime api calls
6154
+ false);
6352
6155
  CACHE$1.set(networkId, pResult);
6353
6156
  try {
6354
6157
  return await pResult;