@pioneer-platform/pioneer-sdk 4.21.1 → 4.21.2

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.cjs CHANGED
@@ -260,7 +260,7 @@ var require_lib = __commonJS((exports2) => {
260
260
  this.spec = spec;
261
261
  this.queryKey = config.queryKey;
262
262
  this.pioneer = {};
263
- this.timeout = config.queryKey || 45000;
263
+ this.timeout = config.timeout || 45000;
264
264
  }
265
265
  Pioneer2.prototype.init = function() {
266
266
  return __awaiter(this, undefined, undefined, function() {
@@ -665,21 +665,101 @@ function createBalanceIdentifier(caip, pubkey) {
665
665
  return `${caip}:${pubkey}`;
666
666
  }
667
667
 
668
+ // src/charts/custom-tokens.ts
669
+ var tag = "| charts-custom-tokens |";
670
+ async function fetchCustomTokens(params, balances) {
671
+ const { pioneer, pubkeys, blockchains, context } = params;
672
+ console.log(tag, "Fetching custom tokens...");
673
+ const evmPubkey = pubkeys.find((e) => e.networks && Array.isArray(e.networks) && e.networks.includes("eip155:*"));
674
+ const primaryAddress = evmPubkey?.address || evmPubkey?.master;
675
+ if (!primaryAddress) {
676
+ console.log(tag, "No EVM address found, skipping custom tokens");
677
+ return;
678
+ }
679
+ console.log(tag, "Using EVM address for custom tokens:", primaryAddress);
680
+ const supportedNetworks = blockchains.filter((net) => net.startsWith("eip155:"));
681
+ if (supportedNetworks.length === 0) {
682
+ console.log(tag, "No EVM networks for custom tokens");
683
+ return;
684
+ }
685
+ console.log(tag, `Checking custom tokens on ${supportedNetworks.length} networks`);
686
+ for (const networkId of supportedNetworks) {
687
+ try {
688
+ const response = await pioneer.GetCustomTokens({ networkId, address: primaryAddress });
689
+ const customTokens = response?.data?.tokens || [];
690
+ console.log(tag, `Found ${customTokens.length} custom tokens on ${networkId}`);
691
+ for (const token of customTokens) {
692
+ const chartBalance = processCustomToken(token, primaryAddress, context, blockchains);
693
+ if (chartBalance && !checkDuplicateBalance(balances, chartBalance.caip, chartBalance.pubkey)) {
694
+ balances.push(chartBalance);
695
+ console.log(tag, `Added custom token: ${chartBalance.symbol} = ${chartBalance.balance}`);
696
+ }
697
+ }
698
+ } catch (error) {
699
+ console.error(tag, `Error fetching custom tokens for ${networkId}:`, error.message);
700
+ }
701
+ }
702
+ console.log(tag, `Custom tokens complete. Total balances: ${balances.length}`);
703
+ }
704
+ function processCustomToken(token, primaryAddress, context, blockchains) {
705
+ if (!token.assetCaip || !token.networkId) {
706
+ return null;
707
+ }
708
+ let extractedNetworkId = token.networkId;
709
+ if (token.assetCaip.includes("/denom:")) {
710
+ const parts = token.assetCaip.split("/denom:");
711
+ if (parts.length > 0) {
712
+ extractedNetworkId = parts[0];
713
+ }
714
+ } else if (token.networkId && token.networkId.includes("/")) {
715
+ extractedNetworkId = token.networkId.split("/")[0];
716
+ }
717
+ const isEip155 = extractedNetworkId.startsWith("eip155:");
718
+ if (!isEip155 && !blockchains.includes(extractedNetworkId)) {
719
+ return null;
720
+ }
721
+ const tokenAssetInfo = hydrateAssetData(token.assetCaip);
722
+ const tokenPubkey = token.pubkey || primaryAddress;
723
+ const chartBalance = {
724
+ context,
725
+ chart: "pioneer",
726
+ contextType: context.split(":")[0],
727
+ name: tokenAssetInfo?.name || token.token?.name || "Unknown Custom Token",
728
+ caip: token.assetCaip,
729
+ icon: tokenAssetInfo?.icon || token.token?.icon || "",
730
+ pubkey: tokenPubkey,
731
+ ticker: tokenAssetInfo?.symbol || token.token?.symbol || "UNK",
732
+ ref: `${context}${token.assetCaip}`,
733
+ identifier: createBalanceIdentifier(token.assetCaip, tokenPubkey),
734
+ networkId: extractedNetworkId,
735
+ symbol: tokenAssetInfo?.symbol || token.token?.symbol || "UNK",
736
+ type: tokenAssetInfo?.type || "erc20",
737
+ token: true,
738
+ decimal: tokenAssetInfo?.decimal || token.token?.decimal,
739
+ balance: token.token?.balance?.toString() || "0",
740
+ priceUsd: token.token?.price || 0,
741
+ valueUsd: token.token?.balanceUSD || 0,
742
+ updated: new Date().getTime()
743
+ };
744
+ return chartBalance;
745
+ }
746
+
668
747
  // src/charts/evm.ts
669
- var tag = "| charts-evm |";
748
+ var tag2 = "| charts-evm |";
670
749
  async function getEvmCharts(params) {
671
750
  const { blockchains, pioneer, pubkeys, context } = params;
672
751
  const balances = [];
673
752
  const evmPubkey = pubkeys.find((e) => e.networks && Array.isArray(e.networks) && e.networks.includes("eip155:*"));
674
753
  const primaryAddress = evmPubkey?.address || evmPubkey?.master;
675
- console.log(tag, "Total pubkeys available:", pubkeys.length);
676
- console.log(tag, "Blockchains to process:", blockchains);
754
+ console.log(tag2, "Total pubkeys available:", pubkeys.length);
755
+ console.log(tag2, "Blockchains to process:", blockchains);
677
756
  if (!primaryAddress) {
678
- console.log(tag, "No EVM address found, skipping portfolio lookup (Zapper only supports Ethereum)");
757
+ console.log(tag2, "No EVM address found, skipping portfolio lookup (Zapper only supports Ethereum)");
679
758
  return balances;
680
759
  }
681
- console.log(tag, "Using EVM address for portfolio:", primaryAddress);
760
+ console.log(tag2, "Using EVM address for portfolio:", primaryAddress);
682
761
  await fetchStableCoins(pioneer, primaryAddress, blockchains, balances, context);
762
+ await fetchCustomTokens({ blockchains, pioneer, pubkeys, context }, balances);
683
763
  try {
684
764
  let portfolio = await pioneer.GetPortfolio({
685
765
  networkId: "eip155:1",
@@ -687,10 +767,10 @@ async function getEvmCharts(params) {
687
767
  });
688
768
  portfolio = portfolio.data?.data || portfolio.data;
689
769
  if (!portfolio || !portfolio.balances) {
690
- console.error(tag, "No portfolio.balances found:", portfolio);
770
+ console.error(tag2, "No portfolio.balances found:", portfolio);
691
771
  return balances;
692
772
  }
693
- console.log(tag, `Portfolio returned ${portfolio.balances.length} balances`);
773
+ console.log(tag2, `Portfolio returned ${portfolio.balances.length} balances`);
694
774
  let processedCount = 0;
695
775
  let skippedCount = 0;
696
776
  for (const balance of portfolio.balances) {
@@ -704,9 +784,9 @@ async function getEvmCharts(params) {
704
784
  skippedCount++;
705
785
  }
706
786
  }
707
- console.log(tag, `Processed ${processedCount} balances, skipped ${skippedCount}`);
787
+ console.log(tag2, `Processed ${processedCount} balances, skipped ${skippedCount}`);
708
788
  if (portfolio.tokens && portfolio.tokens.length > 0) {
709
- console.log(tag, "Processing portfolio.tokens:", portfolio.tokens.length);
789
+ console.log(tag2, "Processing portfolio.tokens:", portfolio.tokens.length);
710
790
  for (const token of portfolio.tokens) {
711
791
  const processedToken = processPortfolioToken(token, primaryAddress, context, blockchains);
712
792
  if (processedToken && !checkDuplicateBalance(balances, processedToken.caip, processedToken.pubkey)) {
@@ -715,13 +795,13 @@ async function getEvmCharts(params) {
715
795
  }
716
796
  }
717
797
  } catch (e) {
718
- console.error(tag, "Error fetching portfolio:", e);
798
+ console.error(tag2, "Error fetching portfolio:", e);
719
799
  }
720
800
  return balances;
721
801
  }
722
802
  function processPortfolioBalance(balance, primaryAddress, context, blockchains) {
723
803
  if (!balance.caip) {
724
- console.error(tag, "No caip found for:", balance);
804
+ console.error(tag2, "No caip found for:", balance);
725
805
  return null;
726
806
  }
727
807
  const networkId = balance.caip.split("/")[0];
@@ -739,7 +819,7 @@ function processPortfolioBalance(balance, primaryAddress, context, blockchains)
739
819
  const valueNum = parseFloat(balance.valueUsd.toString());
740
820
  if (balanceNum > 0 && valueNum > 0) {
741
821
  calculatedPrice = valueNum / balanceNum;
742
- console.log(tag, `Calculated price from value/balance: ${calculatedPrice} for ${balance.caip}`);
822
+ console.log(tag2, `Calculated price from value/balance: ${calculatedPrice} for ${balance.caip}`);
743
823
  }
744
824
  }
745
825
  const chartBalance = {
@@ -813,70 +893,70 @@ function processPortfolioToken(token, primaryAddress, context, blockchains) {
813
893
  return chartBalance;
814
894
  }
815
895
  async function fetchStableCoins(pioneer, primaryAddress, blockchains, balances, context) {
816
- console.log(tag, "Fetching stable coins for redundancy...");
896
+ console.log(tag2, "Fetching stable coins for redundancy...");
817
897
  const supportedNetworks = ["eip155:1", "eip155:137", "eip155:8453", "eip155:56"];
818
898
  const networksToCheck = blockchains.filter((net) => supportedNetworks.includes(net));
819
899
  if (networksToCheck.length === 0) {
820
- console.log(tag, "No supported networks for stable coins");
900
+ console.log(tag2, "No supported networks for stable coins");
821
901
  return;
822
902
  }
823
- console.log(tag, `Checking stable coins on ${networksToCheck.length} networks`);
903
+ console.log(tag2, `Checking stable coins on ${networksToCheck.length} networks`);
824
904
  for (const networkId of networksToCheck) {
825
905
  try {
826
906
  const response = await pioneer.GetStableCoins({ networkId, address: primaryAddress });
827
907
  const stableCoins = response?.data?.tokens || [];
828
- console.log(tag, `Found ${stableCoins.length} stable coins on ${networkId}`);
908
+ console.log(tag2, `Found ${stableCoins.length} stable coins on ${networkId}`);
829
909
  for (const token of stableCoins) {
830
910
  const chartBalance = processPortfolioToken(token, primaryAddress, context, blockchains);
831
911
  if (chartBalance && !checkDuplicateBalance(balances, chartBalance.caip, chartBalance.pubkey)) {
832
912
  balances.push(chartBalance);
833
- console.log(tag, `Added stable coin: ${chartBalance.symbol} = ${chartBalance.balance}`);
913
+ console.log(tag2, `Added stable coin: ${chartBalance.symbol} = ${chartBalance.balance}`);
834
914
  }
835
915
  }
836
916
  } catch (error) {
837
- console.error(tag, `Error fetching stable coins for ${networkId}:`, error.message);
917
+ console.error(tag2, `Error fetching stable coins for ${networkId}:`, error.message);
838
918
  }
839
919
  }
840
- console.log(tag, `Stable coin redundancy complete. Total balances: ${balances.length}`);
920
+ console.log(tag2, `Stable coin redundancy complete. Total balances: ${balances.length}`);
841
921
  }
842
922
 
843
923
  // src/charts/maya.ts
844
- var tag2 = "| charts-maya |";
924
+ var tag3 = "| charts-maya |";
845
925
  async function getMayaCharts(params, existingBalances) {
846
926
  const { blockchains, pioneer, pubkeys, context } = params;
847
927
  const balances = [];
848
928
  try {
849
929
  const mayaPubkey = pubkeys.find((p) => p.networks && Array.isArray(p.networks) && p.networks.includes("cosmos:mayachain-mainnet-v1"));
850
930
  if (!mayaPubkey || !mayaPubkey.address) {
851
- console.log(tag2, "No MAYA pubkey found, skipping MAYA token fetch");
931
+ console.log(tag3, "No MAYA pubkey found, skipping MAYA token fetch");
852
932
  return balances;
853
933
  }
854
934
  if (!blockchains.includes("cosmos:mayachain-mainnet-v1")) {
855
- console.log(tag2, "MAYA network not in blockchains list, skipping MAYA token fetch");
935
+ console.log(tag3, "MAYA network not in blockchains list, skipping MAYA token fetch");
856
936
  return balances;
857
937
  }
858
938
  const hasMayaToken = existingBalances.some((b) => b.caip === "cosmos:mayachain-mainnet-v1/denom:maya");
859
939
  if (hasMayaToken) {
860
- console.log(tag2, "MAYA token already exists in balances, skipping");
940
+ console.log(tag3, "MAYA token already exists in balances, skipping");
861
941
  return balances;
862
942
  }
863
- console.log(tag2, "MAYA token not found in portfolio, fetching separately...");
864
- console.log(tag2, "MAYA pubkey address:", mayaPubkey.address);
943
+ console.log(tag3, "MAYA token not found in portfolio, fetching separately...");
944
+ console.log(tag3, "MAYA pubkey address:", mayaPubkey.address);
865
945
  const mayaBalanceResponse = await pioneer.GetPortfolioBalances([
866
946
  {
867
947
  caip: "cosmos:mayachain-mainnet-v1/denom:maya",
868
948
  pubkey: mayaPubkey.address
869
949
  }
870
950
  ]);
871
- console.log(tag2, "MAYA balance response:", JSON.stringify(mayaBalanceResponse?.data, null, 2));
951
+ console.log(tag3, "MAYA balance response:", JSON.stringify(mayaBalanceResponse?.data, null, 2));
872
952
  if (!mayaBalanceResponse?.data || mayaBalanceResponse.data.length === 0) {
873
- console.log(tag2, "No MAYA token balance returned from GetPortfolioBalances API");
953
+ console.log(tag3, "No MAYA token balance returned from GetPortfolioBalances API");
874
954
  return balances;
875
955
  }
876
- console.log(tag2, "Found MAYA token balances:", mayaBalanceResponse.data.length);
956
+ console.log(tag3, "Found MAYA token balances:", mayaBalanceResponse.data.length);
877
957
  for (const mayaBalance of mayaBalanceResponse.data) {
878
958
  if (mayaBalance.caip !== "cosmos:mayachain-mainnet-v1/denom:maya") {
879
- console.log(tag2, "Unexpected balance in MAYA response:", mayaBalance);
959
+ console.log(tag3, "Unexpected balance in MAYA response:", mayaBalance);
880
960
  continue;
881
961
  }
882
962
  const mayaAssetInfo = hydrateAssetData(mayaBalance.caip);
@@ -902,28 +982,28 @@ async function getMayaCharts(params, existingBalances) {
902
982
  valueUsd: parseFloat(mayaBalance.valueUsd) || 0,
903
983
  updated: new Date().getTime()
904
984
  };
905
- console.log(tag2, "Adding MAYA token to balances:", mayaTokenBalance);
985
+ console.log(tag3, "Adding MAYA token to balances:", mayaTokenBalance);
906
986
  balances.push(mayaTokenBalance);
907
987
  }
908
988
  } catch (mayaError) {
909
- console.error(tag2, "Error fetching MAYA token balance:", mayaError);
989
+ console.error(tag3, "Error fetching MAYA token balance:", mayaError);
910
990
  }
911
991
  return balances;
912
992
  }
913
993
 
914
994
  // src/charts/cosmos-staking.ts
915
- var tag3 = "| charts-cosmos-staking |";
995
+ var tag4 = "| charts-cosmos-staking |";
916
996
  async function getCosmosStakingCharts(params) {
917
997
  const { blockchains, pioneer, pubkeys, context } = params;
918
998
  const balances = [];
919
999
  try {
920
- console.log(tag3, "Adding Cosmos staking positions to charts...");
1000
+ console.log(tag4, "Adding Cosmos staking positions to charts...");
921
1001
  const cosmosPubkeys = pubkeys.filter((p) => p.networks && Array.isArray(p.networks) && p.networks.some((n) => n.includes("cosmos:cosmoshub") || n.includes("cosmos:osmosis")));
922
1002
  if (cosmosPubkeys.length === 0) {
923
- console.log(tag3, "No cosmos pubkeys found for staking positions");
1003
+ console.log(tag4, "No cosmos pubkeys found for staking positions");
924
1004
  return balances;
925
1005
  }
926
- console.log(tag3, "Found cosmos pubkeys for staking:", cosmosPubkeys.length);
1006
+ console.log(tag4, "Found cosmos pubkeys for staking:", cosmosPubkeys.length);
927
1007
  for (const cosmosPubkey of cosmosPubkeys) {
928
1008
  if (!cosmosPubkey.address) {
929
1009
  continue;
@@ -937,20 +1017,20 @@ async function getCosmosStakingCharts(params) {
937
1017
  }
938
1018
  }
939
1019
  } catch (e) {
940
- console.error(tag3, "Error adding cosmos staking positions:", e);
1020
+ console.error(tag4, "Error adding cosmos staking positions:", e);
941
1021
  }
942
1022
  return balances;
943
1023
  }
944
1024
  async function fetchStakingPositionsForNetwork(networkId, address, context, pioneer, balances) {
945
1025
  try {
946
- console.log(tag3, `Fetching staking positions for ${address} on ${networkId}...`);
1026
+ console.log(tag4, `Fetching staking positions for ${address} on ${networkId}...`);
947
1027
  let network;
948
1028
  if (networkId === "cosmos:cosmoshub-4") {
949
1029
  network = "cosmos";
950
1030
  } else if (networkId === "cosmos:osmosis-1") {
951
1031
  network = "osmosis";
952
1032
  } else {
953
- console.error(tag3, `Unsupported networkId for staking: ${networkId}`);
1033
+ console.error(tag4, `Unsupported networkId for staking: ${networkId}`);
954
1034
  return;
955
1035
  }
956
1036
  const stakingResponse = await pioneer.GetStakingPositions({
@@ -958,15 +1038,15 @@ async function fetchStakingPositionsForNetwork(networkId, address, context, pion
958
1038
  address
959
1039
  });
960
1040
  if (!stakingResponse?.data || !Array.isArray(stakingResponse.data)) {
961
- console.log(tag3, `No staking positions found for ${address} on ${networkId}`);
1041
+ console.log(tag4, `No staking positions found for ${address} on ${networkId}`);
962
1042
  return;
963
1043
  }
964
- console.log(tag3, `Found ${stakingResponse.data.length} staking positions for ${networkId}`);
1044
+ console.log(tag4, `Found ${stakingResponse.data.length} staking positions for ${networkId}`);
965
1045
  for (const position of stakingResponse.data) {
966
1046
  const processedPosition = processStakingPosition(position, address, context, networkId);
967
1047
  if (processedPosition && !checkDuplicateBalance(balances, processedPosition.caip, processedPosition.pubkey, processedPosition.validator)) {
968
1048
  balances.push(processedPosition);
969
- console.log(tag3, `Added ${position.type} position:`, {
1049
+ console.log(tag4, `Added ${position.type} position:`, {
970
1050
  balance: processedPosition.balance,
971
1051
  ticker: processedPosition.ticker,
972
1052
  valueUsd: processedPosition.valueUsd,
@@ -975,7 +1055,7 @@ async function fetchStakingPositionsForNetwork(networkId, address, context, pion
975
1055
  }
976
1056
  }
977
1057
  } catch (stakingError) {
978
- console.error(tag3, `Error fetching staking positions for ${address} on ${networkId}:`, stakingError);
1058
+ console.error(tag4, `Error fetching staking positions for ${address} on ${networkId}:`, stakingError);
979
1059
  }
980
1060
  }
981
1061
  function processStakingPosition(position, address, context, networkId) {
@@ -1010,11 +1090,11 @@ function processStakingPosition(position, address, context, networkId) {
1010
1090
  }
1011
1091
 
1012
1092
  // src/charts/index.ts
1013
- var tag4 = "| getCharts |";
1093
+ var tag5 = "| getCharts |";
1014
1094
  var getCharts = async (blockchains, pioneer, pubkeys, context) => {
1015
1095
  try {
1016
1096
  const balances = [];
1017
- console.log(tag4, "init");
1097
+ console.log(tag5, "init");
1018
1098
  const params = {
1019
1099
  blockchains,
1020
1100
  pioneer,
@@ -1029,7 +1109,7 @@ var getCharts = async (blockchains, pioneer, pubkeys, context) => {
1029
1109
  balances.push(...stakingBalances);
1030
1110
  return balances;
1031
1111
  } catch (error) {
1032
- console.error(tag4, "Error processing charts:", error);
1112
+ console.error(tag5, "Error processing charts:", error);
1033
1113
  throw error;
1034
1114
  }
1035
1115
  };
@@ -1807,7 +1887,7 @@ async function fetchTokenPriceInUsd(pioneer, caip) {
1807
1887
  }
1808
1888
  }
1809
1889
  async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pubkeyContext, isMax, feeLevel = 5) {
1810
- const tag5 = TAG + " | createUnsignedEvmTx | ";
1890
+ const tag6 = TAG + " | createUnsignedEvmTx | ";
1811
1891
  try {
1812
1892
  if (!pioneer)
1813
1893
  throw new Error("Failed to initialize Pioneer");
@@ -1828,11 +1908,11 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1828
1908
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
1829
1909
  }
1830
1910
  const address = pubkeyContext.address || pubkeyContext.pubkey;
1831
- console.log(tag5, "✅ Using FROM address from pubkeyContext:", address, "note:", pubkeyContext.note);
1911
+ console.log(tag6, "✅ Using FROM address from pubkeyContext:", address, "note:", pubkeyContext.note);
1832
1912
  if (!address)
1833
1913
  throw new Error("No address found for the specified network");
1834
1914
  const gasPriceData = await pioneer.GetGasPriceByNetwork({ networkId });
1835
- console.log(tag5, "Gas price data from API:", JSON.stringify(gasPriceData.data));
1915
+ console.log(tag6, "Gas price data from API:", JSON.stringify(gasPriceData.data));
1836
1916
  let gasPrice;
1837
1917
  const defaultGasPrices = {
1838
1918
  1: 30,
@@ -1848,75 +1928,75 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1848
1928
  let selectedGasPrice;
1849
1929
  if (feeLevel <= 2) {
1850
1930
  selectedGasPrice = gasPriceData.data.slow || gasPriceData.data.average || gasPriceData.data.fastest;
1851
- console.log(tag5, "Selecting SLOW gas price from API");
1931
+ console.log(tag6, "Selecting SLOW gas price from API");
1852
1932
  } else if (feeLevel >= 8) {
1853
1933
  selectedGasPrice = gasPriceData.data.fastest || gasPriceData.data.fast || gasPriceData.data.average;
1854
- console.log(tag5, "Selecting FAST gas price from API");
1934
+ console.log(tag6, "Selecting FAST gas price from API");
1855
1935
  } else {
1856
1936
  selectedGasPrice = gasPriceData.data.average || gasPriceData.data.fast || gasPriceData.data.fastest;
1857
- console.log(tag5, "Selecting AVERAGE gas price from API");
1937
+ console.log(tag6, "Selecting AVERAGE gas price from API");
1858
1938
  }
1859
1939
  let gasPriceNum;
1860
1940
  if (selectedGasPrice === undefined || selectedGasPrice === null) {
1861
- console.warn(tag5, "No valid gas price found in API response, using fallback:", fallbackGasGwei, "gwei");
1941
+ console.warn(tag6, "No valid gas price found in API response, using fallback:", fallbackGasGwei, "gwei");
1862
1942
  gasPriceNum = fallbackGasGwei;
1863
1943
  } else {
1864
1944
  gasPriceNum = typeof selectedGasPrice === "string" ? parseFloat(selectedGasPrice) : selectedGasPrice;
1865
1945
  if (isNaN(gasPriceNum) || !isFinite(gasPriceNum)) {
1866
- console.warn(tag5, "Invalid gas price (NaN or Infinite):", selectedGasPrice, "- using fallback:", fallbackGasGwei, "gwei");
1946
+ console.warn(tag6, "Invalid gas price (NaN or Infinite):", selectedGasPrice, "- using fallback:", fallbackGasGwei, "gwei");
1867
1947
  gasPriceNum = fallbackGasGwei;
1868
1948
  }
1869
1949
  }
1870
1950
  gasPrice = BigInt(Math.round(gasPriceNum * 1e9));
1871
1951
  if (gasPrice < MIN_GAS_PRICE_WEI) {
1872
- console.warn(tag5, "Gas price from API too low:", gasPrice.toString(), "wei - using minimum:", MIN_GAS_PRICE_WEI.toString());
1952
+ console.warn(tag6, "Gas price from API too low:", gasPrice.toString(), "wei - using minimum:", MIN_GAS_PRICE_WEI.toString());
1873
1953
  gasPrice = MIN_GAS_PRICE_WEI;
1874
1954
  }
1875
1955
  } else {
1876
1956
  let gasPriceNum;
1877
1957
  if (gasPriceData.data === undefined || gasPriceData.data === null) {
1878
- console.warn(tag5, "Gas price API returned null/undefined, using fallback:", fallbackGasGwei, "gwei");
1958
+ console.warn(tag6, "Gas price API returned null/undefined, using fallback:", fallbackGasGwei, "gwei");
1879
1959
  gasPriceNum = fallbackGasGwei;
1880
1960
  } else {
1881
1961
  gasPriceNum = typeof gasPriceData.data === "string" ? parseFloat(gasPriceData.data) : gasPriceData.data;
1882
1962
  if (isNaN(gasPriceNum) || !isFinite(gasPriceNum)) {
1883
- console.warn(tag5, "Invalid gas price (NaN or Infinite):", gasPriceData.data, "- using fallback:", fallbackGasGwei, "gwei");
1963
+ console.warn(tag6, "Invalid gas price (NaN or Infinite):", gasPriceData.data, "- using fallback:", fallbackGasGwei, "gwei");
1884
1964
  gasPriceNum = fallbackGasGwei;
1885
1965
  }
1886
1966
  }
1887
1967
  const baseGasPrice = BigInt(Math.round(gasPriceNum * 1e9));
1888
1968
  if (feeLevel <= 2) {
1889
1969
  gasPrice = baseGasPrice * BigInt(80) / BigInt(100);
1890
- console.log(tag5, "Using SLOW gas price (80% of base)");
1970
+ console.log(tag6, "Using SLOW gas price (80% of base)");
1891
1971
  } else if (feeLevel >= 8) {
1892
1972
  gasPrice = baseGasPrice * BigInt(150) / BigInt(100);
1893
- console.log(tag5, "Using FAST gas price (150% of base)");
1973
+ console.log(tag6, "Using FAST gas price (150% of base)");
1894
1974
  } else {
1895
1975
  gasPrice = baseGasPrice;
1896
- console.log(tag5, "Using AVERAGE gas price (100% of base)");
1976
+ console.log(tag6, "Using AVERAGE gas price (100% of base)");
1897
1977
  }
1898
1978
  if (gasPrice < MIN_GAS_PRICE_WEI) {
1899
- console.warn(tag5, "Gas price too low:", gasPrice.toString(), "wei - using minimum:", MIN_GAS_PRICE_WEI.toString());
1979
+ console.warn(tag6, "Gas price too low:", gasPrice.toString(), "wei - using minimum:", MIN_GAS_PRICE_WEI.toString());
1900
1980
  gasPrice = MIN_GAS_PRICE_WEI;
1901
1981
  }
1902
1982
  }
1903
- console.log(tag5, "Final gasPrice:", gasPrice.toString(), "wei (", Number(gasPrice) / 1e9, "gwei)");
1983
+ console.log(tag6, "Final gasPrice:", gasPrice.toString(), "wei (", Number(gasPrice) / 1e9, "gwei)");
1904
1984
  let nonce;
1905
1985
  try {
1906
1986
  const nonceData = await pioneer.GetNonceByNetwork({ networkId, address });
1907
1987
  nonce = nonceData.data.nonce;
1908
1988
  if (nonce === undefined || nonce === null) {
1909
- console.log(tag5, "No nonce found for address (likely fresh address), defaulting to 0");
1989
+ console.log(tag6, "No nonce found for address (likely fresh address), defaulting to 0");
1910
1990
  nonce = 0;
1911
1991
  }
1912
1992
  } catch (nonceError) {
1913
- console.log(tag5, "Failed to fetch nonce (likely fresh address):", nonceError.message, "- defaulting to 0");
1993
+ console.log(tag6, "Failed to fetch nonce (likely fresh address):", nonceError.message, "- defaulting to 0");
1914
1994
  nonce = 0;
1915
1995
  }
1916
1996
  const balanceData = await pioneer.GetBalanceAddressByNetwork({ networkId, address });
1917
1997
  const balanceEth = parseFloat(balanceData.data.nativeBalance || balanceData.data.balance || "0");
1918
1998
  const balance = BigInt(Math.round(balanceEth * 1000000000000000000));
1919
- console.log(tag5, "Native ETH balance from API:", balanceData.data.nativeBalance || balanceData.data.balance, "ETH (", balance.toString(), "wei)");
1999
+ console.log(tag6, "Native ETH balance from API:", balanceData.data.nativeBalance || balanceData.data.balance, "ETH (", balance.toString(), "wei)");
1920
2000
  if (balance <= 0n)
1921
2001
  throw new Error("Wallet balance is zero");
1922
2002
  const assetType = classifyCaipEvm(caip);
@@ -1929,7 +2009,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1929
2009
  let gasLimit;
1930
2010
  if (isThorchainOperation) {
1931
2011
  gasLimit = BigInt(120000);
1932
- console.log(tag5, "Using higher gas limit for THORChain swap:", gasLimit.toString());
2012
+ console.log(tag6, "Using higher gas limit for THORChain swap:", gasLimit.toString());
1933
2013
  } else {
1934
2014
  gasLimit = chainId === 1 ? BigInt(21000) : BigInt(25000);
1935
2015
  }
@@ -1945,7 +2025,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1945
2025
  }
1946
2026
  const buffer = BigInt(100);
1947
2027
  amountWei = balance - gasFee - buffer;
1948
- console.log(tag5, "isMax calculation - balance:", balance.toString(), "gasFee:", gasFee.toString(), "buffer:", buffer.toString(), "amountWei:", amountWei.toString());
2028
+ console.log(tag6, "isMax calculation - balance:", balance.toString(), "gasFee:", gasFee.toString(), "buffer:", buffer.toString(), "amountWei:", amountWei.toString());
1949
2029
  } else {
1950
2030
  amountWei = BigInt(Math.round(amount * 1000000000000000000));
1951
2031
  if (amountWei + gasFee > balance) {
@@ -1955,14 +2035,14 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1955
2035
  const isThorchainSwap = memo && (memo.startsWith("=") || memo.startsWith("SWAP") || memo.includes(":"));
1956
2036
  let txData = "0x";
1957
2037
  if (isThorchainSwap) {
1958
- console.log(tag5, "Detected THORChain swap, encoding deposit data for memo:", memo);
2038
+ console.log(tag6, "Detected THORChain swap, encoding deposit data for memo:", memo);
1959
2039
  let fixedMemo = memo;
1960
2040
  if (memo.startsWith("=:b:") || memo.startsWith("=:btc:")) {
1961
2041
  fixedMemo = memo.replace(/^=:(b|btc):/, "=:BTC.BTC:");
1962
- console.log(tag5, "Fixed Bitcoin swap memo from:", memo, "to:", fixedMemo);
2042
+ console.log(tag6, "Fixed Bitcoin swap memo from:", memo, "to:", fixedMemo);
1963
2043
  } else if (memo.startsWith("=:e:") || memo.startsWith("=:eth:")) {
1964
2044
  fixedMemo = memo.replace(/^=:(e|eth):/, "=:ETH.ETH:");
1965
- console.log(tag5, "Fixed Ethereum swap memo from:", memo, "to:", fixedMemo);
2045
+ console.log(tag6, "Fixed Ethereum swap memo from:", memo, "to:", fixedMemo);
1966
2046
  }
1967
2047
  if (fixedMemo.length > 250) {
1968
2048
  throw new Error(`Memo too long for THORChain: ${fixedMemo.length} bytes (max 250)`);
@@ -1978,14 +2058,14 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1978
2058
  if (ethInbound) {
1979
2059
  vaultAddress = ethInbound.address;
1980
2060
  routerAddress = ethInbound.router || to;
1981
- console.log(tag5, "Using THORChain inbound addresses - vault:", vaultAddress, "router:", routerAddress);
2061
+ console.log(tag6, "Using THORChain inbound addresses - vault:", vaultAddress, "router:", routerAddress);
1982
2062
  to = routerAddress;
1983
2063
  } else {
1984
2064
  throw new Error("ETH inbound is halted or not found - cannot proceed with swap");
1985
2065
  }
1986
2066
  }
1987
2067
  } catch (fetchError) {
1988
- console.error(tag5, "Failed to fetch inbound addresses:", fetchError);
2068
+ console.error(tag6, "Failed to fetch inbound addresses:", fetchError);
1989
2069
  throw new Error(`Cannot proceed with THORChain swap - failed to fetch inbound addresses: ${fetchError.message}`);
1990
2070
  }
1991
2071
  if (vaultAddress === "0x0000000000000000000000000000000000000000") {
@@ -2005,7 +2085,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2005
2085
  const paddingLength = (32 - memoBytes.length % 32) % 32;
2006
2086
  const memoPadded = memoHex + "0".repeat(paddingLength * 2);
2007
2087
  txData = "0x" + functionSelector + vaultPadded + assetPadded + amountPadded + stringOffset + expiryPadded + stringLength + memoPadded;
2008
- console.log(tag5, "Encoded THORChain depositWithExpiry data:", {
2088
+ console.log(tag6, "Encoded THORChain depositWithExpiry data:", {
2009
2089
  functionSelector: "0x" + functionSelector,
2010
2090
  vault: vaultAddress,
2011
2091
  asset: assetAddress,
@@ -2015,9 +2095,9 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2015
2095
  stringOffset: "0x" + stringOffset,
2016
2096
  fullData: txData
2017
2097
  });
2018
- console.log(tag5, "Native ETH swap - value will be set to:", amountWei.toString(), "wei");
2098
+ console.log(tag6, "Native ETH swap - value will be set to:", amountWei.toString(), "wei");
2019
2099
  } catch (error) {
2020
- console.error(tag5, "Error encoding THORChain deposit:", error);
2100
+ console.error(tag6, "Error encoding THORChain deposit:", error);
2021
2101
  throw new Error(`Failed to encode THORChain swap: ${error.message}`);
2022
2102
  }
2023
2103
  } else if (memo) {
@@ -2036,19 +2116,19 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2036
2116
  }
2037
2117
  case "erc20": {
2038
2118
  const contractAddress = extractContractAddressFromCaip(caip);
2039
- console.log(tag5, "Fetching token decimals from contract:", contractAddress, "on network:", networkId);
2119
+ console.log(tag6, "Fetching token decimals from contract:", contractAddress, "on network:", networkId);
2040
2120
  let tokenDecimals;
2041
2121
  try {
2042
- console.log(tag5, "Fetching token decimals via pioneer-server API for", contractAddress, "on", networkId);
2122
+ console.log(tag6, "Fetching token decimals via pioneer-server API for", contractAddress, "on", networkId);
2043
2123
  const decimalsResponse = await pioneer.GetTokenDecimals({
2044
2124
  networkId,
2045
2125
  contractAddress
2046
2126
  });
2047
2127
  tokenDecimals = Number(decimalsResponse.data.decimals);
2048
- console.log(tag5, "✅ Fetched decimals from pioneer-server:", tokenDecimals);
2128
+ console.log(tag6, "✅ Fetched decimals from pioneer-server:", tokenDecimals);
2049
2129
  } catch (error) {
2050
- console.error(tag5, "Failed to fetch token decimals from pioneer-server:", error);
2051
- console.warn(tag5, "⚠️ FALLBACK: Using default 18 decimals - THIS MAY BE INCORRECT!");
2130
+ console.error(tag6, "Failed to fetch token decimals from pioneer-server:", error);
2131
+ console.warn(tag6, "⚠️ FALLBACK: Using default 18 decimals - THIS MAY BE INCORRECT!");
2052
2132
  tokenDecimals = 18;
2053
2133
  }
2054
2134
  const tokenMultiplier = 10n ** BigInt(tokenDecimals);
@@ -2069,7 +2149,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2069
2149
  amountWei = tokenBalance;
2070
2150
  } else {
2071
2151
  amountWei = BigInt(Math.round(amount * Number(tokenMultiplier)));
2072
- console.log(tag5, "Token amount calculation:", {
2152
+ console.log(tag6, "Token amount calculation:", {
2073
2153
  inputAmount: amount,
2074
2154
  decimals: tokenDecimals,
2075
2155
  multiplier: tokenMultiplier,
@@ -2105,23 +2185,23 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2105
2185
  }
2106
2186
  if (pubkeyContext.addressNListMaster) {
2107
2187
  unsignedTx.addressNList = pubkeyContext.addressNListMaster;
2108
- console.log(tag5, "✅ Using addressNListMaster from pubkey context:", unsignedTx.addressNList, "for address:", address);
2188
+ console.log(tag6, "✅ Using addressNListMaster from pubkey context:", unsignedTx.addressNList, "for address:", address);
2109
2189
  } else if (pubkeyContext.pathMaster) {
2110
2190
  unsignedTx.addressNList = import_pioneer_coins2.bip32ToAddressNList(pubkeyContext.pathMaster);
2111
- console.log(tag5, "✅ Converted pathMaster to addressNList:", pubkeyContext.pathMaster, "→", unsignedTx.addressNList);
2191
+ console.log(tag6, "✅ Converted pathMaster to addressNList:", pubkeyContext.pathMaster, "→", unsignedTx.addressNList);
2112
2192
  } else if (pubkeyContext.addressNList) {
2113
2193
  unsignedTx.addressNList = pubkeyContext.addressNList;
2114
- console.log(tag5, "✅ Using addressNList from pubkey context:", unsignedTx.addressNList);
2194
+ console.log(tag6, "✅ Using addressNList from pubkey context:", unsignedTx.addressNList);
2115
2195
  } else if (pubkeyContext.path) {
2116
2196
  unsignedTx.addressNList = import_pioneer_coins2.bip32ToAddressNList(pubkeyContext.path);
2117
- console.log(tag5, "⚠️ Using regular path (not master):", pubkeyContext.path, "→", unsignedTx.addressNList);
2197
+ console.log(tag6, "⚠️ Using regular path (not master):", pubkeyContext.path, "→", unsignedTx.addressNList);
2118
2198
  } else {
2119
2199
  unsignedTx.addressNList = [2147483648 + 44, 2147483648 + 60, 2147483648, 0, 0];
2120
- console.warn(tag5, "⚠️ No path info in pubkey context, using default account 0");
2200
+ console.warn(tag6, "⚠️ No path info in pubkey context, using default account 0");
2121
2201
  }
2122
2202
  return unsignedTx;
2123
2203
  } catch (error) {
2124
- console.error(tag5, "Error:", error.message);
2204
+ console.error(tag6, "Error:", error.message);
2125
2205
  throw error;
2126
2206
  }
2127
2207
  }
@@ -2130,7 +2210,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2130
2210
  var import_pioneer_caip2 = require("@pioneer-platform/pioneer-caip");
2131
2211
  var TAG2 = " | createUnsignedUxtoTx | ";
2132
2212
  async function createUnsignedRippleTx(caip, to, amount, memo, pubkeys, pioneer, pubkeyContext, isMax) {
2133
- let tag5 = TAG2 + " | createUnsignedRippleTx | ";
2213
+ let tag6 = TAG2 + " | createUnsignedRippleTx | ";
2134
2214
  try {
2135
2215
  if (!pioneer)
2136
2216
  throw new Error("Failed to init! pioneer");
@@ -2141,7 +2221,7 @@ async function createUnsignedRippleTx(caip, to, amount, memo, pubkeys, pioneer,
2141
2221
  if (!pubkeyContext.networks?.includes(networkId)) {
2142
2222
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
2143
2223
  }
2144
- console.log(tag5, `✅ Using pubkeyContext for network ${networkId}:`, {
2224
+ console.log(tag6, `✅ Using pubkeyContext for network ${networkId}:`, {
2145
2225
  address: pubkeyContext.address
2146
2226
  });
2147
2227
  const fromAddress = pubkeyContext.address || pubkeyContext.pubkey;
@@ -2209,7 +2289,7 @@ async function createUnsignedRippleTx(caip, to, amount, memo, pubkeys, pioneer,
2209
2289
  };
2210
2290
  return unsignedTx;
2211
2291
  } catch (error) {
2212
- console.error(tag5, "Error:", error);
2292
+ console.error(tag6, "Error:", error);
2213
2293
  throw error;
2214
2294
  }
2215
2295
  }
@@ -2349,7 +2429,7 @@ var thorchainDepositTemplate = (params) => ({
2349
2429
  // src/txbuilder/createUnsignedTendermintTx.ts
2350
2430
  var TAG3 = " | createUnsignedTendermintTx | ";
2351
2431
  async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pioneer, pubkeyContext, isMax, to) {
2352
- const tag5 = TAG3 + " | createUnsignedTendermintTx | ";
2432
+ const tag6 = TAG3 + " | createUnsignedTendermintTx | ";
2353
2433
  try {
2354
2434
  if (!pioneer)
2355
2435
  throw new Error("Failed to init! pioneer");
@@ -2360,7 +2440,7 @@ async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pio
2360
2440
  if (!pubkeyContext.networks?.includes(networkId)) {
2361
2441
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
2362
2442
  }
2363
- console.log(tag5, `✅ Using pubkeyContext for network ${networkId}:`, {
2443
+ console.log(tag6, `✅ Using pubkeyContext for network ${networkId}:`, {
2364
2444
  address: pubkeyContext.address,
2365
2445
  addressNList: pubkeyContext.addressNList || pubkeyContext.addressNListMaster
2366
2446
  });
@@ -2383,11 +2463,11 @@ async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pio
2383
2463
  }
2384
2464
  const fromAddress = pubkeyContext.address || pubkeyContext.pubkey;
2385
2465
  let asset = caip.split(":")[1];
2386
- console.log(tag5, `\uD83D\uDD0D Fetching account info for address: ${fromAddress}`);
2466
+ console.log(tag6, `\uD83D\uDD0D Fetching account info for address: ${fromAddress}`);
2387
2467
  const accountInfo = (await pioneer.GetAccountInfo({ network: chain, address: fromAddress })).data;
2388
- console.log(tag5, "\uD83D\uDCCB accountInfo:", JSON.stringify(accountInfo, null, 2));
2468
+ console.log(tag6, "\uD83D\uDCCB accountInfo:", JSON.stringify(accountInfo, null, 2));
2389
2469
  let balanceInfo = await pioneer.GetPubkeyBalance({ asset: chain, pubkey: fromAddress });
2390
- console.log(tag5, `\uD83D\uDCB0 balanceInfo:`, balanceInfo);
2470
+ console.log(tag6, `\uD83D\uDCB0 balanceInfo:`, balanceInfo);
2391
2471
  let account_number, sequence;
2392
2472
  if (accountInfo.account) {
2393
2473
  account_number = accountInfo.account.account_number || "0";
@@ -2398,13 +2478,13 @@ async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pio
2398
2478
  } else {
2399
2479
  throw new Error(`Unexpected account info format for ${networkId}: ${JSON.stringify(accountInfo)}`);
2400
2480
  }
2401
- console.log(tag5, `\uD83D\uDCCA Extracted account_number: ${account_number}, sequence: ${sequence}`);
2481
+ console.log(tag6, `\uD83D\uDCCA Extracted account_number: ${account_number}, sequence: ${sequence}`);
2402
2482
  if (account_number === "0" || account_number === 0) {
2403
- console.log(tag5, `⚠️ WARNING: Account number is 0 from Pioneer API`);
2404
- console.log(tag5, ` This is likely due to stale Pioneer API cache`);
2405
- console.log(tag5, ` The mayachain-network module queries nodes directly but Pioneer API may be cached`);
2406
- console.log(tag5, ` Proceeding with account_number: 0 but transaction will likely fail`);
2407
- console.log(tag5, ` TODO: Fix Pioneer API to use fresh data from mayachain-network module`);
2483
+ console.log(tag6, `⚠️ WARNING: Account number is 0 from Pioneer API`);
2484
+ console.log(tag6, ` This is likely due to stale Pioneer API cache`);
2485
+ console.log(tag6, ` The mayachain-network module queries nodes directly but Pioneer API may be cached`);
2486
+ console.log(tag6, ` Proceeding with account_number: 0 but transaction will likely fail`);
2487
+ console.log(tag6, ` TODO: Fix Pioneer API to use fresh data from mayachain-network module`);
2408
2488
  }
2409
2489
  const fees = {
2410
2490
  "cosmos:thorchain-mainnet-v1": 0.02,
@@ -2559,7 +2639,7 @@ async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pio
2559
2639
  }
2560
2640
  }
2561
2641
  } catch (error) {
2562
- console.error(tag5, "Error:", error);
2642
+ console.error(tag6, "Error:", error);
2563
2643
  throw error;
2564
2644
  }
2565
2645
  }
@@ -2588,7 +2668,7 @@ function getCoinTypeFromNetworkId(networkId) {
2588
2668
  return coinType;
2589
2669
  }
2590
2670
  async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pubkeyContext, isMax, feeLevel = 5, changeScriptType) {
2591
- let tag5 = " | createUnsignedUxtoTx | ";
2671
+ let tag6 = " | createUnsignedUxtoTx | ";
2592
2672
  try {
2593
2673
  if (!pioneer)
2594
2674
  throw Error("Failed to init! pioneer");
@@ -2599,7 +2679,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2599
2679
  if (!pubkeyContext.networks?.includes(networkId)) {
2600
2680
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
2601
2681
  }
2602
- console.log(tag5, `✅ Using pubkeyContext for network ${networkId}:`, {
2682
+ console.log(tag6, `✅ Using pubkeyContext for network ${networkId}:`, {
2603
2683
  address: pubkeyContext.address,
2604
2684
  scriptType: pubkeyContext.scriptType
2605
2685
  });
@@ -2610,15 +2690,15 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2610
2690
  const isSegwit = segwitNetworks.includes(networkId);
2611
2691
  let chain = import_pioneer_caip4.NetworkIdToChain[networkId];
2612
2692
  const coinType = getCoinTypeFromNetworkId(networkId);
2613
- console.log(`${tag5}: Using SLIP-44 coin type ${coinType} for ${chain}`);
2693
+ console.log(`${tag6}: Using SLIP-44 coin type ${coinType} for ${chain}`);
2614
2694
  const utxos = [];
2615
2695
  for (const pubkey of relevantPubkeys) {
2616
2696
  try {
2617
2697
  let utxosResp = await pioneer.ListUnspent({ network: chain, xpub: pubkey.pubkey });
2618
2698
  utxosResp = utxosResp.data;
2619
- console.log(`${tag5}: ListUnspent response for ${pubkey.scriptType}:`, utxosResp?.length || 0, "UTXOs");
2699
+ console.log(`${tag6}: ListUnspent response for ${pubkey.scriptType}:`, utxosResp?.length || 0, "UTXOs");
2620
2700
  if (!utxosResp || !Array.isArray(utxosResp)) {
2621
- console.warn(`${tag5}: Invalid or empty UTXO response for ${pubkey.pubkey}`);
2701
+ console.warn(`${tag6}: Invalid or empty UTXO response for ${pubkey.pubkey}`);
2622
2702
  continue;
2623
2703
  }
2624
2704
  let scriptType = pubkey.scriptType;
@@ -2627,10 +2707,10 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2627
2707
  }
2628
2708
  utxos.push(...utxosResp);
2629
2709
  } catch (error) {
2630
- console.error(`${tag5}: Failed to fetch UTXOs for ${pubkey.pubkey}:`, error);
2710
+ console.error(`${tag6}: Failed to fetch UTXOs for ${pubkey.pubkey}:`, error);
2631
2711
  }
2632
2712
  }
2633
- console.log(`${tag5}: Total UTXOs collected:`, utxos.length);
2713
+ console.log(`${tag6}: Total UTXOs collected:`, utxos.length);
2634
2714
  if (!utxos || utxos.length === 0)
2635
2715
  throw Error("No UTXOs found across all addresses");
2636
2716
  for (const utxo of utxos) {
@@ -2643,14 +2723,14 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2643
2723
  }, {});
2644
2724
  const mostCommonInputType = Object.entries(scriptTypeCount).sort(([, a], [, b2]) => b2 - a)[0]?.[0] || "p2pkh";
2645
2725
  const actualChangeScriptType = changeScriptType || mostCommonInputType || relevantPubkeys[0]?.scriptType || "p2pkh";
2646
- console.log(`${tag5}: Input script types:`, scriptTypeCount);
2647
- console.log(`${tag5}: Using change script type: ${actualChangeScriptType} (matches inputs: ${mostCommonInputType})`);
2726
+ console.log(`${tag6}: Input script types:`, scriptTypeCount);
2727
+ console.log(`${tag6}: Using change script type: ${actualChangeScriptType} (matches inputs: ${mostCommonInputType})`);
2648
2728
  const changeXpubInfo = relevantPubkeys.find((pk) => pk.scriptType === actualChangeScriptType);
2649
2729
  if (!changeXpubInfo) {
2650
2730
  throw new Error(`No ${actualChangeScriptType} xpub available for change address. ` + `Available types: ${relevantPubkeys.map((pk) => pk.scriptType).join(", ")}. ` + `Cannot create change output with mismatched script type.`);
2651
2731
  }
2652
2732
  const changeXpub = changeXpubInfo.pubkey;
2653
- console.log(`${tag5}: Change xpub selected for ${actualChangeScriptType}:`, changeXpub?.substring(0, 10) + "...");
2733
+ console.log(`${tag6}: Change xpub selected for ${actualChangeScriptType}:`, changeXpub?.substring(0, 10) + "...");
2654
2734
  let changeAddressIndex = await pioneer.GetChangeAddress({
2655
2735
  network: chain,
2656
2736
  xpub: changeXpub
@@ -2670,7 +2750,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2670
2750
  break;
2671
2751
  }
2672
2752
  const path = bipPath;
2673
- console.log(`${tag5}: Change address path: ${path} (coin type: ${coinType}, index: ${changeAddressIndex})`);
2753
+ console.log(`${tag6}: Change address path: ${path} (coin type: ${coinType}, index: ${changeAddressIndex})`);
2674
2754
  const changeAddress = {
2675
2755
  path,
2676
2756
  isChange: true,
@@ -2680,7 +2760,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2680
2760
  };
2681
2761
  let feeRateFromNode;
2682
2762
  if (networkId === "bip122:00000000001a91e3dace36e2be3bf030") {
2683
- console.log(`${tag5}: Using hardcoded fees for DOGE (10 sat/byte)`);
2763
+ console.log(`${tag6}: Using hardcoded fees for DOGE (10 sat/byte)`);
2684
2764
  feeRateFromNode = {
2685
2765
  slow: 10,
2686
2766
  average: 10,
@@ -2693,19 +2773,19 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2693
2773
  try {
2694
2774
  let feeResponse;
2695
2775
  if (pioneer.GetFeeRateByNetwork) {
2696
- console.log(`${tag5}: Trying GetFeeRateByNetwork for ${networkId}`);
2776
+ console.log(`${tag6}: Trying GetFeeRateByNetwork for ${networkId}`);
2697
2777
  feeResponse = await pioneer.GetFeeRateByNetwork({ networkId });
2698
2778
  } else {
2699
- console.log(`${tag5}: Using GetFeeRate for ${networkId}`);
2779
+ console.log(`${tag6}: Using GetFeeRate for ${networkId}`);
2700
2780
  feeResponse = await pioneer.GetFeeRate({ networkId });
2701
2781
  }
2702
2782
  feeRateFromNode = feeResponse.data;
2703
- console.log(`${tag5}: Got fee rates from API:`, JSON.stringify(feeRateFromNode, null, 2));
2783
+ console.log(`${tag6}: Got fee rates from API:`, JSON.stringify(feeRateFromNode, null, 2));
2704
2784
  const conversionThreshold = 500;
2705
2785
  const needsConversion = feeRateFromNode.slow && feeRateFromNode.slow > conversionThreshold || feeRateFromNode.average && feeRateFromNode.average > conversionThreshold || feeRateFromNode.fast && feeRateFromNode.fast > conversionThreshold || feeRateFromNode.fastest && feeRateFromNode.fastest > conversionThreshold;
2706
2786
  if (needsConversion) {
2707
- console.warn(`${tag5}: Detected wrong units - values appear to be in sat/kB instead of sat/byte`);
2708
- console.warn(`${tag5}: Original values:`, {
2787
+ console.warn(`${tag6}: Detected wrong units - values appear to be in sat/kB instead of sat/byte`);
2788
+ console.warn(`${tag6}: Original values:`, {
2709
2789
  slow: feeRateFromNode.slow,
2710
2790
  average: feeRateFromNode.average,
2711
2791
  fast: feeRateFromNode.fast,
@@ -2719,12 +2799,12 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2719
2799
  feeRateFromNode.fast = feeRateFromNode.fast / 1000;
2720
2800
  if (feeRateFromNode.fastest)
2721
2801
  feeRateFromNode.fastest = feeRateFromNode.fastest / 1000;
2722
- console.warn(`${tag5}: Converted to sat/byte:`, feeRateFromNode);
2802
+ console.warn(`${tag6}: Converted to sat/byte:`, feeRateFromNode);
2723
2803
  }
2724
2804
  if (!feeRateFromNode || typeof feeRateFromNode !== "object") {
2725
2805
  throw new Error(`Invalid fee rate response from API: ${JSON.stringify(feeRateFromNode)}`);
2726
2806
  }
2727
- console.log(`${tag5}: Available fee rates:`, {
2807
+ console.log(`${tag6}: Available fee rates:`, {
2728
2808
  slow: feeRateFromNode.slow,
2729
2809
  average: feeRateFromNode.average,
2730
2810
  fast: feeRateFromNode.fast,
@@ -2734,33 +2814,33 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2734
2814
  throw new Error(`No valid fee rates in API response: ${JSON.stringify(feeRateFromNode)}`);
2735
2815
  }
2736
2816
  } catch (error) {
2737
- console.error(`${tag5}: Failed to get fee rates from Pioneer API:`, error.message || error);
2817
+ console.error(`${tag6}: Failed to get fee rates from Pioneer API:`, error.message || error);
2738
2818
  throw new Error(`Unable to get fee rate for network ${networkId}: ${error.message || "API unavailable"}`);
2739
2819
  }
2740
2820
  }
2741
2821
  let effectiveFeeRate;
2742
- console.log(`${tag5}: Using fee level ${feeLevel}`);
2822
+ console.log(`${tag6}: Using fee level ${feeLevel}`);
2743
2823
  switch (feeLevel) {
2744
2824
  case 1:
2745
2825
  case 2:
2746
2826
  effectiveFeeRate = feeRateFromNode.slow || feeRateFromNode.average;
2747
- console.log(`${tag5}: Using SLOW fee rate: ${effectiveFeeRate} sat/vB`);
2827
+ console.log(`${tag6}: Using SLOW fee rate: ${effectiveFeeRate} sat/vB`);
2748
2828
  break;
2749
2829
  case 3:
2750
2830
  case 4:
2751
2831
  effectiveFeeRate = feeRateFromNode.average || feeRateFromNode.fast;
2752
- console.log(`${tag5}: Using AVERAGE fee rate: ${effectiveFeeRate} sat/vB`);
2832
+ console.log(`${tag6}: Using AVERAGE fee rate: ${effectiveFeeRate} sat/vB`);
2753
2833
  break;
2754
2834
  case 5:
2755
2835
  effectiveFeeRate = feeRateFromNode.fastest || feeRateFromNode.fast;
2756
- console.log(`${tag5}: Using FASTEST fee rate: ${effectiveFeeRate} sat/vB`);
2836
+ console.log(`${tag6}: Using FASTEST fee rate: ${effectiveFeeRate} sat/vB`);
2757
2837
  break;
2758
2838
  default:
2759
2839
  throw new Error(`Invalid fee level: ${feeLevel}. Must be 1-5`);
2760
2840
  }
2761
2841
  if (!effectiveFeeRate)
2762
2842
  throw new Error("Unable to get fee rate for network");
2763
- console.log(`${tag5}: Using fee rate from API:`, {
2843
+ console.log(`${tag6}: Using fee rate from API:`, {
2764
2844
  feeLevel,
2765
2845
  selectedRate: effectiveFeeRate,
2766
2846
  description: feeLevel <= 2 ? "slow" : feeLevel <= 4 ? "average" : "fast"
@@ -2770,22 +2850,22 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2770
2850
  effectiveFeeRate = Math.ceil(effectiveFeeRate);
2771
2851
  const MIN_RELAY_FEE_RATE = 3;
2772
2852
  if (effectiveFeeRate < MIN_RELAY_FEE_RATE) {
2773
- console.log(`${tag5}: Fee rate ${effectiveFeeRate} is below minimum relay fee, increasing to ${MIN_RELAY_FEE_RATE} sat/vB`);
2853
+ console.log(`${tag6}: Fee rate ${effectiveFeeRate} is below minimum relay fee, increasing to ${MIN_RELAY_FEE_RATE} sat/vB`);
2774
2854
  effectiveFeeRate = MIN_RELAY_FEE_RATE;
2775
2855
  }
2776
- console.log(`${tag5}: Final fee rate to use (rounded, with minimums): ${effectiveFeeRate} sat/vB`);
2856
+ console.log(`${tag6}: Final fee rate to use (rounded, with minimums): ${effectiveFeeRate} sat/vB`);
2777
2857
  amount = parseInt(String(amount * 1e8));
2778
2858
  if (amount <= 0 && !isMax)
2779
2859
  throw Error("Invalid amount! 0");
2780
2860
  const totalBalance = utxos.reduce((sum, utxo) => sum + utxo.value, 0);
2781
- console.log(`${tag5}: Coin selection inputs:`, {
2861
+ console.log(`${tag6}: Coin selection inputs:`, {
2782
2862
  utxoCount: utxos.length,
2783
2863
  totalBalance: totalBalance / 1e8,
2784
2864
  requestedAmount: amount / 1e8,
2785
2865
  isMax,
2786
2866
  feeRate: effectiveFeeRate
2787
2867
  });
2788
- console.log(`${tag5}: UTXO details for coin selection:`, utxos.map((u) => ({
2868
+ console.log(`${tag6}: UTXO details for coin selection:`, utxos.map((u) => ({
2789
2869
  value: u.value,
2790
2870
  txid: u.txid?.substring(0, 10) + "...",
2791
2871
  vout: u.vout,
@@ -2799,8 +2879,8 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2799
2879
  } else {
2800
2880
  result = import_coinselect.default(utxos, [{ address: to, value: amount }], effectiveFeeRate);
2801
2881
  }
2802
- console.log(tag5, "coinSelect result object:", result);
2803
- console.log(tag5, "coinSelect result.inputs:", result?.inputs);
2882
+ console.log(tag6, "coinSelect result object:", result);
2883
+ console.log(tag6, "coinSelect result.inputs:", result?.inputs);
2804
2884
  if (!result || !result.inputs) {
2805
2885
  const errorDetails = {
2806
2886
  utxoCount: utxos.length,
@@ -2809,7 +2889,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2809
2889
  feeRate: effectiveFeeRate,
2810
2890
  insufficientFunds: totalBalance < amount
2811
2891
  };
2812
- console.error(`${tag5}: Coin selection failed:`, errorDetails);
2892
+ console.error(`${tag6}: Coin selection failed:`, errorDetails);
2813
2893
  if (utxos.length === 0) {
2814
2894
  throw Error("No UTXOs available for coin selection");
2815
2895
  } else if (totalBalance < amount) {
@@ -2825,7 +2905,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2825
2905
  throw Error("Failed to create transaction: Missing outputs");
2826
2906
  if (fee === undefined)
2827
2907
  throw Error("Failed to calculate transaction fee");
2828
- console.log(`${tag5}: Transaction built with:`, {
2908
+ console.log(`${tag6}: Transaction built with:`, {
2829
2909
  feeLevel,
2830
2910
  effectiveFeeRate: `${effectiveFeeRate} sat/vB`,
2831
2911
  calculatedFee: `${fee} satoshis`,
@@ -2833,8 +2913,8 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2833
2913
  outputCount: outputs.length
2834
2914
  });
2835
2915
  const uniqueInputSet = new Set;
2836
- console.log(tag5, "inputs:", inputs);
2837
- console.log(tag5, "inputs:", inputs[0]);
2916
+ console.log(tag6, "inputs:", inputs);
2917
+ console.log(tag6, "inputs:", inputs[0]);
2838
2918
  const preparedInputs = inputs.map(transformInput).filter(({ hash, index }) => uniqueInputSet.has(`${hash}:${index}`) ? false : uniqueInputSet.add(`${hash}:${index}`)).map(({ value, index, hash, txHex, path: path2, scriptType }) => ({
2839
2919
  addressNList: import_pioneer_coins3.bip32ToAddressNList(path2),
2840
2920
  scriptType,
@@ -2942,7 +3022,7 @@ class TransactionManager {
2942
3022
  throw new Error(`Unsupported CAIP: ${caip}`);
2943
3023
  }
2944
3024
  async transfer({ caip, to, amount, memo, isMax = false, feeLevel = 5, changeScriptType }) {
2945
- let tag5 = TAG4 + " | transfer | ";
3025
+ let tag6 = TAG4 + " | transfer | ";
2946
3026
  try {
2947
3027
  if (!this.pioneer)
2948
3028
  throw Error("Failed to init! pioneer");
@@ -2980,12 +3060,12 @@ class TransactionManager {
2980
3060
  }
2981
3061
  return unsignedTx;
2982
3062
  } catch (e) {
2983
- console.error(tag5, e);
3063
+ console.error(tag6, e);
2984
3064
  throw e;
2985
3065
  }
2986
3066
  }
2987
3067
  async sign({ caip, unsignedTx }) {
2988
- let tag5 = TAG4 + " | sign | ";
3068
+ let tag6 = TAG4 + " | sign | ";
2989
3069
  try {
2990
3070
  if (!this.pioneer)
2991
3071
  throw Error("Failed to init! pioneer");
@@ -3071,20 +3151,20 @@ class TransactionManager {
3071
3151
  }
3072
3152
  case "cosmos:mayachain-mainnet-v1/slip44:931":
3073
3153
  case "cosmos:mayachain-mainnet-v1/denom:maya": {
3074
- console.log(tag5, "\uD83D\uDD0D ===== MAYACHAIN SIGNING AUDIT =====");
3075
- console.log(tag5, "\uD83D\uDCCB unsignedTx:", JSON.stringify(unsignedTx, null, 2));
3076
- console.log(tag5, "\uD83D\uDD11 unsignedTx.addressNList:", unsignedTx.addressNList);
3077
- console.log(tag5, "\uD83D\uDCCD unsignedTx.signerAddress:", unsignedTx.signerAddress);
3078
- console.log(tag5, "\uD83C\uDF10 pubkeyContext:", this.pubkeyContext);
3079
- console.log(tag5, "\uD83D\uDD10 pubkeyContext.addressNList:", this.pubkeyContext?.addressNList);
3080
- console.log(tag5, "\uD83D\uDD10 pubkeyContext.addressNListMaster:", this.pubkeyContext?.addressNListMaster);
3081
- console.log(tag5, "\uD83D\uDCEC pubkeyContext.address:", this.pubkeyContext?.address);
3082
- console.log(tag5, "=======================================");
3154
+ console.log(tag6, "\uD83D\uDD0D ===== MAYACHAIN SIGNING AUDIT =====");
3155
+ console.log(tag6, "\uD83D\uDCCB unsignedTx:", JSON.stringify(unsignedTx, null, 2));
3156
+ console.log(tag6, "\uD83D\uDD11 unsignedTx.addressNList:", unsignedTx.addressNList);
3157
+ console.log(tag6, "\uD83D\uDCCD unsignedTx.signerAddress:", unsignedTx.signerAddress);
3158
+ console.log(tag6, "\uD83C\uDF10 pubkeyContext:", this.pubkeyContext);
3159
+ console.log(tag6, "\uD83D\uDD10 pubkeyContext.addressNList:", this.pubkeyContext?.addressNList);
3160
+ console.log(tag6, "\uD83D\uDD10 pubkeyContext.addressNListMaster:", this.pubkeyContext?.addressNListMaster);
3161
+ console.log(tag6, "\uD83D\uDCEC pubkeyContext.address:", this.pubkeyContext?.address);
3162
+ console.log(tag6, "=======================================");
3083
3163
  if (unsignedTx.signDoc.msgs[0].type === "mayachain/MsgSend") {
3084
3164
  const responseSign = await this.keepKeySdk.mayachain.mayachainSignAminoTransfer(unsignedTx);
3085
3165
  signedTx = responseSign.serialized;
3086
- console.log(tag5, "✅ Signing completed");
3087
- console.log(tag5, "\uD83D\uDCE6 responseSign:", responseSign);
3166
+ console.log(tag6, "✅ Signing completed");
3167
+ console.log(tag6, "\uD83D\uDCE6 responseSign:", responseSign);
3088
3168
  } else if (unsignedTx.signDoc.msgs[0].type === "mayachain/MsgDeposit") {
3089
3169
  const responseSign = await this.keepKeySdk.mayachain.mayachainSignAminoDeposit(unsignedTx);
3090
3170
  signedTx = responseSign.serialized;
@@ -3106,11 +3186,11 @@ class TransactionManager {
3106
3186
  if (serialized.length > 140) {
3107
3187
  signedTx = serialized;
3108
3188
  } else {
3109
- console.error(tag5, "EIP155 signing returned incomplete transaction - only signature components");
3189
+ console.error(tag6, "EIP155 signing returned incomplete transaction - only signature components");
3110
3190
  throw new Error("KeepKey returned incomplete transaction - cannot reconstruct without r,s,v components");
3111
3191
  }
3112
3192
  } else {
3113
- console.error(tag5, "EIP155 signing failed - no valid signature in response:", responseSign);
3193
+ console.error(tag6, "EIP155 signing failed - no valid signature in response:", responseSign);
3114
3194
  throw new Error("Failed to sign transaction - no valid signature in response");
3115
3195
  }
3116
3196
  break;
@@ -3131,19 +3211,19 @@ class TransactionManager {
3131
3211
  }
3132
3212
  }
3133
3213
  if (!signedTx) {
3134
- console.error(tag5, "CRITICAL ERROR: signedTx is missing after signing process");
3135
- console.error(tag5, "CAIP:", caip);
3136
- console.error(tag5, "Type:", type);
3214
+ console.error(tag6, "CRITICAL ERROR: signedTx is missing after signing process");
3215
+ console.error(tag6, "CAIP:", caip);
3216
+ console.error(tag6, "Type:", type);
3137
3217
  throw Error("Failed to sign! missing signedTx");
3138
3218
  }
3139
3219
  return signedTx;
3140
3220
  } catch (e) {
3141
- console.error(tag5, e);
3221
+ console.error(tag6, e);
3142
3222
  throw e;
3143
3223
  }
3144
3224
  }
3145
3225
  async broadcast({ networkId, serialized }) {
3146
- let tag5 = TAG4 + " | broadcast | ";
3226
+ let tag6 = TAG4 + " | broadcast | ";
3147
3227
  try {
3148
3228
  if (!this.pioneer)
3149
3229
  throw Error("Failed to init! pioneer");
@@ -3157,7 +3237,7 @@ class TransactionManager {
3157
3237
  return result.txid;
3158
3238
  }
3159
3239
  } catch (e) {
3160
- console.error(tag5, e);
3240
+ console.error(tag6, e);
3161
3241
  throw e;
3162
3242
  }
3163
3243
  }
@@ -3277,7 +3357,7 @@ var cosmosClaimAllRewardsTemplate = (params) => ({
3277
3357
  // src/txbuilder/createUnsignedStakingTx.ts
3278
3358
  var TAG5 = " | createUnsignedStakingTx | ";
3279
3359
  async function createUnsignedStakingTx(caip, params, pubkeys, pioneer, pubkeyContext) {
3280
- const tag5 = TAG5 + " | createUnsignedStakingTx | ";
3360
+ const tag6 = TAG5 + " | createUnsignedStakingTx | ";
3281
3361
  try {
3282
3362
  if (!pioneer)
3283
3363
  throw new Error("Failed to init! pioneer");
@@ -3288,7 +3368,7 @@ async function createUnsignedStakingTx(caip, params, pubkeys, pioneer, pubkeyCon
3288
3368
  if (!pubkeyContext.networks?.includes(networkId)) {
3289
3369
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
3290
3370
  }
3291
- console.log(tag5, `✅ Using pubkeyContext for network ${networkId}:`, {
3371
+ console.log(tag6, `✅ Using pubkeyContext for network ${networkId}:`, {
3292
3372
  address: pubkeyContext.address
3293
3373
  });
3294
3374
  let chain;
@@ -3320,10 +3400,10 @@ async function createUnsignedStakingTx(caip, params, pubkeys, pioneer, pubkeyCon
3320
3400
  default:
3321
3401
  throw new Error(`Unsupported networkId for staking: ${networkId}`);
3322
3402
  }
3323
- console.log(tag5, `Building ${params.type} transaction for ${chain}`);
3403
+ console.log(tag6, `Building ${params.type} transaction for ${chain}`);
3324
3404
  const fromAddress = pubkeyContext.address || pubkeyContext.pubkey;
3325
3405
  const accountInfo = (await pioneer.GetAccountInfo({ network: chain, address: fromAddress })).data;
3326
- console.log(tag5, "accountInfo: ", accountInfo);
3406
+ console.log(tag6, "accountInfo: ", accountInfo);
3327
3407
  let account_number;
3328
3408
  let sequence;
3329
3409
  if (networkId === "cosmos:cosmoshub-4" || networkId === "cosmos:osmosis-1") {
@@ -3405,7 +3485,7 @@ async function createUnsignedStakingTx(caip, params, pubkeys, pioneer, pubkeyCon
3405
3485
  throw new Error(`Unsupported staking transaction type: ${params.type}`);
3406
3486
  }
3407
3487
  } catch (error) {
3408
- console.error(tag5, "Error:", error);
3488
+ console.error(tag6, "Error:", error);
3409
3489
  throw error;
3410
3490
  }
3411
3491
  }
@@ -3451,16 +3531,16 @@ function withTimeout(promise, timeoutMs) {
3451
3531
  ]);
3452
3532
  }
3453
3533
  async function getFees(pioneer, networkId) {
3454
- const tag5 = TAG6 + " | getFees | ";
3534
+ const tag6 = TAG6 + " | getFees | ";
3455
3535
  try {
3456
- console.log(tag5, `Fetching fees for network: ${networkId}`);
3536
+ console.log(tag6, `Fetching fees for network: ${networkId}`);
3457
3537
  const networkType = getNetworkType(networkId);
3458
3538
  if (networkType === "COSMOS") {
3459
- console.log(tag5, "Using hardcoded fees for Cosmos network:", networkId);
3539
+ console.log(tag6, "Using hardcoded fees for Cosmos network:", networkId);
3460
3540
  return getCosmosFees(networkId);
3461
3541
  }
3462
3542
  if (networkId === "bip122:00000000001a91e3dace36e2be3bf030") {
3463
- console.log(tag5, "Using hardcoded fees for Dogecoin: 10 sat/byte");
3543
+ console.log(tag6, "Using hardcoded fees for Dogecoin: 10 sat/byte");
3464
3544
  return {
3465
3545
  slow: {
3466
3546
  label: "Slow",
@@ -3497,7 +3577,7 @@ async function getFees(pioneer, networkId) {
3497
3577
  const apiCall = pioneer.GetFeeRateByNetwork ? pioneer.GetFeeRateByNetwork({ networkId }) : pioneer.GetFeeRate({ networkId });
3498
3578
  feeResponse = await withTimeout(apiCall, 3000);
3499
3579
  } catch (timeoutError) {
3500
- console.warn(tag5, "Dash fee API timeout, using fallback fees");
3580
+ console.warn(tag6, "Dash fee API timeout, using fallback fees");
3501
3581
  return {
3502
3582
  slow: {
3503
3583
  label: "Economy",
@@ -3535,17 +3615,17 @@ async function getFees(pioneer, networkId) {
3535
3615
  throw new Error(`No fee data returned for ${networkId}`);
3536
3616
  }
3537
3617
  const feeData = feeResponse.data;
3538
- console.log(tag5, "Raw fee data:", feeData);
3618
+ console.log(tag6, "Raw fee data:", feeData);
3539
3619
  const networkName = getNetworkName(networkId);
3540
3620
  let normalizedFees = normalizeFeeData(feeData, networkType, networkName, networkId);
3541
3621
  normalizedFees = ensureFeeDifferentiation(normalizedFees, networkType);
3542
3622
  normalizedFees.networkId = networkId;
3543
3623
  normalizedFees.networkType = networkType;
3544
3624
  normalizedFees.raw = feeData;
3545
- console.log(tag5, "Normalized fees:", normalizedFees);
3625
+ console.log(tag6, "Normalized fees:", normalizedFees);
3546
3626
  return normalizedFees;
3547
3627
  } catch (error) {
3548
- console.error(tag5, "Failed to fetch fees:", error);
3628
+ console.error(tag6, "Failed to fetch fees:", error);
3549
3629
  return getFallbackFees(networkId);
3550
3630
  }
3551
3631
  }
@@ -3854,7 +3934,7 @@ function estimateTransactionFee(feeRate, unit, networkType, txSize) {
3854
3934
 
3855
3935
  // src/utils/kkapi-detection.ts
3856
3936
  async function detectKkApiAvailability(forceLocalhost) {
3857
- const tag5 = " | detectKkApiAvailability | ";
3937
+ const tag6 = " | detectKkApiAvailability | ";
3858
3938
  try {
3859
3939
  const isTauri = typeof window !== "undefined" && "__TAURI__" in window;
3860
3940
  const isBrowser = typeof window !== "undefined";
@@ -3982,6 +4062,11 @@ function buildDashboardFromBalances(balances, blockchains, assetsMap) {
3982
4062
  return sum + balanceNum;
3983
4063
  }, 0).toString();
3984
4064
  const assetInfo = nativeAssetCaip ? assetsMap.get(nativeAssetCaip) : null;
4065
+ console.log(TAG7, `[DEBUG] Network: ${blockchain}`);
4066
+ console.log(TAG7, `[DEBUG] nativeAssetCaip: ${nativeAssetCaip}`);
4067
+ console.log(TAG7, `[DEBUG] assetInfo:`, assetInfo);
4068
+ console.log(TAG7, `[DEBUG] gasAsset:`, gasAsset);
4069
+ console.log(TAG7, `[DEBUG] Resolved name: ${gasAsset?.name || assetInfo?.name || "NO NAME"}`);
3985
4070
  networksTemp.push({
3986
4071
  networkId: blockchain,
3987
4072
  totalValueUsd: networkTotal,
@@ -4007,11 +4092,11 @@ function buildDashboardFromBalances(balances, blockchains, assetsMap) {
4007
4092
  // src/utils/sync-market.ts
4008
4093
  var TAG8 = " | sync-market | ";
4009
4094
  async function syncMarket(balances, pioneer) {
4010
- const tag5 = `${TAG8} | syncMarket | `;
4095
+ const tag6 = `${TAG8} | syncMarket | `;
4011
4096
  try {
4012
4097
  const invalidBalances = balances.filter((b2) => !b2 || !b2.caip || typeof b2.caip !== "string" || !b2.caip.includes(":"));
4013
4098
  if (invalidBalances.length > 0) {
4014
- console.warn(tag5, `Found ${invalidBalances.length} balances with invalid CAIPs:`, invalidBalances.map((b2) => ({
4099
+ console.warn(tag6, `Found ${invalidBalances.length} balances with invalid CAIPs:`, invalidBalances.map((b2) => ({
4015
4100
  caip: b2?.caip,
4016
4101
  type: typeof b2?.caip,
4017
4102
  symbol: b2?.symbol,
@@ -4026,7 +4111,7 @@ async function syncMarket(balances, pioneer) {
4026
4111
  console.log("GetMarketInfo: payload length: ", allCaips.length);
4027
4112
  const invalidEntries = allCaips.filter((caip) => typeof caip !== "string");
4028
4113
  if (invalidEntries.length > 0) {
4029
- console.error(tag5, "CRITICAL: Invalid entries detected in allCaips:", invalidEntries);
4114
+ console.error(tag6, "CRITICAL: Invalid entries detected in allCaips:", invalidEntries);
4030
4115
  throw new Error("Invalid CAIP entries detected - aborting market sync");
4031
4116
  }
4032
4117
  if (allCaips && allCaips.length > 0) {
@@ -4047,13 +4132,13 @@ async function syncMarket(balances, pioneer) {
4047
4132
  }
4048
4133
  }
4049
4134
  } catch (apiError) {
4050
- console.error(tag5, "API error fetching market info:", apiError);
4051
- console.warn(tag5, "Continuing without market prices");
4135
+ console.error(tag6, "API error fetching market info:", apiError);
4136
+ console.warn(tag6, "Continuing without market prices");
4052
4137
  }
4053
4138
  }
4054
4139
  return true;
4055
4140
  } catch (e) {
4056
- console.error(tag5, "e:", e);
4141
+ console.error(tag6, "e:", e);
4057
4142
  throw e;
4058
4143
  }
4059
4144
  }
@@ -4223,7 +4308,7 @@ class SDK {
4223
4308
  return true;
4224
4309
  };
4225
4310
  this.setPubkeys = (newPubkeys) => {
4226
- const tag5 = `${TAG9} | setPubkeys | `;
4311
+ const tag6 = `${TAG9} | setPubkeys | `;
4227
4312
  this.pubkeys = [];
4228
4313
  this.pubkeySet.clear();
4229
4314
  let added = 0;
@@ -4234,7 +4319,7 @@ class SDK {
4234
4319
  }
4235
4320
  };
4236
4321
  this.getUnifiedPortfolio = async function() {
4237
- const tag5 = `${TAG9} | getUnifiedPortfolio | `;
4322
+ const tag6 = `${TAG9} | getUnifiedPortfolio | `;
4238
4323
  try {
4239
4324
  const startTime = performance.now();
4240
4325
  try {
@@ -4245,17 +4330,17 @@ class SDK {
4245
4330
  signal: AbortSignal.timeout(2000)
4246
4331
  });
4247
4332
  if (!portfolioResponse.ok) {
4248
- console.warn(tag5, "Portfolio endpoint returned", portfolioResponse.status);
4333
+ console.warn(tag6, "Portfolio endpoint returned", portfolioResponse.status);
4249
4334
  return null;
4250
4335
  }
4251
4336
  const portfolioData = await portfolioResponse.json();
4252
4337
  const loadTime = performance.now() - startTime;
4253
4338
  if (!portfolioData.success) {
4254
- console.warn(tag5, "Portfolio API returned success=false");
4339
+ console.warn(tag6, "Portfolio API returned success=false");
4255
4340
  return null;
4256
4341
  }
4257
4342
  if (portfolioData.totalValueUsd === 0 || !portfolioData.totalValueUsd) {
4258
- console.warn(tag5, "Portfolio value is $0.00 - may need device connection or sync");
4343
+ console.warn(tag6, "Portfolio value is $0.00 - may need device connection or sync");
4259
4344
  return null;
4260
4345
  }
4261
4346
  let allBalances = [];
@@ -4330,19 +4415,19 @@ class SDK {
4330
4415
  };
4331
4416
  } catch (fetchError) {
4332
4417
  if (fetchError.name === "AbortError") {
4333
- console.log(tag5, "Unified portfolio request timed out (this is normal if vault not running)");
4418
+ console.log(tag6, "Unified portfolio request timed out (this is normal if vault not running)");
4334
4419
  } else {
4335
- console.log(tag5, "Failed to fetch unified portfolio:", fetchError.message);
4420
+ console.log(tag6, "Failed to fetch unified portfolio:", fetchError.message);
4336
4421
  }
4337
4422
  return null;
4338
4423
  }
4339
4424
  } catch (e) {
4340
- console.error(tag5, "Error:", e);
4425
+ console.error(tag6, "Error:", e);
4341
4426
  return null;
4342
4427
  }
4343
4428
  };
4344
4429
  this.init = async function(walletsVerbose, setup) {
4345
- const tag5 = `${TAG9} | init | `;
4430
+ const tag6 = `${TAG9} | init | `;
4346
4431
  try {
4347
4432
  if (!this.username)
4348
4433
  throw Error("username required!");
@@ -4425,7 +4510,7 @@ class SDK {
4425
4510
  }
4426
4511
  return this.pioneer;
4427
4512
  } catch (e) {
4428
- console.error(tag5, "e: ", e);
4513
+ console.error(tag6, "e: ", e);
4429
4514
  throw e;
4430
4515
  }
4431
4516
  };
@@ -4436,7 +4521,7 @@ class SDK {
4436
4521
  return syncMarket(this.balances, this.pioneer);
4437
4522
  };
4438
4523
  this.sync = async function() {
4439
- const tag5 = `${TAG9} | sync | `;
4524
+ const tag6 = `${TAG9} | sync | `;
4440
4525
  try {
4441
4526
  const matchesNetwork = (item, networkId) => {
4442
4527
  if (!item.networks || !Array.isArray(item.networks))
@@ -4488,16 +4573,16 @@ class SDK {
4488
4573
  let totalPortfolioValue = 0;
4489
4574
  const networksTemp = [];
4490
4575
  const uniqueBlockchains = [...new Set(this.blockchains)];
4491
- console.log(tag5, "uniqueBlockchains: ", uniqueBlockchains);
4576
+ console.log(tag6, "uniqueBlockchains: ", uniqueBlockchains);
4492
4577
  for (const blockchain of uniqueBlockchains) {
4493
4578
  const filteredBalances = this.balances.filter((b2) => {
4494
4579
  const networkId = import_pioneer_caip7.caipToNetworkId(b2.caip);
4495
4580
  return networkId === blockchain || blockchain === "eip155:*" && networkId.startsWith("eip155:");
4496
4581
  });
4497
- console.log(tag5, `Filtering for blockchain: ${blockchain}`);
4498
- console.log(tag5, `Found ${filteredBalances.length} balances before deduplication`);
4582
+ console.log(tag6, `Filtering for blockchain: ${blockchain}`);
4583
+ console.log(tag6, `Found ${filteredBalances.length} balances before deduplication`);
4499
4584
  filteredBalances.forEach((balance, idx) => {
4500
- console.log(tag5, `Balance[${idx}]:`, {
4585
+ console.log(tag6, `Balance[${idx}]:`, {
4501
4586
  caip: balance.caip,
4502
4587
  pubkey: balance.pubkey,
4503
4588
  balance: balance.balance,
@@ -4507,7 +4592,7 @@ class SDK {
4507
4592
  const balanceMap = new Map;
4508
4593
  const isBitcoin = blockchain.includes("bip122:000000000019d6689c085ae165831e93");
4509
4594
  if (isBitcoin) {
4510
- console.log(tag5, "Bitcoin network detected - checking for duplicate balances");
4595
+ console.log(tag6, "Bitcoin network detected - checking for duplicate balances");
4511
4596
  const bitcoinByValue = new Map;
4512
4597
  filteredBalances.forEach((balance) => {
4513
4598
  const valueKey = `${balance.balance}_${balance.valueUsd}`;
@@ -4518,7 +4603,7 @@ class SDK {
4518
4603
  });
4519
4604
  for (const [valueKey, balances] of bitcoinByValue.entries()) {
4520
4605
  if (balances.length === 3 && parseFloat(balances[0].valueUsd || "0") > 0) {
4521
- console.log(tag5, "BITCOIN API BUG DETECTED: All 3 address types have same balance, keeping only xpub");
4606
+ console.log(tag6, "BITCOIN API BUG DETECTED: All 3 address types have same balance, keeping only xpub");
4522
4607
  const xpubBalance = balances.find((b2) => b2.pubkey?.startsWith("xpub")) || balances[0];
4523
4608
  const key = `${xpubBalance.caip}_${xpubBalance.pubkey || "default"}`;
4524
4609
  balanceMap.set(key, xpubBalance);
@@ -4538,13 +4623,13 @@ class SDK {
4538
4623
  });
4539
4624
  }
4540
4625
  const networkBalances = Array.from(balanceMap.values());
4541
- console.log(tag5, "networkBalances (deduplicated): ", networkBalances);
4542
- console.log(tag5, "networkBalances count: ", networkBalances.length);
4626
+ console.log(tag6, "networkBalances (deduplicated): ", networkBalances);
4627
+ console.log(tag6, "networkBalances count: ", networkBalances.length);
4543
4628
  const networkTotal = networkBalances.reduce((sum, balance, idx) => {
4544
4629
  const valueUsd = typeof balance.valueUsd === "string" ? parseFloat(balance.valueUsd) : balance.valueUsd || 0;
4545
- console.log(tag5, `[${idx}] valueUsd:`, balance.valueUsd, "→ parsed:", valueUsd, "| running sum:", sum + valueUsd);
4630
+ console.log(tag6, `[${idx}] valueUsd:`, balance.valueUsd, "→ parsed:", valueUsd, "| running sum:", sum + valueUsd);
4546
4631
  if (blockchain.includes("bip122:000000000019d6689c085ae165831e93")) {
4547
- console.log(tag5, `[BITCOIN DEBUG ${idx}] pubkey:`, balance.pubkey?.substring(0, 10) + "...", "| balance:", balance.balance, "| valueUsd:", balance.valueUsd, "→ parsed:", valueUsd);
4632
+ console.log(tag6, `[BITCOIN DEBUG ${idx}] pubkey:`, balance.pubkey?.substring(0, 10) + "...", "| balance:", balance.balance, "| valueUsd:", balance.valueUsd, "→ parsed:", valueUsd);
4548
4633
  }
4549
4634
  return sum + valueUsd;
4550
4635
  }, 0);
@@ -4575,7 +4660,7 @@ class SDK {
4575
4660
  this.dashboard = dashboardData;
4576
4661
  return true;
4577
4662
  } catch (e) {
4578
- console.error(tag5, "Error in sync:", e);
4663
+ console.error(tag6, "Error in sync:", e);
4579
4664
  throw e;
4580
4665
  }
4581
4666
  };
@@ -4589,7 +4674,7 @@ class SDK {
4589
4674
  }
4590
4675
  };
4591
4676
  this.buildTx = async function(sendPayload) {
4592
- let tag5 = TAG9 + " | buildTx | ";
4677
+ let tag6 = TAG9 + " | buildTx | ";
4593
4678
  try {
4594
4679
  const transactionDependencies = {
4595
4680
  context: this.context,
@@ -4603,7 +4688,7 @@ class SDK {
4603
4688
  };
4604
4689
  let txManager = new TransactionManager(transactionDependencies, this.events);
4605
4690
  let unsignedTx = await txManager.transfer(sendPayload);
4606
- console.log(tag5, "unsignedTx: ", unsignedTx);
4691
+ console.log(tag6, "unsignedTx: ", unsignedTx);
4607
4692
  return unsignedTx;
4608
4693
  } catch (e) {
4609
4694
  console.error(e);
@@ -4611,14 +4696,14 @@ class SDK {
4611
4696
  }
4612
4697
  };
4613
4698
  this.buildDelegateTx = async function(caip, params) {
4614
- let tag5 = TAG9 + " | buildDelegateTx | ";
4699
+ let tag6 = TAG9 + " | buildDelegateTx | ";
4615
4700
  try {
4616
4701
  const delegateParams = {
4617
4702
  ...params,
4618
4703
  type: "delegate"
4619
4704
  };
4620
4705
  let unsignedTx = await createUnsignedStakingTx(caip, delegateParams, this.pubkeys, this.pioneer, this.pubkeyContext);
4621
- console.log(tag5, "unsignedTx: ", unsignedTx);
4706
+ console.log(tag6, "unsignedTx: ", unsignedTx);
4622
4707
  return unsignedTx;
4623
4708
  } catch (e) {
4624
4709
  console.error(e);
@@ -4626,14 +4711,14 @@ class SDK {
4626
4711
  }
4627
4712
  };
4628
4713
  this.buildUndelegateTx = async function(caip, params) {
4629
- let tag5 = TAG9 + " | buildUndelegateTx | ";
4714
+ let tag6 = TAG9 + " | buildUndelegateTx | ";
4630
4715
  try {
4631
4716
  const undelegateParams = {
4632
4717
  ...params,
4633
4718
  type: "undelegate"
4634
4719
  };
4635
4720
  let unsignedTx = await createUnsignedStakingTx(caip, undelegateParams, this.pubkeys, this.pioneer, this.pubkeyContext);
4636
- console.log(tag5, "unsignedTx: ", unsignedTx);
4721
+ console.log(tag6, "unsignedTx: ", unsignedTx);
4637
4722
  return unsignedTx;
4638
4723
  } catch (e) {
4639
4724
  console.error(e);
@@ -4641,14 +4726,14 @@ class SDK {
4641
4726
  }
4642
4727
  };
4643
4728
  this.buildClaimRewardsTx = async function(caip, params) {
4644
- let tag5 = TAG9 + " | buildClaimRewardsTx | ";
4729
+ let tag6 = TAG9 + " | buildClaimRewardsTx | ";
4645
4730
  try {
4646
4731
  const claimParams = {
4647
4732
  ...params,
4648
4733
  type: "claim_rewards"
4649
4734
  };
4650
4735
  let unsignedTx = await createUnsignedStakingTx(caip, claimParams, this.pubkeys, this.pioneer, this.pubkeyContext);
4651
- console.log(tag5, "unsignedTx: ", unsignedTx);
4736
+ console.log(tag6, "unsignedTx: ", unsignedTx);
4652
4737
  return unsignedTx;
4653
4738
  } catch (e) {
4654
4739
  console.error(e);
@@ -4656,7 +4741,7 @@ class SDK {
4656
4741
  }
4657
4742
  };
4658
4743
  this.buildClaimAllRewardsTx = async function(caip, params) {
4659
- let tag5 = TAG9 + " | buildClaimAllRewardsTx | ";
4744
+ let tag6 = TAG9 + " | buildClaimAllRewardsTx | ";
4660
4745
  try {
4661
4746
  const claimAllParams = {
4662
4747
  ...params,
@@ -4669,8 +4754,8 @@ class SDK {
4669
4754
  throw e;
4670
4755
  }
4671
4756
  };
4672
- this.signTx = async function(unsignedTx) {
4673
- let tag5 = TAG9 + " | signTx | ";
4757
+ this.signTx = async function(caip, unsignedTx) {
4758
+ let tag6 = TAG9 + " | signTx | ";
4674
4759
  try {
4675
4760
  const transactionDependencies = {
4676
4761
  context: this.context,
@@ -4683,7 +4768,7 @@ class SDK {
4683
4768
  keepKeySdk: this.keepKeySdk
4684
4769
  };
4685
4770
  let txManager = new TransactionManager(transactionDependencies, this.events);
4686
- let signedTx = await txManager.sign(unsignedTx);
4771
+ let signedTx = await txManager.sign({ caip, unsignedTx });
4687
4772
  return signedTx;
4688
4773
  } catch (e) {
4689
4774
  console.error(e);
@@ -4691,7 +4776,7 @@ class SDK {
4691
4776
  }
4692
4777
  };
4693
4778
  this.broadcastTx = async function(caip, signedTx) {
4694
- let tag5 = TAG9 + " | broadcastTx | ";
4779
+ let tag6 = TAG9 + " | broadcastTx | ";
4695
4780
  try {
4696
4781
  const transactionDependencies = {
4697
4782
  context: this.context,
@@ -4715,7 +4800,7 @@ class SDK {
4715
4800
  }
4716
4801
  };
4717
4802
  this.swap = async function(swapPayload) {
4718
- let tag5 = `${TAG9} | swap | `;
4803
+ let tag6 = `${TAG9} | swap | `;
4719
4804
  try {
4720
4805
  if (!swapPayload)
4721
4806
  throw Error("swapPayload required!");
@@ -4764,15 +4849,15 @@ class SDK {
4764
4849
  throw new Error(`Cannot use max amount: no balance found for ${swapPayload.caipIn}`);
4765
4850
  }
4766
4851
  let totalBalance = 0;
4767
- console.log(tag5, `Found ${inputBalances.length} balance entries for ${swapPayload.caipIn}`);
4852
+ console.log(tag6, `Found ${inputBalances.length} balance entries for ${swapPayload.caipIn}`);
4768
4853
  for (const balanceEntry of inputBalances) {
4769
4854
  const balance = parseFloat(balanceEntry.balance) || 0;
4770
4855
  totalBalance += balance;
4771
- console.log(tag5, ` - ${balanceEntry.pubkey || balanceEntry.identifier}: ${balance}`);
4856
+ console.log(tag6, ` - ${balanceEntry.pubkey || balanceEntry.identifier}: ${balance}`);
4772
4857
  }
4773
4858
  this.assetContext.balance = totalBalance.toString();
4774
4859
  this.assetContext.valueUsd = (totalBalance * parseFloat(this.assetContext.priceUsd || "0")).toFixed(2);
4775
- console.log(tag5, `Updated assetContext balance to aggregated total: ${totalBalance}`);
4860
+ console.log(tag6, `Updated assetContext balance to aggregated total: ${totalBalance}`);
4776
4861
  const feeReserves = {
4777
4862
  "bip122:000000000019d6689c085ae165831e93/slip44:0": 0.00005,
4778
4863
  "eip155:1/slip44:60": 0.001,
@@ -4783,7 +4868,7 @@ class SDK {
4783
4868
  };
4784
4869
  const reserve = feeReserves[swapPayload.caipIn] || 0.0001;
4785
4870
  inputAmount = Math.max(0, totalBalance - reserve);
4786
- console.log(tag5, `Using max amount for swap: ${inputAmount} (total balance: ${totalBalance}, reserve: ${reserve})`);
4871
+ console.log(tag6, `Using max amount for swap: ${inputAmount} (total balance: ${totalBalance}, reserve: ${reserve})`);
4787
4872
  } else {
4788
4873
  inputAmount = typeof swapPayload.amount === "string" ? parseFloat(swapPayload.amount) : swapPayload.amount;
4789
4874
  if (isNaN(inputAmount) || inputAmount <= 0) {
@@ -4791,23 +4876,23 @@ class SDK {
4791
4876
  }
4792
4877
  }
4793
4878
  let quote = {
4794
- affiliate: "0x658DE0443259a1027caA976ef9a42E6982037A03",
4795
- sellAsset: this.assetContext,
4879
+ sellAsset: this.assetContext.caip,
4796
4880
  sellAmount: inputAmount.toPrecision(8),
4797
- buyAsset: this.outboundAssetContext,
4881
+ buyAsset: this.outboundAssetContext.caip,
4798
4882
  recipientAddress,
4799
4883
  senderAddress,
4800
- slippage: "3"
4884
+ slippage: swapPayload.slippagePercentage || 3
4801
4885
  };
4802
4886
  let result;
4803
4887
  try {
4804
4888
  result = await this.pioneer.Quote(quote);
4805
4889
  result = result.data;
4806
4890
  } catch (e) {
4807
- console.error(tag5, "Failed to get quote: ", e);
4891
+ console.error(tag6, "Failed to get quote: ", e);
4892
+ throw Error("Quote API failed for path: " + quote.sellAsset + " -> " + quote.buyAsset + ". Error: " + e);
4808
4893
  }
4809
- if (result.length === 0)
4810
- throw Error("No quotes available! path: " + quote.sellAsset.caip + " -> " + quote.buyAsset.caip);
4894
+ if (!result || result.length === 0)
4895
+ throw Error("No quotes available! path: " + quote.sellAsset + " -> " + quote.buyAsset);
4811
4896
  let selected = result[0];
4812
4897
  let txs = selected.quote.txs;
4813
4898
  if (!txs)
@@ -4820,6 +4905,7 @@ class SDK {
4820
4905
  balances: this.balances,
4821
4906
  pioneer: this.pioneer,
4822
4907
  pubkeys: this.pubkeys,
4908
+ pubkeyContext: this.pubkeyContext,
4823
4909
  nodes: this.nodes,
4824
4910
  keepKeySdk: this.keepKeySdk
4825
4911
  };
@@ -4827,7 +4913,10 @@ class SDK {
4827
4913
  let caip = swapPayload.caipIn;
4828
4914
  let unsignedTx;
4829
4915
  if (tx.type === "deposit") {
4830
- unsignedTx = await createUnsignedTendermintTx(caip, tx.type, tx.txParams.amount, tx.txParams.memo, this.pubkeys, this.pioneer, this.keepKeySdk, false, undefined);
4916
+ unsignedTx = await createUnsignedTendermintTx(caip, tx.type, tx.txParams.amount, tx.txParams.memo, this.pubkeys, this.pioneer, this.pubkeyContext, false, undefined);
4917
+ } else if (tx.type === "EVM" || tx.type === "evm") {
4918
+ console.log(tag6, "Using pre-built EVM transaction from integration");
4919
+ unsignedTx = tx.txParams;
4831
4920
  } else {
4832
4921
  if (!tx.txParams.memo)
4833
4922
  throw Error("memo required on swaps!");
@@ -4845,12 +4934,12 @@ class SDK {
4845
4934
  return unsignedTx;
4846
4935
  }
4847
4936
  } catch (e) {
4848
- console.error(tag5, "Error: ", e);
4937
+ console.error(tag6, "Error: ", e);
4849
4938
  throw e;
4850
4939
  }
4851
4940
  };
4852
4941
  this.transfer = async function(sendPayload) {
4853
- let tag5 = `${TAG9} | transfer | `;
4942
+ let tag6 = `${TAG9} | transfer | `;
4854
4943
  try {
4855
4944
  if (!sendPayload)
4856
4945
  throw Error("sendPayload required!");
@@ -4884,15 +4973,15 @@ class SDK {
4884
4973
  return { txid, events: this.events };
4885
4974
  } catch (error) {
4886
4975
  if (error instanceof Error) {
4887
- console.error(tag5, "An error occurred during the transfer process:", error.message);
4976
+ console.error(tag6, "An error occurred during the transfer process:", error.message);
4888
4977
  } else {
4889
- console.error(tag5, "An unknown error occurred during the transfer process");
4978
+ console.error(tag6, "An unknown error occurred during the transfer process");
4890
4979
  }
4891
4980
  throw error;
4892
4981
  }
4893
4982
  };
4894
4983
  this.followTransaction = async function(caip, txid) {
4895
- let tag5 = " | followTransaction | ";
4984
+ let tag6 = " | followTransaction | ";
4896
4985
  try {
4897
4986
  const finalConfirmationBlocksByCaip = {
4898
4987
  dogecoin: 3,
@@ -4922,7 +5011,7 @@ class SDK {
4922
5011
  }
4923
5012
  }
4924
5013
  } catch (error) {
4925
- console.error(tag5, "Error:", error);
5014
+ console.error(tag6, "Error:", error);
4926
5015
  }
4927
5016
  if (!isConfirmed) {
4928
5017
  await new Promise((resolve) => setTimeout(resolve, 8000));
@@ -4940,18 +5029,18 @@ class SDK {
4940
5029
  requiredConfirmations
4941
5030
  };
4942
5031
  } catch (error) {
4943
- console.error(tag5, "Error:", error);
5032
+ console.error(tag6, "Error:", error);
4944
5033
  throw new Error("Failed to follow transaction");
4945
5034
  }
4946
5035
  };
4947
5036
  this.setBlockchains = async function(blockchains) {
4948
- const tag5 = `${TAG9} | setBlockchains | `;
5037
+ const tag6 = `${TAG9} | setBlockchains | `;
4949
5038
  try {
4950
5039
  if (!blockchains)
4951
5040
  throw Error("blockchains required!");
4952
5041
  const uniqueBlockchains = [...new Set(blockchains)];
4953
5042
  if (blockchains.length !== uniqueBlockchains.length) {
4954
- console.warn(tag5, `Removed ${blockchains.length - uniqueBlockchains.length} duplicate blockchains`);
5043
+ console.warn(tag6, `Removed ${blockchains.length - uniqueBlockchains.length} duplicate blockchains`);
4955
5044
  }
4956
5045
  this.blockchains = uniqueBlockchains;
4957
5046
  this.events.emit("SET_BLOCKCHAINS", this.blockchains);
@@ -4961,7 +5050,7 @@ class SDK {
4961
5050
  }
4962
5051
  };
4963
5052
  this.addAsset = async function(caip, data) {
4964
- let tag5 = TAG9 + " | addAsset | ";
5053
+ let tag6 = TAG9 + " | addAsset | ";
4965
5054
  try {
4966
5055
  let success = false;
4967
5056
  if (!caip)
@@ -4999,22 +5088,22 @@ class SDK {
4999
5088
  }
5000
5089
  };
5001
5090
  this.clearWalletState = async function() {
5002
- const tag5 = `${TAG9} | clearWalletState | `;
5091
+ const tag6 = `${TAG9} | clearWalletState | `;
5003
5092
  try {
5004
5093
  this.context = null;
5005
5094
  this.paths = [];
5006
5095
  this.blockchains = [];
5007
5096
  this.pubkeys = [];
5008
5097
  this.pubkeySet.clear();
5009
- console.log(tag5, "Cleared wallet state including pubkeys and tracking set");
5098
+ console.log(tag6, "Cleared wallet state including pubkeys and tracking set");
5010
5099
  return true;
5011
5100
  } catch (e) {
5012
- console.error(tag5, "e: ", e);
5101
+ console.error(tag6, "e: ", e);
5013
5102
  throw e;
5014
5103
  }
5015
5104
  };
5016
5105
  this.addPath = async function(path) {
5017
- const tag5 = `${TAG9} | addPath | `;
5106
+ const tag6 = `${TAG9} | addPath | `;
5018
5107
  try {
5019
5108
  this.paths.push(path);
5020
5109
  const pubkey = await getPubkey(path.networks[0], path, this.keepKeySdk, this.context);
@@ -5023,14 +5112,14 @@ class SDK {
5023
5112
  this.buildDashboardFromBalances();
5024
5113
  return { success: true, pubkey };
5025
5114
  } catch (e) {
5026
- console.error(tag5, "Failed:", e);
5115
+ console.error(tag6, "Failed:", e);
5027
5116
  throw e;
5028
5117
  }
5029
5118
  };
5030
5119
  this.addPaths = async function(paths) {
5031
- const tag5 = `${TAG9} | addPaths | `;
5120
+ const tag6 = `${TAG9} | addPaths | `;
5032
5121
  try {
5033
- console.log(tag5, `Adding ${paths.length} paths in batch mode...`);
5122
+ console.log(tag6, `Adding ${paths.length} paths in batch mode...`);
5034
5123
  this.paths.push(...paths);
5035
5124
  const newPubkeys = [];
5036
5125
  for (const path of paths) {
@@ -5039,10 +5128,10 @@ class SDK {
5039
5128
  this.addPubkey(pubkey);
5040
5129
  newPubkeys.push(pubkey);
5041
5130
  } catch (error) {
5042
- console.warn(tag5, `Failed to get pubkey for path ${path.note}:`, error.message);
5131
+ console.warn(tag6, `Failed to get pubkey for path ${path.note}:`, error.message);
5043
5132
  }
5044
5133
  }
5045
- console.log(tag5, `Successfully added ${newPubkeys.length} pubkeys`);
5134
+ console.log(tag6, `Successfully added ${newPubkeys.length} pubkeys`);
5046
5135
  const networkSet = new Set;
5047
5136
  for (const path of paths) {
5048
5137
  if (path.networks && Array.isArray(path.networks)) {
@@ -5050,13 +5139,13 @@ class SDK {
5050
5139
  }
5051
5140
  }
5052
5141
  const uniqueNetworks = [...networkSet];
5053
- console.log(tag5, `Fetching balances for ${uniqueNetworks.length} unique networks in single API call...`);
5142
+ console.log(tag6, `Fetching balances for ${uniqueNetworks.length} unique networks in single API call...`);
5054
5143
  await this.getBalancesForNetworks(uniqueNetworks);
5055
5144
  this.buildDashboardFromBalances();
5056
- console.log(tag5, `Batch add complete: ${paths.length} paths, ${newPubkeys.length} pubkeys, ${this.balances?.length || 0} balances`);
5145
+ console.log(tag6, `Batch add complete: ${paths.length} paths, ${newPubkeys.length} pubkeys, ${this.balances?.length || 0} balances`);
5057
5146
  return { success: true, pubkeys: newPubkeys };
5058
5147
  } catch (e) {
5059
- console.error(tag5, "Failed:", e);
5148
+ console.error(tag6, "Failed:", e);
5060
5149
  throw e;
5061
5150
  }
5062
5151
  };
@@ -5064,7 +5153,7 @@ class SDK {
5064
5153
  return this.getGasAssets();
5065
5154
  };
5066
5155
  this.getGasAssets = async function() {
5067
- const tag5 = `${TAG9} | getGasAssets | `;
5156
+ const tag6 = `${TAG9} | getGasAssets | `;
5068
5157
  try {
5069
5158
  for (let i = 0;i < this.blockchains.length; i++) {
5070
5159
  let networkId = this.blockchains[i];
@@ -5098,7 +5187,7 @@ class SDK {
5098
5187
  denom: "maya"
5099
5188
  };
5100
5189
  this.assetsMap.set(mayaTokenCaip, mayaToken);
5101
- console.log(tag5, "Added MAYA token to assetsMap");
5190
+ console.log(tag6, "Added MAYA token to assetsMap");
5102
5191
  }
5103
5192
  return this.assetsMap;
5104
5193
  } catch (e) {
@@ -5107,7 +5196,7 @@ class SDK {
5107
5196
  }
5108
5197
  };
5109
5198
  this.getPubkeys = async function() {
5110
- const tag5 = `${TAG9} | getPubkeys | `;
5199
+ const tag6 = `${TAG9} | getPubkeys | `;
5111
5200
  try {
5112
5201
  if (this.paths.length === 0)
5113
5202
  throw new Error("No paths found!");
@@ -5123,15 +5212,15 @@ class SDK {
5123
5212
  return pubkeys;
5124
5213
  } catch (error) {
5125
5214
  console.error("Error in getPubkeys:", error);
5126
- console.error(tag5, "Error in getPubkeys:", error);
5215
+ console.error(tag6, "Error in getPubkeys:", error);
5127
5216
  throw error;
5128
5217
  }
5129
5218
  };
5130
5219
  this.getBalancesForNetworks = async function(networkIds) {
5131
- const tag5 = `${TAG9} | getBalancesForNetworks | `;
5220
+ const tag6 = `${TAG9} | getBalancesForNetworks | `;
5132
5221
  try {
5133
5222
  if (!this.pioneer) {
5134
- console.error(tag5, "ERROR: Pioneer client not initialized! this.pioneer is:", this.pioneer);
5223
+ console.error(tag6, "ERROR: Pioneer client not initialized! this.pioneer is:", this.pioneer);
5135
5224
  throw new Error("Pioneer client not initialized. Call init() first.");
5136
5225
  }
5137
5226
  const assetQuery = [];
@@ -5169,48 +5258,48 @@ class SDK {
5169
5258
  identifier: `${balance.caip}:${balance.pubkey}`
5170
5259
  });
5171
5260
  }
5172
- console.log(tag5, "balances: ", balances);
5261
+ console.log(tag6, "balances: ", balances);
5173
5262
  this.balances = balances;
5174
5263
  this.events.emit("SET_BALANCES", this.balances);
5175
5264
  return this.balances;
5176
5265
  } catch (apiError) {
5177
- console.error(tag5, "GetPortfolioBalances API call failed:", apiError);
5266
+ console.error(tag6, "GetPortfolioBalances API call failed:", apiError);
5178
5267
  throw new Error(`GetPortfolioBalances API call failed: ${apiError?.message || "Unknown error"}`);
5179
5268
  }
5180
5269
  } catch (e) {
5181
- console.error(tag5, "Error: ", e);
5270
+ console.error(tag6, "Error: ", e);
5182
5271
  throw e;
5183
5272
  }
5184
5273
  };
5185
5274
  this.getBalances = async function() {
5186
- const tag5 = `${TAG9} | getBalances | `;
5275
+ const tag6 = `${TAG9} | getBalances | `;
5187
5276
  try {
5188
5277
  return await this.getBalancesForNetworks(this.blockchains);
5189
5278
  } catch (e) {
5190
- console.error(tag5, "Error in getBalances: ", e);
5279
+ console.error(tag6, "Error in getBalances: ", e);
5191
5280
  throw e;
5192
5281
  }
5193
5282
  };
5194
5283
  this.getBalance = async function(networkId) {
5195
- const tag5 = `${TAG9} | getBalance | `;
5284
+ const tag6 = `${TAG9} | getBalance | `;
5196
5285
  try {
5197
5286
  const results = await this.getBalancesForNetworks([networkId]);
5198
5287
  const filtered = results.filter(async (b2) => b2.networkId === await import_pioneer_caip7.networkIdToCaip(networkId));
5199
5288
  return filtered;
5200
5289
  } catch (e) {
5201
- console.error(tag5, "Error: ", e);
5290
+ console.error(tag6, "Error: ", e);
5202
5291
  throw e;
5203
5292
  }
5204
5293
  };
5205
5294
  this.getFees = async function(networkId) {
5206
- const tag5 = `${TAG9} | getFees | `;
5295
+ const tag6 = `${TAG9} | getFees | `;
5207
5296
  try {
5208
5297
  if (!this.pioneer) {
5209
5298
  throw new Error("Pioneer client not initialized. Call init() first.");
5210
5299
  }
5211
5300
  return await getFees(this.pioneer, networkId);
5212
5301
  } catch (e) {
5213
- console.error(tag5, "Error getting fees: ", e);
5302
+ console.error(tag6, "Error getting fees: ", e);
5214
5303
  throw e;
5215
5304
  }
5216
5305
  };
@@ -5218,11 +5307,11 @@ class SDK {
5218
5307
  return estimateTransactionFee(feeRate, unit, networkType, txSize);
5219
5308
  };
5220
5309
  this.getCharts = async function() {
5221
- const tag5 = `${TAG9} | getCharts | `;
5310
+ const tag6 = `${TAG9} | getCharts | `;
5222
5311
  try {
5223
- console.log(tag5, "Fetching charts");
5312
+ console.log(tag6, "Fetching charts");
5224
5313
  const newBalances = await getCharts(this.blockchains, this.pioneer, this.pubkeys, this.context);
5225
- console.log(tag5, "newBalances: ", newBalances);
5314
+ console.log(tag6, "newBalances: ", newBalances);
5226
5315
  const uniqueBalances = new Map([...this.balances, ...newBalances].map((balance) => [
5227
5316
  balance.identifier,
5228
5317
  {
@@ -5230,17 +5319,17 @@ class SDK {
5230
5319
  type: balance.type || "balance"
5231
5320
  }
5232
5321
  ]));
5233
- console.log(tag5, "uniqueBalances: ", uniqueBalances);
5322
+ console.log(tag6, "uniqueBalances: ", uniqueBalances);
5234
5323
  this.balances = Array.from(uniqueBalances.values());
5235
- console.log(tag5, "Updated this.balances: ", this.balances);
5324
+ console.log(tag6, "Updated this.balances: ", this.balances);
5236
5325
  return this.balances;
5237
5326
  } catch (e) {
5238
- console.error(tag5, "Error in getCharts:", e);
5327
+ console.error(tag6, "Error in getCharts:", e);
5239
5328
  throw e;
5240
5329
  }
5241
5330
  };
5242
5331
  this.setContext = async (context) => {
5243
- const tag5 = `${TAG9} | setContext | `;
5332
+ const tag6 = `${TAG9} | setContext | `;
5244
5333
  try {
5245
5334
  if (!context)
5246
5335
  throw Error("context required!");
@@ -5248,12 +5337,12 @@ class SDK {
5248
5337
  this.events.emit("SET_CONTEXT", context);
5249
5338
  return { success: true };
5250
5339
  } catch (e) {
5251
- console.error(tag5, "e: ", e);
5340
+ console.error(tag6, "e: ", e);
5252
5341
  return { success: false };
5253
5342
  }
5254
5343
  };
5255
5344
  this.setContextType = async (contextType) => {
5256
- const tag5 = `${TAG9} | setContextType | `;
5345
+ const tag6 = `${TAG9} | setContextType | `;
5257
5346
  try {
5258
5347
  if (!contextType)
5259
5348
  throw Error("contextType required!");
@@ -5261,22 +5350,22 @@ class SDK {
5261
5350
  this.events.emit("SET_CONTEXT_TYPE", contextType);
5262
5351
  return { success: true };
5263
5352
  } catch (e) {
5264
- console.error(tag5, "e: ", e);
5353
+ console.error(tag6, "e: ", e);
5265
5354
  return { success: false };
5266
5355
  }
5267
5356
  };
5268
5357
  this.refresh = async () => {
5269
- const tag5 = `${TAG9} | refresh | `;
5358
+ const tag6 = `${TAG9} | refresh | `;
5270
5359
  try {
5271
5360
  await this.sync();
5272
5361
  return this.balances;
5273
5362
  } catch (e) {
5274
- console.error(tag5, "e: ", e);
5363
+ console.error(tag6, "e: ", e);
5275
5364
  throw e;
5276
5365
  }
5277
5366
  };
5278
5367
  this.setAssetContext = async function(asset) {
5279
- const tag5 = `${TAG9} | setAssetContext | `;
5368
+ const tag6 = `${TAG9} | setAssetContext | `;
5280
5369
  try {
5281
5370
  if (!asset) {
5282
5371
  this.assetContext = null;
@@ -5288,7 +5377,7 @@ class SDK {
5288
5377
  asset.networkId = import_pioneer_caip7.caipToNetworkId(asset.caip);
5289
5378
  if (!this.pubkeys || this.pubkeys.length === 0) {
5290
5379
  const errorMsg = `Cannot set asset context for ${asset.caip} - no pubkeys loaded. Please initialize wallet first.`;
5291
- console.error(tag5, errorMsg);
5380
+ console.error(tag6, errorMsg);
5292
5381
  throw new Error(errorMsg);
5293
5382
  }
5294
5383
  const pubkeysForNetwork = this.pubkeys.filter((e) => {
@@ -5303,8 +5392,8 @@ class SDK {
5303
5392
  });
5304
5393
  if (pubkeysForNetwork.length === 0) {
5305
5394
  const errorMsg = `Cannot set asset context for ${asset.caip} - no address/xpub found for network ${asset.networkId}`;
5306
- console.error(tag5, errorMsg);
5307
- console.error(tag5, "Available networks in pubkeys:", [
5395
+ console.error(tag6, errorMsg);
5396
+ console.error(tag6, "Available networks in pubkeys:", [
5308
5397
  ...new Set(this.pubkeys.flatMap((p2) => p2.networks || []))
5309
5398
  ]);
5310
5399
  throw new Error(errorMsg);
@@ -5314,43 +5403,43 @@ class SDK {
5314
5403
  const xpubFound = pubkeysForNetwork.some((p2) => p2.type === "xpub" && p2.pubkey);
5315
5404
  if (!xpubFound) {
5316
5405
  const errorMsg = `Cannot set asset context for UTXO chain ${asset.caip} - xpub required but not found`;
5317
- console.error(tag5, errorMsg);
5406
+ console.error(tag6, errorMsg);
5318
5407
  throw new Error(errorMsg);
5319
5408
  }
5320
5409
  }
5321
5410
  const hasValidAddress = pubkeysForNetwork.some((p2) => p2.address || p2.master || p2.pubkey);
5322
5411
  if (!hasValidAddress) {
5323
5412
  const errorMsg = `Cannot set asset context for ${asset.caip} - no valid address found in pubkeys`;
5324
- console.error(tag5, errorMsg);
5413
+ console.error(tag6, errorMsg);
5325
5414
  throw new Error(errorMsg);
5326
5415
  }
5327
- console.log(tag5, `✅ Validated: Found ${pubkeysForNetwork.length} addresses for ${asset.networkId}`);
5416
+ console.log(tag6, `✅ Validated: Found ${pubkeysForNetwork.length} addresses for ${asset.networkId}`);
5328
5417
  let freshPriceUsd = 0;
5329
5418
  try {
5330
5419
  if (!asset.caip || typeof asset.caip !== "string" || !asset.caip.includes(":")) {
5331
- console.warn(tag5, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
5420
+ console.warn(tag6, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
5332
5421
  } else {
5333
- console.log(tag5, "Fetching fresh market price for:", asset.caip);
5422
+ console.log(tag6, "Fetching fresh market price for:", asset.caip);
5334
5423
  const marketData = await this.pioneer.GetMarketInfo([asset.caip]);
5335
- console.log(tag5, "Market data response:", marketData);
5424
+ console.log(tag6, "Market data response:", marketData);
5336
5425
  if (marketData && marketData.data && marketData.data.length > 0) {
5337
5426
  freshPriceUsd = marketData.data[0];
5338
- console.log(tag5, "✅ Fresh market price:", freshPriceUsd);
5427
+ console.log(tag6, "✅ Fresh market price:", freshPriceUsd);
5339
5428
  } else {
5340
- console.warn(tag5, "No market data returned for:", asset.caip);
5429
+ console.warn(tag6, "No market data returned for:", asset.caip);
5341
5430
  }
5342
5431
  }
5343
5432
  } catch (marketError) {
5344
- console.error(tag5, "Error fetching market price:", marketError);
5433
+ console.error(tag6, "Error fetching market price:", marketError);
5345
5434
  }
5346
5435
  let assetInfo = this.assetsMap.get(asset.caip.toLowerCase());
5347
- console.log(tag5, "assetInfo: ", assetInfo);
5436
+ console.log(tag6, "assetInfo: ", assetInfo);
5348
5437
  let assetInfoDiscovery = import_pioneer_discovery2.assetData[asset.caip];
5349
- console.log(tag5, "assetInfoDiscovery: ", assetInfoDiscovery);
5438
+ console.log(tag6, "assetInfoDiscovery: ", assetInfoDiscovery);
5350
5439
  if (assetInfoDiscovery)
5351
5440
  assetInfo = assetInfoDiscovery;
5352
5441
  if (!assetInfo) {
5353
- console.log(tag5, "Building placeholder asset!");
5442
+ console.log(tag6, "Building placeholder asset!");
5354
5443
  assetInfo = {
5355
5444
  caip: asset.caip.toLowerCase(),
5356
5445
  networkId: asset.networkId,
@@ -5367,30 +5456,30 @@ class SDK {
5367
5456
  const valueUsd = parseFloat(matchingBalances[0].valueUsd);
5368
5457
  if (balance > 0 && valueUsd > 0) {
5369
5458
  priceValue = valueUsd / balance;
5370
- console.log(tag5, "calculated priceUsd from valueUsd/balance:", priceValue);
5459
+ console.log(tag6, "calculated priceUsd from valueUsd/balance:", priceValue);
5371
5460
  }
5372
5461
  }
5373
5462
  if (priceValue && priceValue > 0) {
5374
- console.log(tag5, "detected priceUsd from balance:", priceValue);
5463
+ console.log(tag6, "detected priceUsd from balance:", priceValue);
5375
5464
  assetInfo.priceUsd = priceValue;
5376
5465
  }
5377
5466
  }
5378
5467
  if (freshPriceUsd && freshPriceUsd > 0) {
5379
5468
  assetInfo.priceUsd = freshPriceUsd;
5380
- console.log(tag5, "✅ Using fresh market price:", freshPriceUsd);
5469
+ console.log(tag6, "✅ Using fresh market price:", freshPriceUsd);
5381
5470
  let totalBalance = 0;
5382
5471
  let totalValueUsd = 0;
5383
- console.log(tag5, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5472
+ console.log(tag6, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5384
5473
  for (const balanceEntry of matchingBalances) {
5385
5474
  const balance = parseFloat(balanceEntry.balance) || 0;
5386
5475
  const valueUsd = parseFloat(balanceEntry.valueUsd) || 0;
5387
5476
  totalBalance += balance;
5388
5477
  totalValueUsd += valueUsd;
5389
- console.log(tag5, ` Balance entry: ${balance} (${valueUsd} USD)`);
5478
+ console.log(tag6, ` Balance entry: ${balance} (${valueUsd} USD)`);
5390
5479
  }
5391
5480
  assetInfo.balance = totalBalance.toString();
5392
5481
  assetInfo.valueUsd = totalValueUsd.toFixed(2);
5393
- console.log(tag5, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5482
+ console.log(tag6, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5394
5483
  }
5395
5484
  const assetBalances = this.balances.filter((b2) => b2.caip === asset.caip);
5396
5485
  const assetPubkeys = this.pubkeys.filter((p2) => p2.networks && Array.isArray(p2.networks) && p2.networks.includes(import_pioneer_caip7.caipToNetworkId(asset.caip)) || import_pioneer_caip7.caipToNetworkId(asset.caip).includes("eip155") && p2.networks && Array.isArray(p2.networks) && p2.networks.some((n2) => n2.startsWith("eip155")));
@@ -5410,7 +5499,7 @@ class SDK {
5410
5499
  const balanceAmount = parseFloat(balance.balance || 0);
5411
5500
  balance.valueUsd = (balanceAmount * freshPriceUsd).toString();
5412
5501
  }
5413
- console.log(tag5, "Updated all balances with fresh price data");
5502
+ console.log(tag6, "Updated all balances with fresh price data");
5414
5503
  }
5415
5504
  this.assetContext = finalAssetContext;
5416
5505
  if (asset.isToken || asset.type === "token" || assetInfo.isToken || assetInfo.type === "token") {
@@ -5462,20 +5551,20 @@ class SDK {
5462
5551
  const currentContextValid = this.pubkeyContext?.networks?.includes(networkId);
5463
5552
  if (!this.pubkeyContext || !currentContextValid) {
5464
5553
  this.pubkeyContext = assetPubkeys[0];
5465
- console.log(tag5, "Auto-set pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey);
5554
+ console.log(tag6, "Auto-set pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey);
5466
5555
  } else {
5467
- console.log(tag5, "Preserving existing pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey, `(addressNList: [${(this.pubkeyContext.addressNList || this.pubkeyContext.addressNListMaster).join(", ")}])`);
5556
+ console.log(tag6, "Preserving existing pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey, `(addressNList: [${(this.pubkeyContext.addressNList || this.pubkeyContext.addressNListMaster).join(", ")}])`);
5468
5557
  }
5469
5558
  }
5470
5559
  this.events.emit("SET_ASSET_CONTEXT", this.assetContext);
5471
5560
  return this.assetContext;
5472
5561
  } catch (e) {
5473
- console.error(tag5, "e: ", e);
5562
+ console.error(tag6, "e: ", e);
5474
5563
  throw e;
5475
5564
  }
5476
5565
  };
5477
5566
  this.setPubkeyContext = async function(pubkey) {
5478
- let tag5 = `${TAG9} | setPubkeyContext | `;
5567
+ let tag6 = `${TAG9} | setPubkeyContext | `;
5479
5568
  try {
5480
5569
  if (!pubkey)
5481
5570
  throw Error("pubkey is required");
@@ -5483,31 +5572,31 @@ class SDK {
5483
5572
  throw Error("invalid pubkey: missing pubkey or address");
5484
5573
  const exists = this.pubkeys.some((pk) => pk.pubkey === pubkey.pubkey || pk.address === pubkey.address || pk.pubkey === pubkey.address);
5485
5574
  if (!exists) {
5486
- console.warn(tag5, "Pubkey not found in current pubkeys array");
5575
+ console.warn(tag6, "Pubkey not found in current pubkeys array");
5487
5576
  }
5488
5577
  this.pubkeyContext = pubkey;
5489
- console.log(tag5, "Pubkey context set to:", pubkey.address || pubkey.pubkey, "note:", pubkey.note, "addressNList:", pubkey.addressNList || pubkey.addressNListMaster);
5578
+ console.log(tag6, "Pubkey context set to:", pubkey.address || pubkey.pubkey, "note:", pubkey.note, "addressNList:", pubkey.addressNList || pubkey.addressNListMaster);
5490
5579
  return true;
5491
5580
  } catch (e) {
5492
- console.error(tag5, "e: ", e);
5581
+ console.error(tag6, "e: ", e);
5493
5582
  throw e;
5494
5583
  }
5495
5584
  };
5496
5585
  this.setOutboundAssetContext = async function(asset) {
5497
- const tag5 = `${TAG9} | setOutputAssetContext | `;
5586
+ const tag6 = `${TAG9} | setOutputAssetContext | `;
5498
5587
  try {
5499
- console.log(tag5, "0. asset: ", asset);
5588
+ console.log(tag6, "0. asset: ", asset);
5500
5589
  if (!asset) {
5501
5590
  this.outboundAssetContext = null;
5502
5591
  return;
5503
5592
  }
5504
- console.log(tag5, "1 asset: ", asset);
5593
+ console.log(tag6, "1 asset: ", asset);
5505
5594
  if (!asset.caip)
5506
5595
  throw Error("Invalid Asset! missing caip!");
5507
5596
  if (!asset.networkId)
5508
5597
  asset.networkId = import_pioneer_caip7.caipToNetworkId(asset.caip);
5509
- console.log(tag5, "networkId: ", asset.networkId);
5510
- console.log(tag5, "this.pubkeys: ", this.pubkeys);
5598
+ console.log(tag6, "networkId: ", asset.networkId);
5599
+ console.log(tag6, "this.pubkeys: ", this.pubkeys);
5511
5600
  const pubkey = this.pubkeys.find((p2) => {
5512
5601
  if (!p2.networks || !Array.isArray(p2.networks))
5513
5602
  return false;
@@ -5522,23 +5611,23 @@ class SDK {
5522
5611
  let freshPriceUsd = 0;
5523
5612
  try {
5524
5613
  if (!asset.caip || typeof asset.caip !== "string" || !asset.caip.includes(":")) {
5525
- console.warn(tag5, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
5614
+ console.warn(tag6, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
5526
5615
  } else {
5527
- console.log(tag5, "Fetching fresh market price for:", asset.caip);
5616
+ console.log(tag6, "Fetching fresh market price for:", asset.caip);
5528
5617
  const marketData = await this.pioneer.GetMarketInfo([asset.caip]);
5529
- console.log(tag5, "Market data response:", marketData);
5618
+ console.log(tag6, "Market data response:", marketData);
5530
5619
  if (marketData && marketData.data && marketData.data.length > 0) {
5531
5620
  freshPriceUsd = marketData.data[0];
5532
- console.log(tag5, "✅ Fresh market price:", freshPriceUsd);
5621
+ console.log(tag6, "✅ Fresh market price:", freshPriceUsd);
5533
5622
  } else {
5534
- console.warn(tag5, "No market data returned for:", asset.caip);
5623
+ console.warn(tag6, "No market data returned for:", asset.caip);
5535
5624
  }
5536
5625
  }
5537
5626
  } catch (marketError) {
5538
- console.error(tag5, "Error fetching market price:", marketError);
5627
+ console.error(tag6, "Error fetching market price:", marketError);
5539
5628
  }
5540
5629
  let assetInfo = this.assetsMap.get(asset.caip.toLowerCase());
5541
- console.log(tag5, "assetInfo: ", assetInfo);
5630
+ console.log(tag6, "assetInfo: ", assetInfo);
5542
5631
  if (!assetInfo) {
5543
5632
  assetInfo = {
5544
5633
  caip: asset.caip.toLowerCase(),
@@ -5556,45 +5645,45 @@ class SDK {
5556
5645
  const valueUsd = parseFloat(matchingBalances[0].valueUsd);
5557
5646
  if (balance > 0 && valueUsd > 0) {
5558
5647
  priceValue = valueUsd / balance;
5559
- console.log(tag5, "calculated priceUsd from valueUsd/balance:", priceValue);
5648
+ console.log(tag6, "calculated priceUsd from valueUsd/balance:", priceValue);
5560
5649
  }
5561
5650
  }
5562
5651
  if (priceValue && priceValue > 0) {
5563
- console.log(tag5, "detected priceUsd from balance:", priceValue);
5652
+ console.log(tag6, "detected priceUsd from balance:", priceValue);
5564
5653
  assetInfo.priceUsd = priceValue;
5565
5654
  }
5566
5655
  }
5567
5656
  if (freshPriceUsd && freshPriceUsd > 0) {
5568
5657
  assetInfo.priceUsd = freshPriceUsd;
5569
- console.log(tag5, "✅ Using fresh market price:", freshPriceUsd);
5658
+ console.log(tag6, "✅ Using fresh market price:", freshPriceUsd);
5570
5659
  let totalBalance = 0;
5571
5660
  let totalValueUsd = 0;
5572
- console.log(tag5, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5661
+ console.log(tag6, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5573
5662
  for (const balanceEntry of matchingBalances) {
5574
5663
  const balance = parseFloat(balanceEntry.balance) || 0;
5575
5664
  const valueUsd = parseFloat(balanceEntry.valueUsd) || 0;
5576
5665
  totalBalance += balance;
5577
5666
  totalValueUsd += valueUsd;
5578
- console.log(tag5, ` Balance entry: ${balance} (${valueUsd} USD)`);
5667
+ console.log(tag6, ` Balance entry: ${balance} (${valueUsd} USD)`);
5579
5668
  }
5580
5669
  assetInfo.balance = totalBalance.toString();
5581
5670
  assetInfo.valueUsd = totalValueUsd.toFixed(2);
5582
- console.log(tag5, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5671
+ console.log(tag6, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5583
5672
  }
5584
- console.log(tag5, "CHECKPOINT 1");
5673
+ console.log(tag6, "CHECKPOINT 1");
5585
5674
  this.outboundAssetContext = { ...assetInfo, ...asset, ...pubkey };
5586
- console.log(tag5, "CHECKPOINT 3");
5587
- console.log(tag5, "outboundAssetContext: assetInfo: ", assetInfo);
5675
+ console.log(tag6, "CHECKPOINT 3");
5676
+ console.log(tag6, "outboundAssetContext: assetInfo: ", assetInfo);
5588
5677
  if (asset.caip) {
5589
5678
  this.outboundBlockchainContext = import_pioneer_caip7.caipToNetworkId(asset.caip);
5590
5679
  } else if (asset.networkId) {
5591
5680
  this.outboundBlockchainContext = asset.networkId;
5592
5681
  }
5593
- console.log(tag5, "CHECKPOINT 4");
5682
+ console.log(tag6, "CHECKPOINT 4");
5594
5683
  this.events.emit("SET_OUTBOUND_ASSET_CONTEXT", this.outboundAssetContext);
5595
5684
  return this.outboundAssetContext;
5596
5685
  } catch (e) {
5597
- console.error(tag5, "e: ", e);
5686
+ console.error(tag6, "e: ", e);
5598
5687
  throw e;
5599
5688
  }
5600
5689
  };