@talismn/balances 0.0.0-pr2091-20250715125148 → 0.0.0-pr2092-20250715131755

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,14 +1,12 @@
1
- import { EvmErc20TokenSchema, parseTokenId, parseEvmErc20TokenId, evmErc20TokenId, isTokenOfType, TokenBaseSchema, EvmNativeTokenSchema, evmNativeTokenId, EvmUniswapV2TokenSchema, evmUniswapV2TokenId, SolNativeTokenSchema, solNativeTokenId, SubAssetsTokenSchema, subAssetTokenId, MINIMETADATA_VERSION, SubForeignAssetsTokenSchema, subForeignAssetTokenId, SubHydrationTokenSchema, subHydrationTokenId, SubNativeTokenSchema, subNativeTokenId, SubPsp22TokenSchema, subPsp22TokenId, SubTokensTokenSchema, subTokensTokenId, isNetworkDot } from '@talismn/chaindata-provider';
1
+ import { EvmErc20TokenSchema, parseTokenId, parseEvmErc20TokenId, evmErc20TokenId, isTokenOfType, TokenBaseSchema, EvmNativeTokenSchema, evmNativeTokenId, EvmUniswapV2TokenSchema, evmUniswapV2TokenId, SubAssetsTokenSchema, subAssetTokenId, MINIMETADATA_VERSION, SubForeignAssetsTokenSchema, subForeignAssetTokenId, SubHydrationTokenSchema, subHydrationTokenId, SubNativeTokenSchema, subNativeTokenId, SubPsp22TokenSchema, subPsp22TokenId, SubTokensTokenSchema, subTokensTokenId, isNetworkDot } from '@talismn/chaindata-provider';
2
2
  export { MINIMETADATA_VERSION } from '@talismn/chaindata-provider';
3
- import { isEthereumAddress, isSolanaAddress, normalizeAddress, getAccountPlatformFromAddress } from '@talismn/crypto';
3
+ import { isEthereumAddress, isNotNil, BigMath, isArrayOf, isBigInt, planckToTokens, isAbortError, getSharedObservable, keepAlive, isTruthy, normalizeAddress } from '@talismn/util';
4
4
  import { parseAbi, erc20Abi, getContract, ContractFunctionExecutionError, hexToString, erc20Abi_bytes32, encodeFunctionData, withRetry } from 'viem';
5
5
  import { assign, omit, isEqual, uniq, keyBy, keys, fromPairs, values, toPairs } from 'lodash-es';
6
6
  import z from 'zod/v4';
7
7
  import anylogger from 'anylogger';
8
8
  import { of, Observable, distinctUntilChanged, map, timer, switchMap, from, firstValueFrom, combineLatest, BehaviorSubject, shareReplay, startWith, filter, defer, catchError, EMPTY, tap } from 'rxjs';
9
9
  import BigNumber from 'bignumber.js';
10
- import { PublicKey } from '@solana/web3.js';
11
- import { isNotNil, BigMath, isArrayOf, isBigInt, planckToTokens, isAbortError, getSharedObservable, keepAlive, isTruthy } from '@talismn/util';
12
10
  import { parseMetadataRpc, toHex, unifyMetadata, decAnyMetadata, getDynamicBuilder, getLookupFn, decodeScale, getStorageKeyPrefix, Twox128, compactMetadata, encodeMetadata, papiParse, papiStringify } from '@talismn/scale';
13
11
  import { newTokenRates } from '@talismn/token-rates';
14
12
  import { mergeUint8 } from '@polkadot-api/utils';
@@ -21,8 +19,8 @@ import { u8aToHex, u8aConcatStrict, u8aToString, hexToNumber } from '@polkadot/u
21
19
  import PQueue from 'p-queue';
22
20
  import { fetchBestMetadata } from '@talismn/sapi';
23
21
 
24
- const MODULE_TYPE$9 = EvmErc20TokenSchema.shape.type.value;
25
- const PLATFORM$9 = EvmErc20TokenSchema.shape.platform.value;
22
+ const MODULE_TYPE$8 = EvmErc20TokenSchema.shape.type.value;
23
+ const PLATFORM$8 = EvmErc20TokenSchema.shape.platform.value;
26
24
 
27
25
  const abiMulticall = parseAbi(["struct Call { address target; bytes callData; }", "struct Call3 { address target; bool allowFailure; bytes callData; }", "struct Call3Value { address target; bool allowFailure; uint256 value; bytes callData; }", "struct Result { bool success; bytes returnData; }", "function aggregate(Call[] calldata calls) public payable returns (uint256 blockNumber, bytes[] memory returnData)", "function aggregate3(Call3[] calldata calls) public payable returns (Result[] memory returnData)", "function aggregate3Value(Call3Value[] calldata calls) public payable returns (Result[] memory returnData)", "function blockAndAggregate(Call[] calldata calls) public payable returns (uint256 blockNumber, bytes32 blockHash, Result[] memory returnData)", "function getBasefee() view returns (uint256 basefee)", "function getBlockHash(uint256 blockNumber) view returns (bytes32 blockHash)", "function getBlockNumber() view returns (uint256 blockNumber)", "function getChainId() view returns (uint256 chainid)", "function getCurrentBlockCoinbase() view returns (address coinbase)", "function getCurrentBlockDifficulty() view returns (uint256 difficulty)", "function getCurrentBlockGasLimit() view returns (uint256 gaslimit)", "function getCurrentBlockTimestamp() view returns (uint256 timestamp)", "function getEthBalance(address addr) view returns (uint256 balance)", "function getLastBlockHash() view returns (bytes32 blockHash)", "function tryAggregate(bool requireSuccess, Call[] calldata calls) public payable returns (Result[] memory returnData)", "function tryBlockAndAggregate(bool requireSuccess, Call[] calldata calls) public payable returns (uint256 blockNumber, bytes32 blockHash, Result[] memory returnData)"]);
28
26
 
@@ -618,7 +616,7 @@ const getBalanceDefs = addressesByToken => {
618
616
  // if there is at least one storage entry, the results will be an array with a single object
619
617
  // if the storage has no entries in it (ex: Assets on ewx or moonbeam), the response will be an empty array
620
618
 
621
- const fetchBalances$9 = async ({
619
+ const fetchBalances$8 = async ({
622
620
  networkId,
623
621
  tokensWithAddresses,
624
622
  connector
@@ -630,7 +628,7 @@ const fetchBalances$9 = async ({
630
628
  const client = await connector.getPublicClientForEvmNetwork(networkId);
631
629
  if (!client) throw new Error(`Could not get rpc provider for evm network ${networkId}`);
632
630
  for (const [token, addresses] of tokensWithAddresses) {
633
- if (token.type !== MODULE_TYPE$9 || token.networkId !== networkId) throw new Error(`Invalid token type or networkId for EVM ERC20 balance module: ${token.type} on ${token.networkId}`);
631
+ if (token.type !== MODULE_TYPE$8 || token.networkId !== networkId) throw new Error(`Invalid token type or networkId for EVM ERC20 balance module: ${token.type} on ${token.networkId}`);
634
632
  for (const address of addresses) if (!isEthereumAddress(address)) throw new Error(`Invalid ethereum address for EVM ERC20 balance module: ${address} for token ${token.id}`);
635
633
  }
636
634
  const balanceDefs = getBalanceDefs(tokensWithAddresses);
@@ -660,7 +658,7 @@ const fetchWithoutAggregator = async (client, balanceDefs) => {
660
658
  address,
661
659
  tokenId: token.id,
662
660
  value: result.toString(),
663
- source: MODULE_TYPE$9,
661
+ source: MODULE_TYPE$8,
664
662
  networkId: parseEvmErc20TokenId(token.id).networkId,
665
663
  status: "live"
666
664
  };
@@ -703,7 +701,7 @@ const fetchWithAggregator = async (client, balanceDefs, erc20BalancesAggregatorA
703
701
  address: balanceDef.address,
704
702
  tokenId: balanceDef.token.id,
705
703
  value: erc20Balances[index].toString(),
706
- source: MODULE_TYPE$9,
704
+ source: MODULE_TYPE$8,
707
705
  networkId: parseTokenId(balanceDef.token.id).networkId,
708
706
  status: "live"
709
707
  }));
@@ -772,7 +770,7 @@ const TokenCacheSchema$1 = z.discriminatedUnion("isValid", [z.strictObject({
772
770
  id: EvmErc20TokenSchema.shape.id,
773
771
  isValid: z.literal(false)
774
772
  })]);
775
- const fetchTokens$9 = async ({
773
+ const fetchTokens$8 = async ({
776
774
  networkId,
777
775
  tokens,
778
776
  connector,
@@ -812,8 +810,8 @@ const fetchTokens$9 = async ({
812
810
  }
813
811
  const base = {
814
812
  id: tokenId,
815
- type: MODULE_TYPE$9,
816
- platform: PLATFORM$9,
813
+ type: MODULE_TYPE$8,
814
+ platform: PLATFORM$8,
817
815
  networkId
818
816
  };
819
817
  const cached2 = cache[tokenId] && TokenCacheSchema$1.safeParse(cache[tokenId]).data;
@@ -831,17 +829,17 @@ const fetchTokens$9 = async ({
831
829
  return result;
832
830
  };
833
831
 
834
- const getMiniMetadata$9 = () => {
832
+ const getMiniMetadata$8 = () => {
835
833
  throw new Error("MiniMetadata is not supported for ethereum tokens");
836
834
  };
837
835
 
838
- const getTransferCallData$9 = ({
836
+ const getTransferCallData$8 = ({
839
837
  from,
840
838
  to,
841
839
  value,
842
840
  token
843
841
  }) => {
844
- if (!isTokenOfType(token, MODULE_TYPE$9)) throw new Error(`Token type ${token.type} is not ${MODULE_TYPE$9}.`);
842
+ if (!isTokenOfType(token, MODULE_TYPE$8)) throw new Error(`Token type ${token.type} is not ${MODULE_TYPE$8}.`);
845
843
  if (!isEthereumAddress(from)) throw new Error("Invalid from address");
846
844
  if (!isEthereumAddress(to)) throw new Error("Invalid to address");
847
845
  const data = encodeFunctionData({
@@ -856,8 +854,8 @@ const getTransferCallData$9 = ({
856
854
  };
857
855
  };
858
856
 
859
- const SUBSCRIPTION_INTERVAL$5 = 6_000;
860
- const subscribeBalances$9 = ({
857
+ const SUBSCRIPTION_INTERVAL$4 = 6_000;
858
+ const subscribeBalances$8 = ({
861
859
  networkId,
862
860
  tokensWithAddresses,
863
861
  connector
@@ -871,17 +869,17 @@ const subscribeBalances$9 = ({
871
869
  const poll = async () => {
872
870
  try {
873
871
  if (abortController.signal.aborted) return;
874
- const balances = await fetchBalances$9({
872
+ const balances = await fetchBalances$8({
875
873
  networkId,
876
874
  tokensWithAddresses: tokensWithAddresses,
877
875
  connector
878
876
  });
879
877
  if (abortController.signal.aborted) return;
880
878
  subscriber.next(balances);
881
- setTimeout(poll, SUBSCRIPTION_INTERVAL$5);
879
+ setTimeout(poll, SUBSCRIPTION_INTERVAL$4);
882
880
  } catch (error) {
883
881
  log.error("Error", {
884
- module: MODULE_TYPE$9,
882
+ module: MODULE_TYPE$8,
885
883
  networkId,
886
884
  addressesByToken: tokensWithAddresses,
887
885
  error
@@ -897,13 +895,13 @@ const subscribeBalances$9 = ({
897
895
  };
898
896
 
899
897
  const EvmErc20BalanceModule = {
900
- type: MODULE_TYPE$9,
901
- platform: PLATFORM$9,
902
- getMiniMetadata: getMiniMetadata$9,
903
- fetchTokens: fetchTokens$9,
904
- fetchBalances: fetchBalances$9,
905
- subscribeBalances: subscribeBalances$9,
906
- getTransferCallData: getTransferCallData$9
898
+ type: MODULE_TYPE$8,
899
+ platform: PLATFORM$8,
900
+ getMiniMetadata: getMiniMetadata$8,
901
+ fetchTokens: fetchTokens$8,
902
+ fetchBalances: fetchBalances$8,
903
+ subscribeBalances: subscribeBalances$8,
904
+ getTransferCallData: getTransferCallData$8
907
905
  };
908
906
 
909
907
  const TokenConfigBaseSchema = TokenBaseSchema.partial().omit({
@@ -916,10 +914,10 @@ const EvmErc20TokenConfigSchema = z.strictObject({
916
914
  ...TokenConfigBaseSchema.shape
917
915
  });
918
916
 
919
- const MODULE_TYPE$8 = EvmNativeTokenSchema.shape.type.value;
920
- const PLATFORM$8 = EvmNativeTokenSchema.shape.platform.value;
917
+ const MODULE_TYPE$7 = EvmNativeTokenSchema.shape.type.value;
918
+ const PLATFORM$7 = EvmNativeTokenSchema.shape.platform.value;
921
919
 
922
- const fetchBalances$8 = async ({
920
+ const fetchBalances$7 = async ({
923
921
  networkId,
924
922
  tokensWithAddresses,
925
923
  connector
@@ -931,7 +929,7 @@ const fetchBalances$8 = async ({
931
929
  const client = await connector.getPublicClientForEvmNetwork(networkId);
932
930
  if (!client) throw new Error(`Could not get rpc provider for evm network ${networkId}`);
933
931
  for (const [token, addresses] of tokensWithAddresses) {
934
- if (token.type !== MODULE_TYPE$8 || token.networkId !== networkId) throw new Error(`Invalid token type or networkId for EVM ERC20 balance module: ${token.type} on ${token.networkId}`);
932
+ if (token.type !== MODULE_TYPE$7 || token.networkId !== networkId) throw new Error(`Invalid token type or networkId for EVM ERC20 balance module: ${token.type} on ${token.networkId}`);
935
933
  for (const address of addresses) if (!isEthereumAddress(address)) throw new Error(`Invalid ethereum address for EVM ERC20 balance module: ${address} for token ${token.id}`);
936
934
  }
937
935
  const balanceDefs = getBalanceDefs(tokensWithAddresses);
@@ -958,7 +956,7 @@ const fetchWithoutMulticall = async (client, balanceDefs) => {
958
956
  address,
959
957
  tokenId: token.id,
960
958
  value: result.toString(),
961
- source: MODULE_TYPE$8,
959
+ source: MODULE_TYPE$7,
962
960
  networkId: parseTokenId(token.id).networkId,
963
961
  status: "live"
964
962
  };
@@ -1004,7 +1002,7 @@ const fetchWithMulticall = async (client, balanceDefs, multicall3Address) => {
1004
1002
  address: balanceDefs[index].address,
1005
1003
  tokenId: balanceDefs[index].token.id,
1006
1004
  value: result.result.toString(),
1007
- source: MODULE_TYPE$8,
1005
+ source: MODULE_TYPE$7,
1008
1006
  networkId: parseTokenId(balanceDefs[index].token.id).networkId,
1009
1007
  status: "live"
1010
1008
  });
@@ -1034,7 +1032,7 @@ const fetchWithMulticall = async (client, balanceDefs, multicall3Address) => {
1034
1032
  }
1035
1033
  };
1036
1034
 
1037
- const fetchTokens$8 = async ({
1035
+ const fetchTokens$7 = async ({
1038
1036
  networkId,
1039
1037
  tokens
1040
1038
  }) => {
@@ -1042,8 +1040,8 @@ const fetchTokens$8 = async ({
1042
1040
  if (tokens.length !== 1) throw new Error("EVM Native module expects the nativeCurrency to be passed as a single token in the array");
1043
1041
  const token = assign({
1044
1042
  id: evmNativeTokenId(networkId),
1045
- type: MODULE_TYPE$8,
1046
- platform: PLATFORM$8,
1043
+ type: MODULE_TYPE$7,
1044
+ platform: PLATFORM$7,
1047
1045
  networkId,
1048
1046
  isDefault: true
1049
1047
  }, tokens[0]);
@@ -1055,17 +1053,17 @@ const fetchTokens$8 = async ({
1055
1053
  return [parsed.data];
1056
1054
  };
1057
1055
 
1058
- const getMiniMetadata$8 = () => {
1056
+ const getMiniMetadata$7 = () => {
1059
1057
  throw new Error("MiniMetadata is not supported for ethereum tokens");
1060
1058
  };
1061
1059
 
1062
- const getTransferCallData$8 = ({
1060
+ const getTransferCallData$7 = ({
1063
1061
  from,
1064
1062
  to,
1065
1063
  value,
1066
1064
  token
1067
1065
  }) => {
1068
- if (!isTokenOfType(token, MODULE_TYPE$8)) throw new Error(`Token type ${token.type} is not ${MODULE_TYPE$8}.`);
1066
+ if (!isTokenOfType(token, MODULE_TYPE$7)) throw new Error(`Token type ${token.type} is not ${MODULE_TYPE$7}.`);
1069
1067
  if (!isEthereumAddress(from)) throw new Error("Invalid from address");
1070
1068
  if (!isEthereumAddress(to)) throw new Error("Invalid to address");
1071
1069
  return {
@@ -1076,8 +1074,8 @@ const getTransferCallData$8 = ({
1076
1074
  };
1077
1075
  };
1078
1076
 
1079
- const SUBSCRIPTION_INTERVAL$4 = 6_000;
1080
- const subscribeBalances$8 = ({
1077
+ const SUBSCRIPTION_INTERVAL$3 = 6_000;
1078
+ const subscribeBalances$7 = ({
1081
1079
  networkId,
1082
1080
  tokensWithAddresses,
1083
1081
  connector
@@ -1091,17 +1089,17 @@ const subscribeBalances$8 = ({
1091
1089
  const poll = async () => {
1092
1090
  try {
1093
1091
  if (abortController.signal.aborted) return;
1094
- const balances = await fetchBalances$8({
1092
+ const balances = await fetchBalances$7({
1095
1093
  networkId,
1096
1094
  tokensWithAddresses: tokensWithAddresses,
1097
1095
  connector
1098
1096
  });
1099
1097
  if (abortController.signal.aborted) return;
1100
1098
  subscriber.next(balances);
1101
- setTimeout(poll, SUBSCRIPTION_INTERVAL$4);
1099
+ setTimeout(poll, SUBSCRIPTION_INTERVAL$3);
1102
1100
  } catch (error) {
1103
1101
  log.error("Error", {
1104
- module: MODULE_TYPE$8,
1102
+ module: MODULE_TYPE$7,
1105
1103
  networkId,
1106
1104
  addressesByToken: tokensWithAddresses,
1107
1105
  error
@@ -1117,13 +1115,13 @@ const subscribeBalances$8 = ({
1117
1115
  };
1118
1116
 
1119
1117
  const EvmNativeBalanceModule = {
1120
- type: MODULE_TYPE$8,
1121
- platform: PLATFORM$8,
1122
- getMiniMetadata: getMiniMetadata$8,
1123
- fetchTokens: fetchTokens$8,
1124
- fetchBalances: fetchBalances$8,
1125
- subscribeBalances: subscribeBalances$8,
1126
- getTransferCallData: getTransferCallData$8
1118
+ type: MODULE_TYPE$7,
1119
+ platform: PLATFORM$7,
1120
+ getMiniMetadata: getMiniMetadata$7,
1121
+ fetchTokens: fetchTokens$7,
1122
+ fetchBalances: fetchBalances$7,
1123
+ subscribeBalances: subscribeBalances$7,
1124
+ getTransferCallData: getTransferCallData$7
1127
1125
  };
1128
1126
 
1129
1127
  // to be used by chaindata too
@@ -1131,10 +1129,10 @@ const EvmNativeTokenConfigSchema = z.strictObject({
1131
1129
  ...TokenConfigBaseSchema.shape
1132
1130
  });
1133
1131
 
1134
- const MODULE_TYPE$7 = EvmUniswapV2TokenSchema.shape.type.value;
1135
- const PLATFORM$7 = EvmUniswapV2TokenSchema.shape.platform.value;
1132
+ const MODULE_TYPE$6 = EvmUniswapV2TokenSchema.shape.type.value;
1133
+ const PLATFORM$6 = EvmUniswapV2TokenSchema.shape.platform.value;
1136
1134
 
1137
- const fetchBalances$7 = async ({
1135
+ const fetchBalances$6 = async ({
1138
1136
  networkId,
1139
1137
  tokensWithAddresses,
1140
1138
  connector
@@ -1146,7 +1144,7 @@ const fetchBalances$7 = async ({
1146
1144
  const client = await connector.getPublicClientForEvmNetwork(networkId);
1147
1145
  if (!client) throw new Error(`Could not get rpc provider for evm network ${networkId}`);
1148
1146
  for (const [token, addresses] of tokensWithAddresses) {
1149
- if (token.type !== MODULE_TYPE$7 || token.networkId !== networkId) throw new Error(`Invalid token type or networkId for EVM ERC20 balance module: ${token.type} on ${token.networkId}`);
1147
+ if (token.type !== MODULE_TYPE$6 || token.networkId !== networkId) throw new Error(`Invalid token type or networkId for EVM ERC20 balance module: ${token.type} on ${token.networkId}`);
1150
1148
  for (const address of addresses) if (!isEthereumAddress(address)) throw new Error(`Invalid ethereum address for EVM ERC20 balance module: ${address} for token ${token.id}`);
1151
1149
  }
1152
1150
  const balanceDefs = getBalanceDefs(tokensWithAddresses);
@@ -1233,7 +1231,7 @@ const fetchPoolBalances = async (client, balanceDefs) => {
1233
1231
  acc.success.push({
1234
1232
  address,
1235
1233
  tokenId: token.id,
1236
- source: MODULE_TYPE$7,
1234
+ source: MODULE_TYPE$6,
1237
1235
  networkId: parseTokenId(token.id).networkId,
1238
1236
  status: "live",
1239
1237
  values: [{
@@ -1311,7 +1309,7 @@ const TokenCacheSchema = z.discriminatedUnion("isValid", [z.strictObject({
1311
1309
  id: EvmUniswapV2TokenSchema.shape.id,
1312
1310
  isValid: z.literal(false)
1313
1311
  })]);
1314
- const fetchTokens$7 = async ({
1312
+ const fetchTokens$6 = async ({
1315
1313
  networkId,
1316
1314
  tokens,
1317
1315
  connector,
@@ -1370,8 +1368,8 @@ const fetchTokens$7 = async ({
1370
1368
  }
1371
1369
  const base = {
1372
1370
  id: tokenId,
1373
- type: MODULE_TYPE$7,
1374
- platform: PLATFORM$7,
1371
+ type: MODULE_TYPE$6,
1372
+ platform: PLATFORM$6,
1375
1373
  networkId
1376
1374
  };
1377
1375
  const cached2 = cache[tokenId] && TokenCacheSchema.safeParse(cache[tokenId]).data;
@@ -1387,17 +1385,17 @@ const fetchTokens$7 = async ({
1387
1385
  return result;
1388
1386
  };
1389
1387
 
1390
- const getMiniMetadata$7 = () => {
1388
+ const getMiniMetadata$6 = () => {
1391
1389
  throw new Error("MiniMetadata is not supported for ethereum tokens");
1392
1390
  };
1393
1391
 
1394
- const getTransferCallData$7 = ({
1392
+ const getTransferCallData$6 = ({
1395
1393
  from,
1396
1394
  to,
1397
1395
  value,
1398
1396
  token
1399
1397
  }) => {
1400
- if (!isTokenOfType(token, MODULE_TYPE$7)) throw new Error(`Token type ${token.type} is not ${MODULE_TYPE$7}.`);
1398
+ if (!isTokenOfType(token, MODULE_TYPE$6)) throw new Error(`Token type ${token.type} is not ${MODULE_TYPE$6}.`);
1401
1399
  if (!isEthereumAddress(from)) throw new Error("Invalid from address");
1402
1400
  if (!isEthereumAddress(to)) throw new Error("Invalid to address");
1403
1401
  const data = encodeFunctionData({
@@ -1412,151 +1410,6 @@ const getTransferCallData$7 = ({
1412
1410
  };
1413
1411
  };
1414
1412
 
1415
- const SUBSCRIPTION_INTERVAL$3 = 6_000;
1416
- const subscribeBalances$7 = ({
1417
- networkId,
1418
- tokensWithAddresses,
1419
- connector
1420
- }) => {
1421
- if (!tokensWithAddresses.length) return of({
1422
- success: [],
1423
- errors: []
1424
- });
1425
- return new Observable(subscriber => {
1426
- const abortController = new AbortController();
1427
- const poll = async () => {
1428
- try {
1429
- if (abortController.signal.aborted) return;
1430
- const balances = await fetchBalances$7({
1431
- networkId,
1432
- tokensWithAddresses: tokensWithAddresses,
1433
- connector
1434
- });
1435
- if (abortController.signal.aborted) return;
1436
- subscriber.next(balances);
1437
- setTimeout(poll, SUBSCRIPTION_INTERVAL$3);
1438
- } catch (error) {
1439
- log.error("Error", {
1440
- module: MODULE_TYPE$7,
1441
- networkId,
1442
- addressesByToken: tokensWithAddresses,
1443
- error
1444
- });
1445
- subscriber.error(error);
1446
- }
1447
- };
1448
- poll();
1449
- return () => {
1450
- abortController.abort();
1451
- };
1452
- }).pipe(distinctUntilChanged(isEqual));
1453
- };
1454
-
1455
- const EvmUniswapV2BalanceModule = {
1456
- type: MODULE_TYPE$7,
1457
- platform: PLATFORM$7,
1458
- getMiniMetadata: getMiniMetadata$7,
1459
- fetchTokens: fetchTokens$7,
1460
- fetchBalances: fetchBalances$7,
1461
- subscribeBalances: subscribeBalances$7,
1462
- getTransferCallData: getTransferCallData$7
1463
- };
1464
-
1465
- // to be used by chaindata too
1466
- const EvmUniswapV2TokenConfigSchema = z.strictObject({
1467
- contractAddress: EvmUniswapV2TokenSchema.shape.contractAddress,
1468
- ...TokenConfigBaseSchema.shape
1469
- });
1470
-
1471
- const MODULE_TYPE$6 = SolNativeTokenSchema.shape.type.value;
1472
- const PLATFORM$6 = SolNativeTokenSchema.shape.platform.value;
1473
-
1474
- const fetchBalances$6 = async ({
1475
- networkId,
1476
- tokensWithAddresses,
1477
- connector
1478
- }) => {
1479
- if (!tokensWithAddresses.length) return {
1480
- success: [],
1481
- errors: []
1482
- };
1483
- const connection = await connector.getConnection(networkId);
1484
- if (!connection) throw new Error(`Could not get rpc provider for sol network ${networkId}`);
1485
- for (const [token, addresses] of tokensWithAddresses) {
1486
- if (token.type !== MODULE_TYPE$6 || token.networkId !== networkId) throw new Error(`Invalid token type or networkId for balance module: ${token.type} on ${token.networkId}`);
1487
- for (const address of addresses) if (!isSolanaAddress(address)) throw new Error(`Invalid solana address for balance module: ${address} for token ${token.id}`);
1488
- }
1489
- const balanceDefs = getBalanceDefs(tokensWithAddresses);
1490
- const results = await Promise.allSettled(balanceDefs.map(async ({
1491
- token,
1492
- address
1493
- }) => {
1494
- try {
1495
- const publicKey = new PublicKey(address);
1496
- const lamports = await connection.getBalance(publicKey);
1497
- return {
1498
- address: address,
1499
- tokenId: token.id,
1500
- value: lamports.toString(),
1501
- source: MODULE_TYPE$6,
1502
- networkId: token.networkId,
1503
- status: "live"
1504
- };
1505
- } catch (err) {
1506
- throw new BalanceFetchError(`Failed to get balance for token ${token.id} and address ${address} on chain ${networkId}`, token.id, address, err);
1507
- }
1508
- }));
1509
- return results.reduce((acc, result) => {
1510
- if (result.status === "fulfilled") acc.success.push(result.value);else {
1511
- const error = result.reason;
1512
- acc.errors.push({
1513
- tokenId: error.tokenId,
1514
- address: error.address,
1515
- error
1516
- });
1517
- }
1518
- return acc;
1519
- }, {
1520
- success: [],
1521
- errors: []
1522
- });
1523
- };
1524
-
1525
- const fetchTokens$6 = async ({
1526
- networkId,
1527
- tokens
1528
- }) => {
1529
- // assume there is one and only one token in the array
1530
- if (tokens.length !== 1) throw new Error("EVM Native module expects the nativeCurrency to be passed as a single token in the array");
1531
- const token = assign({
1532
- id: solNativeTokenId(networkId),
1533
- type: MODULE_TYPE$6,
1534
- platform: PLATFORM$6,
1535
- networkId,
1536
- isDefault: true
1537
- }, tokens[0]);
1538
- const parsed = SolNativeTokenSchema.safeParse(token);
1539
- if (!parsed.success) {
1540
- log.warn("Ignoring token with invalid schema", token);
1541
- return [];
1542
- }
1543
- return [parsed.data];
1544
- };
1545
-
1546
- const getMiniMetadata$6 = () => {
1547
- throw new Error("MiniMetadata is not supported for sol-native tokens");
1548
- };
1549
-
1550
- const getTransferCallData$6 = ({
1551
- // from,
1552
- // to,
1553
- // value,
1554
- token
1555
- }) => {
1556
- if (!isTokenOfType(token, MODULE_TYPE$6)) throw new Error(`Token type ${token.type} is not ${MODULE_TYPE$6}.`);
1557
- throw new Error("Not implemented");
1558
- };
1559
-
1560
1413
  const SUBSCRIPTION_INTERVAL$2 = 6_000;
1561
1414
  const subscribeBalances$6 = ({
1562
1415
  networkId,
@@ -1574,7 +1427,7 @@ const subscribeBalances$6 = ({
1574
1427
  if (abortController.signal.aborted) return;
1575
1428
  const balances = await fetchBalances$6({
1576
1429
  networkId,
1577
- tokensWithAddresses,
1430
+ tokensWithAddresses: tokensWithAddresses,
1578
1431
  connector
1579
1432
  });
1580
1433
  if (abortController.signal.aborted) return;
@@ -1584,7 +1437,7 @@ const subscribeBalances$6 = ({
1584
1437
  log.error("Error", {
1585
1438
  module: MODULE_TYPE$6,
1586
1439
  networkId,
1587
- tokensWithAddresses,
1440
+ addressesByToken: tokensWithAddresses,
1588
1441
  error
1589
1442
  });
1590
1443
  subscriber.error(error);
@@ -1597,7 +1450,7 @@ const subscribeBalances$6 = ({
1597
1450
  }).pipe(distinctUntilChanged(isEqual));
1598
1451
  };
1599
1452
 
1600
- const SolNativeBalanceModule = {
1453
+ const EvmUniswapV2BalanceModule = {
1601
1454
  type: MODULE_TYPE$6,
1602
1455
  platform: PLATFORM$6,
1603
1456
  getMiniMetadata: getMiniMetadata$6,
@@ -1608,7 +1461,8 @@ const SolNativeBalanceModule = {
1608
1461
  };
1609
1462
 
1610
1463
  // to be used by chaindata too
1611
- const SolNativeTokenConfigSchema = z.strictObject({
1464
+ const EvmUniswapV2TokenConfigSchema = z.strictObject({
1465
+ contractAddress: EvmUniswapV2TokenSchema.shape.contractAddress,
1612
1466
  ...TokenConfigBaseSchema.shape
1613
1467
  });
1614
1468
 
@@ -6273,7 +6127,7 @@ const SubTokensMiniMetadataExtraSchema = z.strictObject({
6273
6127
  palletId: z.string()
6274
6128
  });
6275
6129
 
6276
- const BALANCE_MODULES = [SubNativeBalanceModule, SubAssetsBalanceModule, SubHydrationBalanceModule, SubForeignAssetsBalanceModule, SubPsp22BalanceModule, SubTokensBalanceModule, EvmErc20BalanceModule, EvmUniswapV2BalanceModule, EvmNativeBalanceModule, SolNativeBalanceModule];
6130
+ const BALANCE_MODULES = [SubNativeBalanceModule, SubAssetsBalanceModule, SubHydrationBalanceModule, SubForeignAssetsBalanceModule, SubPsp22BalanceModule, SubTokensBalanceModule, EvmErc20BalanceModule, EvmUniswapV2BalanceModule, EvmNativeBalanceModule];
6277
6131
 
6278
6132
  // share requests as all modules will call this at once
6279
6133
  const CACHE$1 = new Map();
@@ -6451,25 +6305,10 @@ class BalancesProvider {
6451
6305
  {
6452
6306
  return this.getEthereumNetworkModuleBalances$(networkId, tokensWithAddresses, mod);
6453
6307
  }
6454
- case "solana":
6455
- {
6456
- return this.getSolanaNetworkModuleBalances$(networkId, tokensWithAddresses, mod);
6457
- }
6458
6308
  case "polkadot":
6459
6309
  {
6460
6310
  return this.getPolkadotNetworkModuleBalances$(networkId, tokensWithAddresses, mod);
6461
6311
  }
6462
- default:
6463
- {
6464
- log.warn("[balances] Unsupported network platform for module", {
6465
- networkId,
6466
- mod
6467
- });
6468
- return of({
6469
- status: "live",
6470
- balances: []
6471
- }); // no solana modules yet
6472
- }
6473
6312
  }
6474
6313
  }));
6475
6314
  }), map(results => {
@@ -6499,7 +6338,7 @@ class BalancesProvider {
6499
6338
  address
6500
6339
  })));
6501
6340
  if (!this.#chainConnectors.substrate) {
6502
- log.warn("[balances] no substrate connector or miniMetadata for module", mod.type);
6341
+ log.debug("[balances] no substrate connector or miniMetadata for module", mod.type);
6503
6342
  return defer(() => of({
6504
6343
  status: "initialising",
6505
6344
  balances: this.getStoredBalances(moduleAddressesByTokenId)
@@ -6550,7 +6389,7 @@ class BalancesProvider {
6550
6389
  address
6551
6390
  })));
6552
6391
  if (!this.#chainConnectors.evm) {
6553
- log.warn("[balances] no ethereum connector for module", mod.type);
6392
+ log.debug("[balances] no ethereum connector for module", mod.type);
6554
6393
  return defer(() => of({
6555
6394
  status: "initialising",
6556
6395
  balances: this.getStoredBalances(moduleAddressesByTokenId)
@@ -6582,56 +6421,6 @@ class BalancesProvider {
6582
6421
  })));
6583
6422
  });
6584
6423
  }
6585
- getSolanaNetworkModuleBalances$(networkId, tokensWithAddresses, mod) {
6586
- return getSharedObservable(`BalancesProvider.getSolanaNetworkModuleBalances$`, {
6587
- networkId,
6588
- mod,
6589
- tokensWithAddresses
6590
- }, () => {
6591
- if (!tokensWithAddresses.length) return of({
6592
- status: "live",
6593
- balances: []
6594
- });
6595
- const moduleAddressesByTokenId = fromPairs(tokensWithAddresses.map(([token, addresses]) => [token.id, addresses]));
6596
-
6597
- // all balance ids expected in result set
6598
- const balanceIds = toPairs(moduleAddressesByTokenId).flatMap(([tokenId, addresses]) => addresses.map(address => getBalanceId({
6599
- tokenId,
6600
- address
6601
- })));
6602
- if (!this.#chainConnectors.solana) {
6603
- log.warn("[balances] no solana connector for module", mod.type);
6604
- return defer(() => of({
6605
- status: "initialising",
6606
- balances: this.getStoredBalances(moduleAddressesByTokenId)
6607
- }));
6608
- }
6609
- const moduleBalances$ = mod.subscribeBalances({
6610
- networkId,
6611
- tokensWithAddresses,
6612
- connector: this.#chainConnectors.solana
6613
- }).pipe(catchError(() => EMPTY),
6614
- // don't emit, let provider mark balances stale
6615
- map(results => ({
6616
- status: "live",
6617
- // exclude zero balances
6618
- balances: results.success.filter(b => new Balance(b).total.planck > 0n)
6619
- })), tap(results => {
6620
- this.updateStorage$(balanceIds, results);
6621
- }),
6622
- // shareReplay + keepAlive(0) keep the subscription alive while root observable is being unsubscribed+resubscribed, in case any input change
6623
- shareReplay({
6624
- refCount: true,
6625
- bufferSize: 1
6626
- }), keepAlive(0));
6627
-
6628
- // defer the startWith call to start with up to date balances each time the observable is re-subscribed to
6629
- return defer(() => moduleBalances$.pipe(startWith({
6630
- status: "initialising",
6631
- balances: this.getStoredBalances(moduleAddressesByTokenId)
6632
- })));
6633
- });
6634
- }
6635
6424
  updateStorage$(balanceIds, balancesResult) {
6636
6425
  if (balancesResult.status !== "live") return;
6637
6426
  const storage = this.#storage.getValue();
@@ -6742,42 +6531,18 @@ class BalancesProvider {
6742
6531
  }));
6743
6532
  }
6744
6533
  }
6745
- const isAccountPlatformCompatibleWithNetwork = (network, platform) => {
6534
+ const isAddressCompatibleWithNetwork = (network, address) => {
6746
6535
  switch (network.platform) {
6747
6536
  case "ethereum":
6748
- return platform === "ethereum";
6749
- case "solana":
6750
- return platform === "solana";
6537
+ return isEthereumAddress(address);
6751
6538
  case "polkadot":
6752
- {
6753
- switch (network.account) {
6754
- case "secp256k1":
6755
- return platform === "ethereum";
6756
- case "*25519":
6757
- return platform === "polkadot";
6758
- default:
6759
- throw new Error(`Unsupported polkadot network account type ${network.account}`);
6760
- }
6761
- }
6539
+ return isEthereumAddress(address) ? network.account === "secp256k1" : network.account !== "secp256k1";
6762
6540
  default:
6763
6541
  log.warn("Unsupported network platform", network);
6764
6542
  throw new Error("Unsupported network platform");
6765
6543
  }
6766
6544
  };
6767
-
6768
- /**
6769
- * If this is the address of an account, use isAccountCompatibleWithChain instead.
6770
- * Otherwise it could lead to a loss of funds
6771
- * @param chain
6772
- * @param address
6773
- * @returns
6774
- */
6775
- const isAddressCompatibleWithNetwork = (network, address) => {
6776
- // TODO try with return true to check if wallet filters correctly upfront
6777
- const accountPlatform = getAccountPlatformFromAddress(address);
6778
- return isAccountPlatformCompatibleWithNetwork(network, accountPlatform);
6779
- };
6780
6545
  const sortByBalanceId = (a, b) => getBalanceId(a).localeCompare(getBalanceId(b));
6781
6546
  const sortByMiniMetadataId = (a, b) => a.id.localeCompare(b.id);
6782
6547
 
6783
- export { BALANCE_MODULES, Balance, BalanceFormatter, BalanceValueGetter, Balances, BalancesProvider, Change24hCurrencyFormatter, EvmErc20BalanceModule, EvmErc20TokenConfigSchema, EvmNativeBalanceModule, EvmNativeTokenConfigSchema, EvmUniswapV2BalanceModule, EvmUniswapV2TokenConfigSchema, FiatSumBalancesFormatter, ONE_ALPHA_TOKEN, PlanckSumBalancesFormatter, SCALE_FACTOR, SUBTENSOR_MIN_STAKE_AMOUNT_PLANK, SUBTENSOR_ROOT_NETUID, SolNativeBalanceModule, SolNativeTokenConfigSchema, SubAssetsBalanceModule, SubAssetsTokenConfigSchema, SubForeignAssetsBalanceModule, SubForeignAssetsTokenConfigSchema, SubHydrationBalanceModule, SubHydrationTokenConfigSchema, SubNativeBalanceModule, SubNativeMiniMetadataExtraSchema, SubNativeModuleConfigSchema, SubNativeTokenConfigSchema, SubPsp22BalanceModule, SubPsp22TokenConfigSchema, SubTokensBalanceModule, SubTokensMiniMetadataExtraSchema, SubTokensModuleConfigSchema, SubTokensTokenConfigSchema, SumBalancesFormatter, abiMulticall, calculateAlphaPrice, calculateTaoAmountFromAlpha, calculateTaoFromDynamicInfo, deriveMiniMetadataId, erc20BalancesAggregatorAbi, excludeFromFeePayableLocks, excludeFromTransferableAmount, filterBaseLocks, filterMirrorTokens, getBalanceId, getLockTitle, getLockedType, getValueId, includeInTotalExtraAmount, uniswapV2PairAbi };
6548
+ export { BALANCE_MODULES, Balance, BalanceFormatter, BalanceValueGetter, Balances, BalancesProvider, Change24hCurrencyFormatter, EvmErc20BalanceModule, EvmErc20TokenConfigSchema, EvmNativeBalanceModule, EvmNativeTokenConfigSchema, EvmUniswapV2BalanceModule, EvmUniswapV2TokenConfigSchema, FiatSumBalancesFormatter, ONE_ALPHA_TOKEN, PlanckSumBalancesFormatter, SCALE_FACTOR, SUBTENSOR_MIN_STAKE_AMOUNT_PLANK, SUBTENSOR_ROOT_NETUID, SubAssetsBalanceModule, SubAssetsTokenConfigSchema, SubForeignAssetsBalanceModule, SubForeignAssetsTokenConfigSchema, SubHydrationBalanceModule, SubHydrationTokenConfigSchema, SubNativeBalanceModule, SubNativeMiniMetadataExtraSchema, SubNativeModuleConfigSchema, SubNativeTokenConfigSchema, SubPsp22BalanceModule, SubPsp22TokenConfigSchema, SubTokensBalanceModule, SubTokensMiniMetadataExtraSchema, SubTokensModuleConfigSchema, SubTokensTokenConfigSchema, SumBalancesFormatter, abiMulticall, calculateAlphaPrice, calculateTaoAmountFromAlpha, calculateTaoFromDynamicInfo, deriveMiniMetadataId, erc20BalancesAggregatorAbi, excludeFromFeePayableLocks, excludeFromTransferableAmount, filterBaseLocks, filterMirrorTokens, getBalanceId, getLockTitle, getLockedType, getValueId, includeInTotalExtraAmount, uniswapV2PairAbi };