@pioneer-platform/pioneer-sdk 4.21.0 → 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,74 +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
- const balanceEth = parseFloat(balanceData.data.balance);
1997
+ const balanceEth = parseFloat(balanceData.data.nativeBalance || balanceData.data.balance || "0");
1918
1998
  const balance = BigInt(Math.round(balanceEth * 1000000000000000000));
1999
+ console.log(tag6, "Native ETH balance from API:", balanceData.data.nativeBalance || balanceData.data.balance, "ETH (", balance.toString(), "wei)");
1919
2000
  if (balance <= 0n)
1920
2001
  throw new Error("Wallet balance is zero");
1921
2002
  const assetType = classifyCaipEvm(caip);
@@ -1928,7 +2009,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1928
2009
  let gasLimit;
1929
2010
  if (isThorchainOperation) {
1930
2011
  gasLimit = BigInt(120000);
1931
- 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());
1932
2013
  } else {
1933
2014
  gasLimit = chainId === 1 ? BigInt(21000) : BigInt(25000);
1934
2015
  }
@@ -1944,7 +2025,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1944
2025
  }
1945
2026
  const buffer = BigInt(100);
1946
2027
  amountWei = balance - gasFee - buffer;
1947
- 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());
1948
2029
  } else {
1949
2030
  amountWei = BigInt(Math.round(amount * 1000000000000000000));
1950
2031
  if (amountWei + gasFee > balance) {
@@ -1954,14 +2035,14 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1954
2035
  const isThorchainSwap = memo && (memo.startsWith("=") || memo.startsWith("SWAP") || memo.includes(":"));
1955
2036
  let txData = "0x";
1956
2037
  if (isThorchainSwap) {
1957
- 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);
1958
2039
  let fixedMemo = memo;
1959
2040
  if (memo.startsWith("=:b:") || memo.startsWith("=:btc:")) {
1960
2041
  fixedMemo = memo.replace(/^=:(b|btc):/, "=:BTC.BTC:");
1961
- console.log(tag5, "Fixed Bitcoin swap memo from:", memo, "to:", fixedMemo);
2042
+ console.log(tag6, "Fixed Bitcoin swap memo from:", memo, "to:", fixedMemo);
1962
2043
  } else if (memo.startsWith("=:e:") || memo.startsWith("=:eth:")) {
1963
2044
  fixedMemo = memo.replace(/^=:(e|eth):/, "=:ETH.ETH:");
1964
- console.log(tag5, "Fixed Ethereum swap memo from:", memo, "to:", fixedMemo);
2045
+ console.log(tag6, "Fixed Ethereum swap memo from:", memo, "to:", fixedMemo);
1965
2046
  }
1966
2047
  if (fixedMemo.length > 250) {
1967
2048
  throw new Error(`Memo too long for THORChain: ${fixedMemo.length} bytes (max 250)`);
@@ -1977,14 +2058,14 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1977
2058
  if (ethInbound) {
1978
2059
  vaultAddress = ethInbound.address;
1979
2060
  routerAddress = ethInbound.router || to;
1980
- console.log(tag5, "Using THORChain inbound addresses - vault:", vaultAddress, "router:", routerAddress);
2061
+ console.log(tag6, "Using THORChain inbound addresses - vault:", vaultAddress, "router:", routerAddress);
1981
2062
  to = routerAddress;
1982
2063
  } else {
1983
2064
  throw new Error("ETH inbound is halted or not found - cannot proceed with swap");
1984
2065
  }
1985
2066
  }
1986
2067
  } catch (fetchError) {
1987
- console.error(tag5, "Failed to fetch inbound addresses:", fetchError);
2068
+ console.error(tag6, "Failed to fetch inbound addresses:", fetchError);
1988
2069
  throw new Error(`Cannot proceed with THORChain swap - failed to fetch inbound addresses: ${fetchError.message}`);
1989
2070
  }
1990
2071
  if (vaultAddress === "0x0000000000000000000000000000000000000000") {
@@ -2004,7 +2085,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2004
2085
  const paddingLength = (32 - memoBytes.length % 32) % 32;
2005
2086
  const memoPadded = memoHex + "0".repeat(paddingLength * 2);
2006
2087
  txData = "0x" + functionSelector + vaultPadded + assetPadded + amountPadded + stringOffset + expiryPadded + stringLength + memoPadded;
2007
- console.log(tag5, "Encoded THORChain depositWithExpiry data:", {
2088
+ console.log(tag6, "Encoded THORChain depositWithExpiry data:", {
2008
2089
  functionSelector: "0x" + functionSelector,
2009
2090
  vault: vaultAddress,
2010
2091
  asset: assetAddress,
@@ -2014,9 +2095,9 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2014
2095
  stringOffset: "0x" + stringOffset,
2015
2096
  fullData: txData
2016
2097
  });
2017
- 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");
2018
2099
  } catch (error) {
2019
- console.error(tag5, "Error encoding THORChain deposit:", error);
2100
+ console.error(tag6, "Error encoding THORChain deposit:", error);
2020
2101
  throw new Error(`Failed to encode THORChain swap: ${error.message}`);
2021
2102
  }
2022
2103
  } else if (memo) {
@@ -2035,19 +2116,19 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2035
2116
  }
2036
2117
  case "erc20": {
2037
2118
  const contractAddress = extractContractAddressFromCaip(caip);
2038
- 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);
2039
2120
  let tokenDecimals;
2040
2121
  try {
2041
- 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);
2042
2123
  const decimalsResponse = await pioneer.GetTokenDecimals({
2043
2124
  networkId,
2044
2125
  contractAddress
2045
2126
  });
2046
2127
  tokenDecimals = Number(decimalsResponse.data.decimals);
2047
- console.log(tag5, "✅ Fetched decimals from pioneer-server:", tokenDecimals);
2128
+ console.log(tag6, "✅ Fetched decimals from pioneer-server:", tokenDecimals);
2048
2129
  } catch (error) {
2049
- console.error(tag5, "Failed to fetch token decimals from pioneer-server:", error);
2050
- 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!");
2051
2132
  tokenDecimals = 18;
2052
2133
  }
2053
2134
  const tokenMultiplier = 10n ** BigInt(tokenDecimals);
@@ -2068,14 +2149,16 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2068
2149
  amountWei = tokenBalance;
2069
2150
  } else {
2070
2151
  amountWei = BigInt(Math.round(amount * Number(tokenMultiplier)));
2071
- console.log(tag5, "Token amount calculation:", {
2152
+ console.log(tag6, "Token amount calculation:", {
2072
2153
  inputAmount: amount,
2073
2154
  decimals: tokenDecimals,
2074
2155
  multiplier: tokenMultiplier,
2075
2156
  resultWei: amountWei.toString()
2076
2157
  });
2077
2158
  }
2078
- if (gasFee > balance) {
2159
+ const estimatedGasForCheck = BigInt(25000);
2160
+ const estimatedGasFee = gasPrice * estimatedGasForCheck;
2161
+ if (estimatedGasFee > balance) {
2079
2162
  throw new Error("Insufficient ETH balance to cover gas fees");
2080
2163
  }
2081
2164
  const data = encodeTransferData(to, amountWei);
@@ -2102,23 +2185,23 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2102
2185
  }
2103
2186
  if (pubkeyContext.addressNListMaster) {
2104
2187
  unsignedTx.addressNList = pubkeyContext.addressNListMaster;
2105
- 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);
2106
2189
  } else if (pubkeyContext.pathMaster) {
2107
2190
  unsignedTx.addressNList = import_pioneer_coins2.bip32ToAddressNList(pubkeyContext.pathMaster);
2108
- console.log(tag5, "✅ Converted pathMaster to addressNList:", pubkeyContext.pathMaster, "→", unsignedTx.addressNList);
2191
+ console.log(tag6, "✅ Converted pathMaster to addressNList:", pubkeyContext.pathMaster, "→", unsignedTx.addressNList);
2109
2192
  } else if (pubkeyContext.addressNList) {
2110
2193
  unsignedTx.addressNList = pubkeyContext.addressNList;
2111
- console.log(tag5, "✅ Using addressNList from pubkey context:", unsignedTx.addressNList);
2194
+ console.log(tag6, "✅ Using addressNList from pubkey context:", unsignedTx.addressNList);
2112
2195
  } else if (pubkeyContext.path) {
2113
2196
  unsignedTx.addressNList = import_pioneer_coins2.bip32ToAddressNList(pubkeyContext.path);
2114
- 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);
2115
2198
  } else {
2116
2199
  unsignedTx.addressNList = [2147483648 + 44, 2147483648 + 60, 2147483648, 0, 0];
2117
- 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");
2118
2201
  }
2119
2202
  return unsignedTx;
2120
2203
  } catch (error) {
2121
- console.error(tag5, "Error:", error.message);
2204
+ console.error(tag6, "Error:", error.message);
2122
2205
  throw error;
2123
2206
  }
2124
2207
  }
@@ -2127,7 +2210,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2127
2210
  var import_pioneer_caip2 = require("@pioneer-platform/pioneer-caip");
2128
2211
  var TAG2 = " | createUnsignedUxtoTx | ";
2129
2212
  async function createUnsignedRippleTx(caip, to, amount, memo, pubkeys, pioneer, pubkeyContext, isMax) {
2130
- let tag5 = TAG2 + " | createUnsignedRippleTx | ";
2213
+ let tag6 = TAG2 + " | createUnsignedRippleTx | ";
2131
2214
  try {
2132
2215
  if (!pioneer)
2133
2216
  throw new Error("Failed to init! pioneer");
@@ -2138,7 +2221,7 @@ async function createUnsignedRippleTx(caip, to, amount, memo, pubkeys, pioneer,
2138
2221
  if (!pubkeyContext.networks?.includes(networkId)) {
2139
2222
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
2140
2223
  }
2141
- console.log(tag5, `✅ Using pubkeyContext for network ${networkId}:`, {
2224
+ console.log(tag6, `✅ Using pubkeyContext for network ${networkId}:`, {
2142
2225
  address: pubkeyContext.address
2143
2226
  });
2144
2227
  const fromAddress = pubkeyContext.address || pubkeyContext.pubkey;
@@ -2206,7 +2289,7 @@ async function createUnsignedRippleTx(caip, to, amount, memo, pubkeys, pioneer,
2206
2289
  };
2207
2290
  return unsignedTx;
2208
2291
  } catch (error) {
2209
- console.error(tag5, "Error:", error);
2292
+ console.error(tag6, "Error:", error);
2210
2293
  throw error;
2211
2294
  }
2212
2295
  }
@@ -2346,7 +2429,7 @@ var thorchainDepositTemplate = (params) => ({
2346
2429
  // src/txbuilder/createUnsignedTendermintTx.ts
2347
2430
  var TAG3 = " | createUnsignedTendermintTx | ";
2348
2431
  async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pioneer, pubkeyContext, isMax, to) {
2349
- const tag5 = TAG3 + " | createUnsignedTendermintTx | ";
2432
+ const tag6 = TAG3 + " | createUnsignedTendermintTx | ";
2350
2433
  try {
2351
2434
  if (!pioneer)
2352
2435
  throw new Error("Failed to init! pioneer");
@@ -2357,7 +2440,7 @@ async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pio
2357
2440
  if (!pubkeyContext.networks?.includes(networkId)) {
2358
2441
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
2359
2442
  }
2360
- console.log(tag5, `✅ Using pubkeyContext for network ${networkId}:`, {
2443
+ console.log(tag6, `✅ Using pubkeyContext for network ${networkId}:`, {
2361
2444
  address: pubkeyContext.address,
2362
2445
  addressNList: pubkeyContext.addressNList || pubkeyContext.addressNListMaster
2363
2446
  });
@@ -2380,11 +2463,11 @@ async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pio
2380
2463
  }
2381
2464
  const fromAddress = pubkeyContext.address || pubkeyContext.pubkey;
2382
2465
  let asset = caip.split(":")[1];
2383
- console.log(tag5, `\uD83D\uDD0D Fetching account info for address: ${fromAddress}`);
2466
+ console.log(tag6, `\uD83D\uDD0D Fetching account info for address: ${fromAddress}`);
2384
2467
  const accountInfo = (await pioneer.GetAccountInfo({ network: chain, address: fromAddress })).data;
2385
- console.log(tag5, "\uD83D\uDCCB accountInfo:", JSON.stringify(accountInfo, null, 2));
2468
+ console.log(tag6, "\uD83D\uDCCB accountInfo:", JSON.stringify(accountInfo, null, 2));
2386
2469
  let balanceInfo = await pioneer.GetPubkeyBalance({ asset: chain, pubkey: fromAddress });
2387
- console.log(tag5, `\uD83D\uDCB0 balanceInfo:`, balanceInfo);
2470
+ console.log(tag6, `\uD83D\uDCB0 balanceInfo:`, balanceInfo);
2388
2471
  let account_number, sequence;
2389
2472
  if (accountInfo.account) {
2390
2473
  account_number = accountInfo.account.account_number || "0";
@@ -2395,13 +2478,13 @@ async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pio
2395
2478
  } else {
2396
2479
  throw new Error(`Unexpected account info format for ${networkId}: ${JSON.stringify(accountInfo)}`);
2397
2480
  }
2398
- 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}`);
2399
2482
  if (account_number === "0" || account_number === 0) {
2400
- console.log(tag5, `⚠️ WARNING: Account number is 0 from Pioneer API`);
2401
- console.log(tag5, ` This is likely due to stale Pioneer API cache`);
2402
- console.log(tag5, ` The mayachain-network module queries nodes directly but Pioneer API may be cached`);
2403
- console.log(tag5, ` Proceeding with account_number: 0 but transaction will likely fail`);
2404
- 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`);
2405
2488
  }
2406
2489
  const fees = {
2407
2490
  "cosmos:thorchain-mainnet-v1": 0.02,
@@ -2556,7 +2639,7 @@ async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pio
2556
2639
  }
2557
2640
  }
2558
2641
  } catch (error) {
2559
- console.error(tag5, "Error:", error);
2642
+ console.error(tag6, "Error:", error);
2560
2643
  throw error;
2561
2644
  }
2562
2645
  }
@@ -2585,7 +2668,7 @@ function getCoinTypeFromNetworkId(networkId) {
2585
2668
  return coinType;
2586
2669
  }
2587
2670
  async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pubkeyContext, isMax, feeLevel = 5, changeScriptType) {
2588
- let tag5 = " | createUnsignedUxtoTx | ";
2671
+ let tag6 = " | createUnsignedUxtoTx | ";
2589
2672
  try {
2590
2673
  if (!pioneer)
2591
2674
  throw Error("Failed to init! pioneer");
@@ -2596,7 +2679,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2596
2679
  if (!pubkeyContext.networks?.includes(networkId)) {
2597
2680
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
2598
2681
  }
2599
- console.log(tag5, `✅ Using pubkeyContext for network ${networkId}:`, {
2682
+ console.log(tag6, `✅ Using pubkeyContext for network ${networkId}:`, {
2600
2683
  address: pubkeyContext.address,
2601
2684
  scriptType: pubkeyContext.scriptType
2602
2685
  });
@@ -2607,15 +2690,15 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2607
2690
  const isSegwit = segwitNetworks.includes(networkId);
2608
2691
  let chain = import_pioneer_caip4.NetworkIdToChain[networkId];
2609
2692
  const coinType = getCoinTypeFromNetworkId(networkId);
2610
- console.log(`${tag5}: Using SLIP-44 coin type ${coinType} for ${chain}`);
2693
+ console.log(`${tag6}: Using SLIP-44 coin type ${coinType} for ${chain}`);
2611
2694
  const utxos = [];
2612
2695
  for (const pubkey of relevantPubkeys) {
2613
2696
  try {
2614
2697
  let utxosResp = await pioneer.ListUnspent({ network: chain, xpub: pubkey.pubkey });
2615
2698
  utxosResp = utxosResp.data;
2616
- 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");
2617
2700
  if (!utxosResp || !Array.isArray(utxosResp)) {
2618
- console.warn(`${tag5}: Invalid or empty UTXO response for ${pubkey.pubkey}`);
2701
+ console.warn(`${tag6}: Invalid or empty UTXO response for ${pubkey.pubkey}`);
2619
2702
  continue;
2620
2703
  }
2621
2704
  let scriptType = pubkey.scriptType;
@@ -2624,10 +2707,10 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2624
2707
  }
2625
2708
  utxos.push(...utxosResp);
2626
2709
  } catch (error) {
2627
- console.error(`${tag5}: Failed to fetch UTXOs for ${pubkey.pubkey}:`, error);
2710
+ console.error(`${tag6}: Failed to fetch UTXOs for ${pubkey.pubkey}:`, error);
2628
2711
  }
2629
2712
  }
2630
- console.log(`${tag5}: Total UTXOs collected:`, utxos.length);
2713
+ console.log(`${tag6}: Total UTXOs collected:`, utxos.length);
2631
2714
  if (!utxos || utxos.length === 0)
2632
2715
  throw Error("No UTXOs found across all addresses");
2633
2716
  for (const utxo of utxos) {
@@ -2640,14 +2723,14 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2640
2723
  }, {});
2641
2724
  const mostCommonInputType = Object.entries(scriptTypeCount).sort(([, a], [, b2]) => b2 - a)[0]?.[0] || "p2pkh";
2642
2725
  const actualChangeScriptType = changeScriptType || mostCommonInputType || relevantPubkeys[0]?.scriptType || "p2pkh";
2643
- console.log(`${tag5}: Input script types:`, scriptTypeCount);
2644
- 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})`);
2645
2728
  const changeXpubInfo = relevantPubkeys.find((pk) => pk.scriptType === actualChangeScriptType);
2646
2729
  if (!changeXpubInfo) {
2647
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.`);
2648
2731
  }
2649
2732
  const changeXpub = changeXpubInfo.pubkey;
2650
- 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) + "...");
2651
2734
  let changeAddressIndex = await pioneer.GetChangeAddress({
2652
2735
  network: chain,
2653
2736
  xpub: changeXpub
@@ -2667,7 +2750,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2667
2750
  break;
2668
2751
  }
2669
2752
  const path = bipPath;
2670
- 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})`);
2671
2754
  const changeAddress = {
2672
2755
  path,
2673
2756
  isChange: true,
@@ -2677,7 +2760,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2677
2760
  };
2678
2761
  let feeRateFromNode;
2679
2762
  if (networkId === "bip122:00000000001a91e3dace36e2be3bf030") {
2680
- console.log(`${tag5}: Using hardcoded fees for DOGE (10 sat/byte)`);
2763
+ console.log(`${tag6}: Using hardcoded fees for DOGE (10 sat/byte)`);
2681
2764
  feeRateFromNode = {
2682
2765
  slow: 10,
2683
2766
  average: 10,
@@ -2690,19 +2773,19 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2690
2773
  try {
2691
2774
  let feeResponse;
2692
2775
  if (pioneer.GetFeeRateByNetwork) {
2693
- console.log(`${tag5}: Trying GetFeeRateByNetwork for ${networkId}`);
2776
+ console.log(`${tag6}: Trying GetFeeRateByNetwork for ${networkId}`);
2694
2777
  feeResponse = await pioneer.GetFeeRateByNetwork({ networkId });
2695
2778
  } else {
2696
- console.log(`${tag5}: Using GetFeeRate for ${networkId}`);
2779
+ console.log(`${tag6}: Using GetFeeRate for ${networkId}`);
2697
2780
  feeResponse = await pioneer.GetFeeRate({ networkId });
2698
2781
  }
2699
2782
  feeRateFromNode = feeResponse.data;
2700
- 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));
2701
2784
  const conversionThreshold = 500;
2702
2785
  const needsConversion = feeRateFromNode.slow && feeRateFromNode.slow > conversionThreshold || feeRateFromNode.average && feeRateFromNode.average > conversionThreshold || feeRateFromNode.fast && feeRateFromNode.fast > conversionThreshold || feeRateFromNode.fastest && feeRateFromNode.fastest > conversionThreshold;
2703
2786
  if (needsConversion) {
2704
- console.warn(`${tag5}: Detected wrong units - values appear to be in sat/kB instead of sat/byte`);
2705
- 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:`, {
2706
2789
  slow: feeRateFromNode.slow,
2707
2790
  average: feeRateFromNode.average,
2708
2791
  fast: feeRateFromNode.fast,
@@ -2716,12 +2799,12 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2716
2799
  feeRateFromNode.fast = feeRateFromNode.fast / 1000;
2717
2800
  if (feeRateFromNode.fastest)
2718
2801
  feeRateFromNode.fastest = feeRateFromNode.fastest / 1000;
2719
- console.warn(`${tag5}: Converted to sat/byte:`, feeRateFromNode);
2802
+ console.warn(`${tag6}: Converted to sat/byte:`, feeRateFromNode);
2720
2803
  }
2721
2804
  if (!feeRateFromNode || typeof feeRateFromNode !== "object") {
2722
2805
  throw new Error(`Invalid fee rate response from API: ${JSON.stringify(feeRateFromNode)}`);
2723
2806
  }
2724
- console.log(`${tag5}: Available fee rates:`, {
2807
+ console.log(`${tag6}: Available fee rates:`, {
2725
2808
  slow: feeRateFromNode.slow,
2726
2809
  average: feeRateFromNode.average,
2727
2810
  fast: feeRateFromNode.fast,
@@ -2731,33 +2814,33 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2731
2814
  throw new Error(`No valid fee rates in API response: ${JSON.stringify(feeRateFromNode)}`);
2732
2815
  }
2733
2816
  } catch (error) {
2734
- 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);
2735
2818
  throw new Error(`Unable to get fee rate for network ${networkId}: ${error.message || "API unavailable"}`);
2736
2819
  }
2737
2820
  }
2738
2821
  let effectiveFeeRate;
2739
- console.log(`${tag5}: Using fee level ${feeLevel}`);
2822
+ console.log(`${tag6}: Using fee level ${feeLevel}`);
2740
2823
  switch (feeLevel) {
2741
2824
  case 1:
2742
2825
  case 2:
2743
2826
  effectiveFeeRate = feeRateFromNode.slow || feeRateFromNode.average;
2744
- console.log(`${tag5}: Using SLOW fee rate: ${effectiveFeeRate} sat/vB`);
2827
+ console.log(`${tag6}: Using SLOW fee rate: ${effectiveFeeRate} sat/vB`);
2745
2828
  break;
2746
2829
  case 3:
2747
2830
  case 4:
2748
2831
  effectiveFeeRate = feeRateFromNode.average || feeRateFromNode.fast;
2749
- console.log(`${tag5}: Using AVERAGE fee rate: ${effectiveFeeRate} sat/vB`);
2832
+ console.log(`${tag6}: Using AVERAGE fee rate: ${effectiveFeeRate} sat/vB`);
2750
2833
  break;
2751
2834
  case 5:
2752
2835
  effectiveFeeRate = feeRateFromNode.fastest || feeRateFromNode.fast;
2753
- console.log(`${tag5}: Using FASTEST fee rate: ${effectiveFeeRate} sat/vB`);
2836
+ console.log(`${tag6}: Using FASTEST fee rate: ${effectiveFeeRate} sat/vB`);
2754
2837
  break;
2755
2838
  default:
2756
2839
  throw new Error(`Invalid fee level: ${feeLevel}. Must be 1-5`);
2757
2840
  }
2758
2841
  if (!effectiveFeeRate)
2759
2842
  throw new Error("Unable to get fee rate for network");
2760
- console.log(`${tag5}: Using fee rate from API:`, {
2843
+ console.log(`${tag6}: Using fee rate from API:`, {
2761
2844
  feeLevel,
2762
2845
  selectedRate: effectiveFeeRate,
2763
2846
  description: feeLevel <= 2 ? "slow" : feeLevel <= 4 ? "average" : "fast"
@@ -2767,22 +2850,22 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2767
2850
  effectiveFeeRate = Math.ceil(effectiveFeeRate);
2768
2851
  const MIN_RELAY_FEE_RATE = 3;
2769
2852
  if (effectiveFeeRate < MIN_RELAY_FEE_RATE) {
2770
- 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`);
2771
2854
  effectiveFeeRate = MIN_RELAY_FEE_RATE;
2772
2855
  }
2773
- 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`);
2774
2857
  amount = parseInt(String(amount * 1e8));
2775
2858
  if (amount <= 0 && !isMax)
2776
2859
  throw Error("Invalid amount! 0");
2777
2860
  const totalBalance = utxos.reduce((sum, utxo) => sum + utxo.value, 0);
2778
- console.log(`${tag5}: Coin selection inputs:`, {
2861
+ console.log(`${tag6}: Coin selection inputs:`, {
2779
2862
  utxoCount: utxos.length,
2780
2863
  totalBalance: totalBalance / 1e8,
2781
2864
  requestedAmount: amount / 1e8,
2782
2865
  isMax,
2783
2866
  feeRate: effectiveFeeRate
2784
2867
  });
2785
- console.log(`${tag5}: UTXO details for coin selection:`, utxos.map((u) => ({
2868
+ console.log(`${tag6}: UTXO details for coin selection:`, utxos.map((u) => ({
2786
2869
  value: u.value,
2787
2870
  txid: u.txid?.substring(0, 10) + "...",
2788
2871
  vout: u.vout,
@@ -2796,8 +2879,8 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2796
2879
  } else {
2797
2880
  result = import_coinselect.default(utxos, [{ address: to, value: amount }], effectiveFeeRate);
2798
2881
  }
2799
- console.log(tag5, "coinSelect result object:", result);
2800
- 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);
2801
2884
  if (!result || !result.inputs) {
2802
2885
  const errorDetails = {
2803
2886
  utxoCount: utxos.length,
@@ -2806,7 +2889,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2806
2889
  feeRate: effectiveFeeRate,
2807
2890
  insufficientFunds: totalBalance < amount
2808
2891
  };
2809
- console.error(`${tag5}: Coin selection failed:`, errorDetails);
2892
+ console.error(`${tag6}: Coin selection failed:`, errorDetails);
2810
2893
  if (utxos.length === 0) {
2811
2894
  throw Error("No UTXOs available for coin selection");
2812
2895
  } else if (totalBalance < amount) {
@@ -2822,7 +2905,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2822
2905
  throw Error("Failed to create transaction: Missing outputs");
2823
2906
  if (fee === undefined)
2824
2907
  throw Error("Failed to calculate transaction fee");
2825
- console.log(`${tag5}: Transaction built with:`, {
2908
+ console.log(`${tag6}: Transaction built with:`, {
2826
2909
  feeLevel,
2827
2910
  effectiveFeeRate: `${effectiveFeeRate} sat/vB`,
2828
2911
  calculatedFee: `${fee} satoshis`,
@@ -2830,8 +2913,8 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2830
2913
  outputCount: outputs.length
2831
2914
  });
2832
2915
  const uniqueInputSet = new Set;
2833
- console.log(tag5, "inputs:", inputs);
2834
- console.log(tag5, "inputs:", inputs[0]);
2916
+ console.log(tag6, "inputs:", inputs);
2917
+ console.log(tag6, "inputs:", inputs[0]);
2835
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 }) => ({
2836
2919
  addressNList: import_pioneer_coins3.bip32ToAddressNList(path2),
2837
2920
  scriptType,
@@ -2939,7 +3022,7 @@ class TransactionManager {
2939
3022
  throw new Error(`Unsupported CAIP: ${caip}`);
2940
3023
  }
2941
3024
  async transfer({ caip, to, amount, memo, isMax = false, feeLevel = 5, changeScriptType }) {
2942
- let tag5 = TAG4 + " | transfer | ";
3025
+ let tag6 = TAG4 + " | transfer | ";
2943
3026
  try {
2944
3027
  if (!this.pioneer)
2945
3028
  throw Error("Failed to init! pioneer");
@@ -2977,12 +3060,12 @@ class TransactionManager {
2977
3060
  }
2978
3061
  return unsignedTx;
2979
3062
  } catch (e) {
2980
- console.error(tag5, e);
3063
+ console.error(tag6, e);
2981
3064
  throw e;
2982
3065
  }
2983
3066
  }
2984
3067
  async sign({ caip, unsignedTx }) {
2985
- let tag5 = TAG4 + " | sign | ";
3068
+ let tag6 = TAG4 + " | sign | ";
2986
3069
  try {
2987
3070
  if (!this.pioneer)
2988
3071
  throw Error("Failed to init! pioneer");
@@ -3068,20 +3151,20 @@ class TransactionManager {
3068
3151
  }
3069
3152
  case "cosmos:mayachain-mainnet-v1/slip44:931":
3070
3153
  case "cosmos:mayachain-mainnet-v1/denom:maya": {
3071
- console.log(tag5, "\uD83D\uDD0D ===== MAYACHAIN SIGNING AUDIT =====");
3072
- console.log(tag5, "\uD83D\uDCCB unsignedTx:", JSON.stringify(unsignedTx, null, 2));
3073
- console.log(tag5, "\uD83D\uDD11 unsignedTx.addressNList:", unsignedTx.addressNList);
3074
- console.log(tag5, "\uD83D\uDCCD unsignedTx.signerAddress:", unsignedTx.signerAddress);
3075
- console.log(tag5, "\uD83C\uDF10 pubkeyContext:", this.pubkeyContext);
3076
- console.log(tag5, "\uD83D\uDD10 pubkeyContext.addressNList:", this.pubkeyContext?.addressNList);
3077
- console.log(tag5, "\uD83D\uDD10 pubkeyContext.addressNListMaster:", this.pubkeyContext?.addressNListMaster);
3078
- console.log(tag5, "\uD83D\uDCEC pubkeyContext.address:", this.pubkeyContext?.address);
3079
- 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, "=======================================");
3080
3163
  if (unsignedTx.signDoc.msgs[0].type === "mayachain/MsgSend") {
3081
3164
  const responseSign = await this.keepKeySdk.mayachain.mayachainSignAminoTransfer(unsignedTx);
3082
3165
  signedTx = responseSign.serialized;
3083
- console.log(tag5, "✅ Signing completed");
3084
- console.log(tag5, "\uD83D\uDCE6 responseSign:", responseSign);
3166
+ console.log(tag6, "✅ Signing completed");
3167
+ console.log(tag6, "\uD83D\uDCE6 responseSign:", responseSign);
3085
3168
  } else if (unsignedTx.signDoc.msgs[0].type === "mayachain/MsgDeposit") {
3086
3169
  const responseSign = await this.keepKeySdk.mayachain.mayachainSignAminoDeposit(unsignedTx);
3087
3170
  signedTx = responseSign.serialized;
@@ -3103,11 +3186,11 @@ class TransactionManager {
3103
3186
  if (serialized.length > 140) {
3104
3187
  signedTx = serialized;
3105
3188
  } else {
3106
- console.error(tag5, "EIP155 signing returned incomplete transaction - only signature components");
3189
+ console.error(tag6, "EIP155 signing returned incomplete transaction - only signature components");
3107
3190
  throw new Error("KeepKey returned incomplete transaction - cannot reconstruct without r,s,v components");
3108
3191
  }
3109
3192
  } else {
3110
- 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);
3111
3194
  throw new Error("Failed to sign transaction - no valid signature in response");
3112
3195
  }
3113
3196
  break;
@@ -3128,19 +3211,19 @@ class TransactionManager {
3128
3211
  }
3129
3212
  }
3130
3213
  if (!signedTx) {
3131
- console.error(tag5, "CRITICAL ERROR: signedTx is missing after signing process");
3132
- console.error(tag5, "CAIP:", caip);
3133
- 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);
3134
3217
  throw Error("Failed to sign! missing signedTx");
3135
3218
  }
3136
3219
  return signedTx;
3137
3220
  } catch (e) {
3138
- console.error(tag5, e);
3221
+ console.error(tag6, e);
3139
3222
  throw e;
3140
3223
  }
3141
3224
  }
3142
3225
  async broadcast({ networkId, serialized }) {
3143
- let tag5 = TAG4 + " | broadcast | ";
3226
+ let tag6 = TAG4 + " | broadcast | ";
3144
3227
  try {
3145
3228
  if (!this.pioneer)
3146
3229
  throw Error("Failed to init! pioneer");
@@ -3154,7 +3237,7 @@ class TransactionManager {
3154
3237
  return result.txid;
3155
3238
  }
3156
3239
  } catch (e) {
3157
- console.error(tag5, e);
3240
+ console.error(tag6, e);
3158
3241
  throw e;
3159
3242
  }
3160
3243
  }
@@ -3274,7 +3357,7 @@ var cosmosClaimAllRewardsTemplate = (params) => ({
3274
3357
  // src/txbuilder/createUnsignedStakingTx.ts
3275
3358
  var TAG5 = " | createUnsignedStakingTx | ";
3276
3359
  async function createUnsignedStakingTx(caip, params, pubkeys, pioneer, pubkeyContext) {
3277
- const tag5 = TAG5 + " | createUnsignedStakingTx | ";
3360
+ const tag6 = TAG5 + " | createUnsignedStakingTx | ";
3278
3361
  try {
3279
3362
  if (!pioneer)
3280
3363
  throw new Error("Failed to init! pioneer");
@@ -3285,7 +3368,7 @@ async function createUnsignedStakingTx(caip, params, pubkeys, pioneer, pubkeyCon
3285
3368
  if (!pubkeyContext.networks?.includes(networkId)) {
3286
3369
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
3287
3370
  }
3288
- console.log(tag5, `✅ Using pubkeyContext for network ${networkId}:`, {
3371
+ console.log(tag6, `✅ Using pubkeyContext for network ${networkId}:`, {
3289
3372
  address: pubkeyContext.address
3290
3373
  });
3291
3374
  let chain;
@@ -3317,10 +3400,10 @@ async function createUnsignedStakingTx(caip, params, pubkeys, pioneer, pubkeyCon
3317
3400
  default:
3318
3401
  throw new Error(`Unsupported networkId for staking: ${networkId}`);
3319
3402
  }
3320
- console.log(tag5, `Building ${params.type} transaction for ${chain}`);
3403
+ console.log(tag6, `Building ${params.type} transaction for ${chain}`);
3321
3404
  const fromAddress = pubkeyContext.address || pubkeyContext.pubkey;
3322
3405
  const accountInfo = (await pioneer.GetAccountInfo({ network: chain, address: fromAddress })).data;
3323
- console.log(tag5, "accountInfo: ", accountInfo);
3406
+ console.log(tag6, "accountInfo: ", accountInfo);
3324
3407
  let account_number;
3325
3408
  let sequence;
3326
3409
  if (networkId === "cosmos:cosmoshub-4" || networkId === "cosmos:osmosis-1") {
@@ -3402,7 +3485,7 @@ async function createUnsignedStakingTx(caip, params, pubkeys, pioneer, pubkeyCon
3402
3485
  throw new Error(`Unsupported staking transaction type: ${params.type}`);
3403
3486
  }
3404
3487
  } catch (error) {
3405
- console.error(tag5, "Error:", error);
3488
+ console.error(tag6, "Error:", error);
3406
3489
  throw error;
3407
3490
  }
3408
3491
  }
@@ -3448,16 +3531,16 @@ function withTimeout(promise, timeoutMs) {
3448
3531
  ]);
3449
3532
  }
3450
3533
  async function getFees(pioneer, networkId) {
3451
- const tag5 = TAG6 + " | getFees | ";
3534
+ const tag6 = TAG6 + " | getFees | ";
3452
3535
  try {
3453
- console.log(tag5, `Fetching fees for network: ${networkId}`);
3536
+ console.log(tag6, `Fetching fees for network: ${networkId}`);
3454
3537
  const networkType = getNetworkType(networkId);
3455
3538
  if (networkType === "COSMOS") {
3456
- console.log(tag5, "Using hardcoded fees for Cosmos network:", networkId);
3539
+ console.log(tag6, "Using hardcoded fees for Cosmos network:", networkId);
3457
3540
  return getCosmosFees(networkId);
3458
3541
  }
3459
3542
  if (networkId === "bip122:00000000001a91e3dace36e2be3bf030") {
3460
- console.log(tag5, "Using hardcoded fees for Dogecoin: 10 sat/byte");
3543
+ console.log(tag6, "Using hardcoded fees for Dogecoin: 10 sat/byte");
3461
3544
  return {
3462
3545
  slow: {
3463
3546
  label: "Slow",
@@ -3494,7 +3577,7 @@ async function getFees(pioneer, networkId) {
3494
3577
  const apiCall = pioneer.GetFeeRateByNetwork ? pioneer.GetFeeRateByNetwork({ networkId }) : pioneer.GetFeeRate({ networkId });
3495
3578
  feeResponse = await withTimeout(apiCall, 3000);
3496
3579
  } catch (timeoutError) {
3497
- console.warn(tag5, "Dash fee API timeout, using fallback fees");
3580
+ console.warn(tag6, "Dash fee API timeout, using fallback fees");
3498
3581
  return {
3499
3582
  slow: {
3500
3583
  label: "Economy",
@@ -3532,17 +3615,17 @@ async function getFees(pioneer, networkId) {
3532
3615
  throw new Error(`No fee data returned for ${networkId}`);
3533
3616
  }
3534
3617
  const feeData = feeResponse.data;
3535
- console.log(tag5, "Raw fee data:", feeData);
3618
+ console.log(tag6, "Raw fee data:", feeData);
3536
3619
  const networkName = getNetworkName(networkId);
3537
3620
  let normalizedFees = normalizeFeeData(feeData, networkType, networkName, networkId);
3538
3621
  normalizedFees = ensureFeeDifferentiation(normalizedFees, networkType);
3539
3622
  normalizedFees.networkId = networkId;
3540
3623
  normalizedFees.networkType = networkType;
3541
3624
  normalizedFees.raw = feeData;
3542
- console.log(tag5, "Normalized fees:", normalizedFees);
3625
+ console.log(tag6, "Normalized fees:", normalizedFees);
3543
3626
  return normalizedFees;
3544
3627
  } catch (error) {
3545
- console.error(tag5, "Failed to fetch fees:", error);
3628
+ console.error(tag6, "Failed to fetch fees:", error);
3546
3629
  return getFallbackFees(networkId);
3547
3630
  }
3548
3631
  }
@@ -3851,7 +3934,7 @@ function estimateTransactionFee(feeRate, unit, networkType, txSize) {
3851
3934
 
3852
3935
  // src/utils/kkapi-detection.ts
3853
3936
  async function detectKkApiAvailability(forceLocalhost) {
3854
- const tag5 = " | detectKkApiAvailability | ";
3937
+ const tag6 = " | detectKkApiAvailability | ";
3855
3938
  try {
3856
3939
  const isTauri = typeof window !== "undefined" && "__TAURI__" in window;
3857
3940
  const isBrowser = typeof window !== "undefined";
@@ -3979,11 +4062,17 @@ function buildDashboardFromBalances(balances, blockchains, assetsMap) {
3979
4062
  return sum + balanceNum;
3980
4063
  }, 0).toString();
3981
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"}`);
3982
4070
  networksTemp.push({
3983
4071
  networkId: blockchain,
3984
4072
  totalValueUsd: networkTotal,
3985
4073
  gasAssetCaip: nativeAssetCaip || null,
3986
4074
  gasAssetSymbol: gasAsset?.ticker || gasAsset?.symbol || assetInfo?.symbol || null,
4075
+ gasAssetName: gasAsset?.name || assetInfo?.name || null,
3987
4076
  icon: gasAsset?.icon || assetInfo?.icon || null,
3988
4077
  color: gasAsset?.color || assetInfo?.color || null,
3989
4078
  totalNativeBalance
@@ -4003,11 +4092,11 @@ function buildDashboardFromBalances(balances, blockchains, assetsMap) {
4003
4092
  // src/utils/sync-market.ts
4004
4093
  var TAG8 = " | sync-market | ";
4005
4094
  async function syncMarket(balances, pioneer) {
4006
- const tag5 = `${TAG8} | syncMarket | `;
4095
+ const tag6 = `${TAG8} | syncMarket | `;
4007
4096
  try {
4008
4097
  const invalidBalances = balances.filter((b2) => !b2 || !b2.caip || typeof b2.caip !== "string" || !b2.caip.includes(":"));
4009
4098
  if (invalidBalances.length > 0) {
4010
- 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) => ({
4011
4100
  caip: b2?.caip,
4012
4101
  type: typeof b2?.caip,
4013
4102
  symbol: b2?.symbol,
@@ -4022,7 +4111,7 @@ async function syncMarket(balances, pioneer) {
4022
4111
  console.log("GetMarketInfo: payload length: ", allCaips.length);
4023
4112
  const invalidEntries = allCaips.filter((caip) => typeof caip !== "string");
4024
4113
  if (invalidEntries.length > 0) {
4025
- console.error(tag5, "CRITICAL: Invalid entries detected in allCaips:", invalidEntries);
4114
+ console.error(tag6, "CRITICAL: Invalid entries detected in allCaips:", invalidEntries);
4026
4115
  throw new Error("Invalid CAIP entries detected - aborting market sync");
4027
4116
  }
4028
4117
  if (allCaips && allCaips.length > 0) {
@@ -4043,13 +4132,13 @@ async function syncMarket(balances, pioneer) {
4043
4132
  }
4044
4133
  }
4045
4134
  } catch (apiError) {
4046
- console.error(tag5, "API error fetching market info:", apiError);
4047
- 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");
4048
4137
  }
4049
4138
  }
4050
4139
  return true;
4051
4140
  } catch (e) {
4052
- console.error(tag5, "e:", e);
4141
+ console.error(tag6, "e:", e);
4053
4142
  throw e;
4054
4143
  }
4055
4144
  }
@@ -4219,7 +4308,7 @@ class SDK {
4219
4308
  return true;
4220
4309
  };
4221
4310
  this.setPubkeys = (newPubkeys) => {
4222
- const tag5 = `${TAG9} | setPubkeys | `;
4311
+ const tag6 = `${TAG9} | setPubkeys | `;
4223
4312
  this.pubkeys = [];
4224
4313
  this.pubkeySet.clear();
4225
4314
  let added = 0;
@@ -4230,7 +4319,7 @@ class SDK {
4230
4319
  }
4231
4320
  };
4232
4321
  this.getUnifiedPortfolio = async function() {
4233
- const tag5 = `${TAG9} | getUnifiedPortfolio | `;
4322
+ const tag6 = `${TAG9} | getUnifiedPortfolio | `;
4234
4323
  try {
4235
4324
  const startTime = performance.now();
4236
4325
  try {
@@ -4241,17 +4330,17 @@ class SDK {
4241
4330
  signal: AbortSignal.timeout(2000)
4242
4331
  });
4243
4332
  if (!portfolioResponse.ok) {
4244
- console.warn(tag5, "Portfolio endpoint returned", portfolioResponse.status);
4333
+ console.warn(tag6, "Portfolio endpoint returned", portfolioResponse.status);
4245
4334
  return null;
4246
4335
  }
4247
4336
  const portfolioData = await portfolioResponse.json();
4248
4337
  const loadTime = performance.now() - startTime;
4249
4338
  if (!portfolioData.success) {
4250
- console.warn(tag5, "Portfolio API returned success=false");
4339
+ console.warn(tag6, "Portfolio API returned success=false");
4251
4340
  return null;
4252
4341
  }
4253
4342
  if (portfolioData.totalValueUsd === 0 || !portfolioData.totalValueUsd) {
4254
- 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");
4255
4344
  return null;
4256
4345
  }
4257
4346
  let allBalances = [];
@@ -4326,19 +4415,19 @@ class SDK {
4326
4415
  };
4327
4416
  } catch (fetchError) {
4328
4417
  if (fetchError.name === "AbortError") {
4329
- 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)");
4330
4419
  } else {
4331
- console.log(tag5, "Failed to fetch unified portfolio:", fetchError.message);
4420
+ console.log(tag6, "Failed to fetch unified portfolio:", fetchError.message);
4332
4421
  }
4333
4422
  return null;
4334
4423
  }
4335
4424
  } catch (e) {
4336
- console.error(tag5, "Error:", e);
4425
+ console.error(tag6, "Error:", e);
4337
4426
  return null;
4338
4427
  }
4339
4428
  };
4340
4429
  this.init = async function(walletsVerbose, setup) {
4341
- const tag5 = `${TAG9} | init | `;
4430
+ const tag6 = `${TAG9} | init | `;
4342
4431
  try {
4343
4432
  if (!this.username)
4344
4433
  throw Error("username required!");
@@ -4421,7 +4510,7 @@ class SDK {
4421
4510
  }
4422
4511
  return this.pioneer;
4423
4512
  } catch (e) {
4424
- console.error(tag5, "e: ", e);
4513
+ console.error(tag6, "e: ", e);
4425
4514
  throw e;
4426
4515
  }
4427
4516
  };
@@ -4432,7 +4521,7 @@ class SDK {
4432
4521
  return syncMarket(this.balances, this.pioneer);
4433
4522
  };
4434
4523
  this.sync = async function() {
4435
- const tag5 = `${TAG9} | sync | `;
4524
+ const tag6 = `${TAG9} | sync | `;
4436
4525
  try {
4437
4526
  const matchesNetwork = (item, networkId) => {
4438
4527
  if (!item.networks || !Array.isArray(item.networks))
@@ -4484,16 +4573,16 @@ class SDK {
4484
4573
  let totalPortfolioValue = 0;
4485
4574
  const networksTemp = [];
4486
4575
  const uniqueBlockchains = [...new Set(this.blockchains)];
4487
- console.log(tag5, "uniqueBlockchains: ", uniqueBlockchains);
4576
+ console.log(tag6, "uniqueBlockchains: ", uniqueBlockchains);
4488
4577
  for (const blockchain of uniqueBlockchains) {
4489
4578
  const filteredBalances = this.balances.filter((b2) => {
4490
4579
  const networkId = import_pioneer_caip7.caipToNetworkId(b2.caip);
4491
4580
  return networkId === blockchain || blockchain === "eip155:*" && networkId.startsWith("eip155:");
4492
4581
  });
4493
- console.log(tag5, `Filtering for blockchain: ${blockchain}`);
4494
- 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`);
4495
4584
  filteredBalances.forEach((balance, idx) => {
4496
- console.log(tag5, `Balance[${idx}]:`, {
4585
+ console.log(tag6, `Balance[${idx}]:`, {
4497
4586
  caip: balance.caip,
4498
4587
  pubkey: balance.pubkey,
4499
4588
  balance: balance.balance,
@@ -4503,7 +4592,7 @@ class SDK {
4503
4592
  const balanceMap = new Map;
4504
4593
  const isBitcoin = blockchain.includes("bip122:000000000019d6689c085ae165831e93");
4505
4594
  if (isBitcoin) {
4506
- console.log(tag5, "Bitcoin network detected - checking for duplicate balances");
4595
+ console.log(tag6, "Bitcoin network detected - checking for duplicate balances");
4507
4596
  const bitcoinByValue = new Map;
4508
4597
  filteredBalances.forEach((balance) => {
4509
4598
  const valueKey = `${balance.balance}_${balance.valueUsd}`;
@@ -4514,7 +4603,7 @@ class SDK {
4514
4603
  });
4515
4604
  for (const [valueKey, balances] of bitcoinByValue.entries()) {
4516
4605
  if (balances.length === 3 && parseFloat(balances[0].valueUsd || "0") > 0) {
4517
- 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");
4518
4607
  const xpubBalance = balances.find((b2) => b2.pubkey?.startsWith("xpub")) || balances[0];
4519
4608
  const key = `${xpubBalance.caip}_${xpubBalance.pubkey || "default"}`;
4520
4609
  balanceMap.set(key, xpubBalance);
@@ -4534,13 +4623,13 @@ class SDK {
4534
4623
  });
4535
4624
  }
4536
4625
  const networkBalances = Array.from(balanceMap.values());
4537
- console.log(tag5, "networkBalances (deduplicated): ", networkBalances);
4538
- console.log(tag5, "networkBalances count: ", networkBalances.length);
4626
+ console.log(tag6, "networkBalances (deduplicated): ", networkBalances);
4627
+ console.log(tag6, "networkBalances count: ", networkBalances.length);
4539
4628
  const networkTotal = networkBalances.reduce((sum, balance, idx) => {
4540
4629
  const valueUsd = typeof balance.valueUsd === "string" ? parseFloat(balance.valueUsd) : balance.valueUsd || 0;
4541
- 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);
4542
4631
  if (blockchain.includes("bip122:000000000019d6689c085ae165831e93")) {
4543
- 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);
4544
4633
  }
4545
4634
  return sum + valueUsd;
4546
4635
  }, 0);
@@ -4571,7 +4660,7 @@ class SDK {
4571
4660
  this.dashboard = dashboardData;
4572
4661
  return true;
4573
4662
  } catch (e) {
4574
- console.error(tag5, "Error in sync:", e);
4663
+ console.error(tag6, "Error in sync:", e);
4575
4664
  throw e;
4576
4665
  }
4577
4666
  };
@@ -4585,7 +4674,7 @@ class SDK {
4585
4674
  }
4586
4675
  };
4587
4676
  this.buildTx = async function(sendPayload) {
4588
- let tag5 = TAG9 + " | buildTx | ";
4677
+ let tag6 = TAG9 + " | buildTx | ";
4589
4678
  try {
4590
4679
  const transactionDependencies = {
4591
4680
  context: this.context,
@@ -4599,7 +4688,7 @@ class SDK {
4599
4688
  };
4600
4689
  let txManager = new TransactionManager(transactionDependencies, this.events);
4601
4690
  let unsignedTx = await txManager.transfer(sendPayload);
4602
- console.log(tag5, "unsignedTx: ", unsignedTx);
4691
+ console.log(tag6, "unsignedTx: ", unsignedTx);
4603
4692
  return unsignedTx;
4604
4693
  } catch (e) {
4605
4694
  console.error(e);
@@ -4607,14 +4696,14 @@ class SDK {
4607
4696
  }
4608
4697
  };
4609
4698
  this.buildDelegateTx = async function(caip, params) {
4610
- let tag5 = TAG9 + " | buildDelegateTx | ";
4699
+ let tag6 = TAG9 + " | buildDelegateTx | ";
4611
4700
  try {
4612
4701
  const delegateParams = {
4613
4702
  ...params,
4614
4703
  type: "delegate"
4615
4704
  };
4616
4705
  let unsignedTx = await createUnsignedStakingTx(caip, delegateParams, this.pubkeys, this.pioneer, this.pubkeyContext);
4617
- console.log(tag5, "unsignedTx: ", unsignedTx);
4706
+ console.log(tag6, "unsignedTx: ", unsignedTx);
4618
4707
  return unsignedTx;
4619
4708
  } catch (e) {
4620
4709
  console.error(e);
@@ -4622,14 +4711,14 @@ class SDK {
4622
4711
  }
4623
4712
  };
4624
4713
  this.buildUndelegateTx = async function(caip, params) {
4625
- let tag5 = TAG9 + " | buildUndelegateTx | ";
4714
+ let tag6 = TAG9 + " | buildUndelegateTx | ";
4626
4715
  try {
4627
4716
  const undelegateParams = {
4628
4717
  ...params,
4629
4718
  type: "undelegate"
4630
4719
  };
4631
4720
  let unsignedTx = await createUnsignedStakingTx(caip, undelegateParams, this.pubkeys, this.pioneer, this.pubkeyContext);
4632
- console.log(tag5, "unsignedTx: ", unsignedTx);
4721
+ console.log(tag6, "unsignedTx: ", unsignedTx);
4633
4722
  return unsignedTx;
4634
4723
  } catch (e) {
4635
4724
  console.error(e);
@@ -4637,14 +4726,14 @@ class SDK {
4637
4726
  }
4638
4727
  };
4639
4728
  this.buildClaimRewardsTx = async function(caip, params) {
4640
- let tag5 = TAG9 + " | buildClaimRewardsTx | ";
4729
+ let tag6 = TAG9 + " | buildClaimRewardsTx | ";
4641
4730
  try {
4642
4731
  const claimParams = {
4643
4732
  ...params,
4644
4733
  type: "claim_rewards"
4645
4734
  };
4646
4735
  let unsignedTx = await createUnsignedStakingTx(caip, claimParams, this.pubkeys, this.pioneer, this.pubkeyContext);
4647
- console.log(tag5, "unsignedTx: ", unsignedTx);
4736
+ console.log(tag6, "unsignedTx: ", unsignedTx);
4648
4737
  return unsignedTx;
4649
4738
  } catch (e) {
4650
4739
  console.error(e);
@@ -4652,7 +4741,7 @@ class SDK {
4652
4741
  }
4653
4742
  };
4654
4743
  this.buildClaimAllRewardsTx = async function(caip, params) {
4655
- let tag5 = TAG9 + " | buildClaimAllRewardsTx | ";
4744
+ let tag6 = TAG9 + " | buildClaimAllRewardsTx | ";
4656
4745
  try {
4657
4746
  const claimAllParams = {
4658
4747
  ...params,
@@ -4665,8 +4754,8 @@ class SDK {
4665
4754
  throw e;
4666
4755
  }
4667
4756
  };
4668
- this.signTx = async function(unsignedTx) {
4669
- let tag5 = TAG9 + " | signTx | ";
4757
+ this.signTx = async function(caip, unsignedTx) {
4758
+ let tag6 = TAG9 + " | signTx | ";
4670
4759
  try {
4671
4760
  const transactionDependencies = {
4672
4761
  context: this.context,
@@ -4679,7 +4768,7 @@ class SDK {
4679
4768
  keepKeySdk: this.keepKeySdk
4680
4769
  };
4681
4770
  let txManager = new TransactionManager(transactionDependencies, this.events);
4682
- let signedTx = await txManager.sign(unsignedTx);
4771
+ let signedTx = await txManager.sign({ caip, unsignedTx });
4683
4772
  return signedTx;
4684
4773
  } catch (e) {
4685
4774
  console.error(e);
@@ -4687,7 +4776,7 @@ class SDK {
4687
4776
  }
4688
4777
  };
4689
4778
  this.broadcastTx = async function(caip, signedTx) {
4690
- let tag5 = TAG9 + " | broadcastTx | ";
4779
+ let tag6 = TAG9 + " | broadcastTx | ";
4691
4780
  try {
4692
4781
  const transactionDependencies = {
4693
4782
  context: this.context,
@@ -4711,7 +4800,7 @@ class SDK {
4711
4800
  }
4712
4801
  };
4713
4802
  this.swap = async function(swapPayload) {
4714
- let tag5 = `${TAG9} | swap | `;
4803
+ let tag6 = `${TAG9} | swap | `;
4715
4804
  try {
4716
4805
  if (!swapPayload)
4717
4806
  throw Error("swapPayload required!");
@@ -4760,15 +4849,15 @@ class SDK {
4760
4849
  throw new Error(`Cannot use max amount: no balance found for ${swapPayload.caipIn}`);
4761
4850
  }
4762
4851
  let totalBalance = 0;
4763
- console.log(tag5, `Found ${inputBalances.length} balance entries for ${swapPayload.caipIn}`);
4852
+ console.log(tag6, `Found ${inputBalances.length} balance entries for ${swapPayload.caipIn}`);
4764
4853
  for (const balanceEntry of inputBalances) {
4765
4854
  const balance = parseFloat(balanceEntry.balance) || 0;
4766
4855
  totalBalance += balance;
4767
- console.log(tag5, ` - ${balanceEntry.pubkey || balanceEntry.identifier}: ${balance}`);
4856
+ console.log(tag6, ` - ${balanceEntry.pubkey || balanceEntry.identifier}: ${balance}`);
4768
4857
  }
4769
4858
  this.assetContext.balance = totalBalance.toString();
4770
4859
  this.assetContext.valueUsd = (totalBalance * parseFloat(this.assetContext.priceUsd || "0")).toFixed(2);
4771
- console.log(tag5, `Updated assetContext balance to aggregated total: ${totalBalance}`);
4860
+ console.log(tag6, `Updated assetContext balance to aggregated total: ${totalBalance}`);
4772
4861
  const feeReserves = {
4773
4862
  "bip122:000000000019d6689c085ae165831e93/slip44:0": 0.00005,
4774
4863
  "eip155:1/slip44:60": 0.001,
@@ -4779,7 +4868,7 @@ class SDK {
4779
4868
  };
4780
4869
  const reserve = feeReserves[swapPayload.caipIn] || 0.0001;
4781
4870
  inputAmount = Math.max(0, totalBalance - reserve);
4782
- 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})`);
4783
4872
  } else {
4784
4873
  inputAmount = typeof swapPayload.amount === "string" ? parseFloat(swapPayload.amount) : swapPayload.amount;
4785
4874
  if (isNaN(inputAmount) || inputAmount <= 0) {
@@ -4787,23 +4876,23 @@ class SDK {
4787
4876
  }
4788
4877
  }
4789
4878
  let quote = {
4790
- affiliate: "0x658DE0443259a1027caA976ef9a42E6982037A03",
4791
- sellAsset: this.assetContext,
4879
+ sellAsset: this.assetContext.caip,
4792
4880
  sellAmount: inputAmount.toPrecision(8),
4793
- buyAsset: this.outboundAssetContext,
4881
+ buyAsset: this.outboundAssetContext.caip,
4794
4882
  recipientAddress,
4795
4883
  senderAddress,
4796
- slippage: "3"
4884
+ slippage: swapPayload.slippagePercentage || 3
4797
4885
  };
4798
4886
  let result;
4799
4887
  try {
4800
4888
  result = await this.pioneer.Quote(quote);
4801
4889
  result = result.data;
4802
4890
  } catch (e) {
4803
- 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);
4804
4893
  }
4805
- if (result.length === 0)
4806
- 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);
4807
4896
  let selected = result[0];
4808
4897
  let txs = selected.quote.txs;
4809
4898
  if (!txs)
@@ -4816,6 +4905,7 @@ class SDK {
4816
4905
  balances: this.balances,
4817
4906
  pioneer: this.pioneer,
4818
4907
  pubkeys: this.pubkeys,
4908
+ pubkeyContext: this.pubkeyContext,
4819
4909
  nodes: this.nodes,
4820
4910
  keepKeySdk: this.keepKeySdk
4821
4911
  };
@@ -4823,7 +4913,10 @@ class SDK {
4823
4913
  let caip = swapPayload.caipIn;
4824
4914
  let unsignedTx;
4825
4915
  if (tx.type === "deposit") {
4826
- 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;
4827
4920
  } else {
4828
4921
  if (!tx.txParams.memo)
4829
4922
  throw Error("memo required on swaps!");
@@ -4841,12 +4934,12 @@ class SDK {
4841
4934
  return unsignedTx;
4842
4935
  }
4843
4936
  } catch (e) {
4844
- console.error(tag5, "Error: ", e);
4937
+ console.error(tag6, "Error: ", e);
4845
4938
  throw e;
4846
4939
  }
4847
4940
  };
4848
4941
  this.transfer = async function(sendPayload) {
4849
- let tag5 = `${TAG9} | transfer | `;
4942
+ let tag6 = `${TAG9} | transfer | `;
4850
4943
  try {
4851
4944
  if (!sendPayload)
4852
4945
  throw Error("sendPayload required!");
@@ -4880,15 +4973,15 @@ class SDK {
4880
4973
  return { txid, events: this.events };
4881
4974
  } catch (error) {
4882
4975
  if (error instanceof Error) {
4883
- 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);
4884
4977
  } else {
4885
- console.error(tag5, "An unknown error occurred during the transfer process");
4978
+ console.error(tag6, "An unknown error occurred during the transfer process");
4886
4979
  }
4887
4980
  throw error;
4888
4981
  }
4889
4982
  };
4890
4983
  this.followTransaction = async function(caip, txid) {
4891
- let tag5 = " | followTransaction | ";
4984
+ let tag6 = " | followTransaction | ";
4892
4985
  try {
4893
4986
  const finalConfirmationBlocksByCaip = {
4894
4987
  dogecoin: 3,
@@ -4918,7 +5011,7 @@ class SDK {
4918
5011
  }
4919
5012
  }
4920
5013
  } catch (error) {
4921
- console.error(tag5, "Error:", error);
5014
+ console.error(tag6, "Error:", error);
4922
5015
  }
4923
5016
  if (!isConfirmed) {
4924
5017
  await new Promise((resolve) => setTimeout(resolve, 8000));
@@ -4936,18 +5029,18 @@ class SDK {
4936
5029
  requiredConfirmations
4937
5030
  };
4938
5031
  } catch (error) {
4939
- console.error(tag5, "Error:", error);
5032
+ console.error(tag6, "Error:", error);
4940
5033
  throw new Error("Failed to follow transaction");
4941
5034
  }
4942
5035
  };
4943
5036
  this.setBlockchains = async function(blockchains) {
4944
- const tag5 = `${TAG9} | setBlockchains | `;
5037
+ const tag6 = `${TAG9} | setBlockchains | `;
4945
5038
  try {
4946
5039
  if (!blockchains)
4947
5040
  throw Error("blockchains required!");
4948
5041
  const uniqueBlockchains = [...new Set(blockchains)];
4949
5042
  if (blockchains.length !== uniqueBlockchains.length) {
4950
- console.warn(tag5, `Removed ${blockchains.length - uniqueBlockchains.length} duplicate blockchains`);
5043
+ console.warn(tag6, `Removed ${blockchains.length - uniqueBlockchains.length} duplicate blockchains`);
4951
5044
  }
4952
5045
  this.blockchains = uniqueBlockchains;
4953
5046
  this.events.emit("SET_BLOCKCHAINS", this.blockchains);
@@ -4957,7 +5050,7 @@ class SDK {
4957
5050
  }
4958
5051
  };
4959
5052
  this.addAsset = async function(caip, data) {
4960
- let tag5 = TAG9 + " | addAsset | ";
5053
+ let tag6 = TAG9 + " | addAsset | ";
4961
5054
  try {
4962
5055
  let success = false;
4963
5056
  if (!caip)
@@ -4995,22 +5088,22 @@ class SDK {
4995
5088
  }
4996
5089
  };
4997
5090
  this.clearWalletState = async function() {
4998
- const tag5 = `${TAG9} | clearWalletState | `;
5091
+ const tag6 = `${TAG9} | clearWalletState | `;
4999
5092
  try {
5000
5093
  this.context = null;
5001
5094
  this.paths = [];
5002
5095
  this.blockchains = [];
5003
5096
  this.pubkeys = [];
5004
5097
  this.pubkeySet.clear();
5005
- console.log(tag5, "Cleared wallet state including pubkeys and tracking set");
5098
+ console.log(tag6, "Cleared wallet state including pubkeys and tracking set");
5006
5099
  return true;
5007
5100
  } catch (e) {
5008
- console.error(tag5, "e: ", e);
5101
+ console.error(tag6, "e: ", e);
5009
5102
  throw e;
5010
5103
  }
5011
5104
  };
5012
5105
  this.addPath = async function(path) {
5013
- const tag5 = `${TAG9} | addPath | `;
5106
+ const tag6 = `${TAG9} | addPath | `;
5014
5107
  try {
5015
5108
  this.paths.push(path);
5016
5109
  const pubkey = await getPubkey(path.networks[0], path, this.keepKeySdk, this.context);
@@ -5019,14 +5112,14 @@ class SDK {
5019
5112
  this.buildDashboardFromBalances();
5020
5113
  return { success: true, pubkey };
5021
5114
  } catch (e) {
5022
- console.error(tag5, "Failed:", e);
5115
+ console.error(tag6, "Failed:", e);
5023
5116
  throw e;
5024
5117
  }
5025
5118
  };
5026
5119
  this.addPaths = async function(paths) {
5027
- const tag5 = `${TAG9} | addPaths | `;
5120
+ const tag6 = `${TAG9} | addPaths | `;
5028
5121
  try {
5029
- console.log(tag5, `Adding ${paths.length} paths in batch mode...`);
5122
+ console.log(tag6, `Adding ${paths.length} paths in batch mode...`);
5030
5123
  this.paths.push(...paths);
5031
5124
  const newPubkeys = [];
5032
5125
  for (const path of paths) {
@@ -5035,10 +5128,10 @@ class SDK {
5035
5128
  this.addPubkey(pubkey);
5036
5129
  newPubkeys.push(pubkey);
5037
5130
  } catch (error) {
5038
- 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);
5039
5132
  }
5040
5133
  }
5041
- console.log(tag5, `Successfully added ${newPubkeys.length} pubkeys`);
5134
+ console.log(tag6, `Successfully added ${newPubkeys.length} pubkeys`);
5042
5135
  const networkSet = new Set;
5043
5136
  for (const path of paths) {
5044
5137
  if (path.networks && Array.isArray(path.networks)) {
@@ -5046,13 +5139,13 @@ class SDK {
5046
5139
  }
5047
5140
  }
5048
5141
  const uniqueNetworks = [...networkSet];
5049
- 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...`);
5050
5143
  await this.getBalancesForNetworks(uniqueNetworks);
5051
5144
  this.buildDashboardFromBalances();
5052
- 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`);
5053
5146
  return { success: true, pubkeys: newPubkeys };
5054
5147
  } catch (e) {
5055
- console.error(tag5, "Failed:", e);
5148
+ console.error(tag6, "Failed:", e);
5056
5149
  throw e;
5057
5150
  }
5058
5151
  };
@@ -5060,7 +5153,7 @@ class SDK {
5060
5153
  return this.getGasAssets();
5061
5154
  };
5062
5155
  this.getGasAssets = async function() {
5063
- const tag5 = `${TAG9} | getGasAssets | `;
5156
+ const tag6 = `${TAG9} | getGasAssets | `;
5064
5157
  try {
5065
5158
  for (let i = 0;i < this.blockchains.length; i++) {
5066
5159
  let networkId = this.blockchains[i];
@@ -5094,7 +5187,7 @@ class SDK {
5094
5187
  denom: "maya"
5095
5188
  };
5096
5189
  this.assetsMap.set(mayaTokenCaip, mayaToken);
5097
- console.log(tag5, "Added MAYA token to assetsMap");
5190
+ console.log(tag6, "Added MAYA token to assetsMap");
5098
5191
  }
5099
5192
  return this.assetsMap;
5100
5193
  } catch (e) {
@@ -5103,7 +5196,7 @@ class SDK {
5103
5196
  }
5104
5197
  };
5105
5198
  this.getPubkeys = async function() {
5106
- const tag5 = `${TAG9} | getPubkeys | `;
5199
+ const tag6 = `${TAG9} | getPubkeys | `;
5107
5200
  try {
5108
5201
  if (this.paths.length === 0)
5109
5202
  throw new Error("No paths found!");
@@ -5119,15 +5212,15 @@ class SDK {
5119
5212
  return pubkeys;
5120
5213
  } catch (error) {
5121
5214
  console.error("Error in getPubkeys:", error);
5122
- console.error(tag5, "Error in getPubkeys:", error);
5215
+ console.error(tag6, "Error in getPubkeys:", error);
5123
5216
  throw error;
5124
5217
  }
5125
5218
  };
5126
5219
  this.getBalancesForNetworks = async function(networkIds) {
5127
- const tag5 = `${TAG9} | getBalancesForNetworks | `;
5220
+ const tag6 = `${TAG9} | getBalancesForNetworks | `;
5128
5221
  try {
5129
5222
  if (!this.pioneer) {
5130
- 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);
5131
5224
  throw new Error("Pioneer client not initialized. Call init() first.");
5132
5225
  }
5133
5226
  const assetQuery = [];
@@ -5165,48 +5258,48 @@ class SDK {
5165
5258
  identifier: `${balance.caip}:${balance.pubkey}`
5166
5259
  });
5167
5260
  }
5168
- console.log(tag5, "balances: ", balances);
5261
+ console.log(tag6, "balances: ", balances);
5169
5262
  this.balances = balances;
5170
5263
  this.events.emit("SET_BALANCES", this.balances);
5171
5264
  return this.balances;
5172
5265
  } catch (apiError) {
5173
- console.error(tag5, "GetPortfolioBalances API call failed:", apiError);
5266
+ console.error(tag6, "GetPortfolioBalances API call failed:", apiError);
5174
5267
  throw new Error(`GetPortfolioBalances API call failed: ${apiError?.message || "Unknown error"}`);
5175
5268
  }
5176
5269
  } catch (e) {
5177
- console.error(tag5, "Error: ", e);
5270
+ console.error(tag6, "Error: ", e);
5178
5271
  throw e;
5179
5272
  }
5180
5273
  };
5181
5274
  this.getBalances = async function() {
5182
- const tag5 = `${TAG9} | getBalances | `;
5275
+ const tag6 = `${TAG9} | getBalances | `;
5183
5276
  try {
5184
5277
  return await this.getBalancesForNetworks(this.blockchains);
5185
5278
  } catch (e) {
5186
- console.error(tag5, "Error in getBalances: ", e);
5279
+ console.error(tag6, "Error in getBalances: ", e);
5187
5280
  throw e;
5188
5281
  }
5189
5282
  };
5190
5283
  this.getBalance = async function(networkId) {
5191
- const tag5 = `${TAG9} | getBalance | `;
5284
+ const tag6 = `${TAG9} | getBalance | `;
5192
5285
  try {
5193
5286
  const results = await this.getBalancesForNetworks([networkId]);
5194
5287
  const filtered = results.filter(async (b2) => b2.networkId === await import_pioneer_caip7.networkIdToCaip(networkId));
5195
5288
  return filtered;
5196
5289
  } catch (e) {
5197
- console.error(tag5, "Error: ", e);
5290
+ console.error(tag6, "Error: ", e);
5198
5291
  throw e;
5199
5292
  }
5200
5293
  };
5201
5294
  this.getFees = async function(networkId) {
5202
- const tag5 = `${TAG9} | getFees | `;
5295
+ const tag6 = `${TAG9} | getFees | `;
5203
5296
  try {
5204
5297
  if (!this.pioneer) {
5205
5298
  throw new Error("Pioneer client not initialized. Call init() first.");
5206
5299
  }
5207
5300
  return await getFees(this.pioneer, networkId);
5208
5301
  } catch (e) {
5209
- console.error(tag5, "Error getting fees: ", e);
5302
+ console.error(tag6, "Error getting fees: ", e);
5210
5303
  throw e;
5211
5304
  }
5212
5305
  };
@@ -5214,11 +5307,11 @@ class SDK {
5214
5307
  return estimateTransactionFee(feeRate, unit, networkType, txSize);
5215
5308
  };
5216
5309
  this.getCharts = async function() {
5217
- const tag5 = `${TAG9} | getCharts | `;
5310
+ const tag6 = `${TAG9} | getCharts | `;
5218
5311
  try {
5219
- console.log(tag5, "Fetching charts");
5312
+ console.log(tag6, "Fetching charts");
5220
5313
  const newBalances = await getCharts(this.blockchains, this.pioneer, this.pubkeys, this.context);
5221
- console.log(tag5, "newBalances: ", newBalances);
5314
+ console.log(tag6, "newBalances: ", newBalances);
5222
5315
  const uniqueBalances = new Map([...this.balances, ...newBalances].map((balance) => [
5223
5316
  balance.identifier,
5224
5317
  {
@@ -5226,17 +5319,17 @@ class SDK {
5226
5319
  type: balance.type || "balance"
5227
5320
  }
5228
5321
  ]));
5229
- console.log(tag5, "uniqueBalances: ", uniqueBalances);
5322
+ console.log(tag6, "uniqueBalances: ", uniqueBalances);
5230
5323
  this.balances = Array.from(uniqueBalances.values());
5231
- console.log(tag5, "Updated this.balances: ", this.balances);
5324
+ console.log(tag6, "Updated this.balances: ", this.balances);
5232
5325
  return this.balances;
5233
5326
  } catch (e) {
5234
- console.error(tag5, "Error in getCharts:", e);
5327
+ console.error(tag6, "Error in getCharts:", e);
5235
5328
  throw e;
5236
5329
  }
5237
5330
  };
5238
5331
  this.setContext = async (context) => {
5239
- const tag5 = `${TAG9} | setContext | `;
5332
+ const tag6 = `${TAG9} | setContext | `;
5240
5333
  try {
5241
5334
  if (!context)
5242
5335
  throw Error("context required!");
@@ -5244,12 +5337,12 @@ class SDK {
5244
5337
  this.events.emit("SET_CONTEXT", context);
5245
5338
  return { success: true };
5246
5339
  } catch (e) {
5247
- console.error(tag5, "e: ", e);
5340
+ console.error(tag6, "e: ", e);
5248
5341
  return { success: false };
5249
5342
  }
5250
5343
  };
5251
5344
  this.setContextType = async (contextType) => {
5252
- const tag5 = `${TAG9} | setContextType | `;
5345
+ const tag6 = `${TAG9} | setContextType | `;
5253
5346
  try {
5254
5347
  if (!contextType)
5255
5348
  throw Error("contextType required!");
@@ -5257,22 +5350,22 @@ class SDK {
5257
5350
  this.events.emit("SET_CONTEXT_TYPE", contextType);
5258
5351
  return { success: true };
5259
5352
  } catch (e) {
5260
- console.error(tag5, "e: ", e);
5353
+ console.error(tag6, "e: ", e);
5261
5354
  return { success: false };
5262
5355
  }
5263
5356
  };
5264
5357
  this.refresh = async () => {
5265
- const tag5 = `${TAG9} | refresh | `;
5358
+ const tag6 = `${TAG9} | refresh | `;
5266
5359
  try {
5267
5360
  await this.sync();
5268
5361
  return this.balances;
5269
5362
  } catch (e) {
5270
- console.error(tag5, "e: ", e);
5363
+ console.error(tag6, "e: ", e);
5271
5364
  throw e;
5272
5365
  }
5273
5366
  };
5274
5367
  this.setAssetContext = async function(asset) {
5275
- const tag5 = `${TAG9} | setAssetContext | `;
5368
+ const tag6 = `${TAG9} | setAssetContext | `;
5276
5369
  try {
5277
5370
  if (!asset) {
5278
5371
  this.assetContext = null;
@@ -5284,7 +5377,7 @@ class SDK {
5284
5377
  asset.networkId = import_pioneer_caip7.caipToNetworkId(asset.caip);
5285
5378
  if (!this.pubkeys || this.pubkeys.length === 0) {
5286
5379
  const errorMsg = `Cannot set asset context for ${asset.caip} - no pubkeys loaded. Please initialize wallet first.`;
5287
- console.error(tag5, errorMsg);
5380
+ console.error(tag6, errorMsg);
5288
5381
  throw new Error(errorMsg);
5289
5382
  }
5290
5383
  const pubkeysForNetwork = this.pubkeys.filter((e) => {
@@ -5299,8 +5392,8 @@ class SDK {
5299
5392
  });
5300
5393
  if (pubkeysForNetwork.length === 0) {
5301
5394
  const errorMsg = `Cannot set asset context for ${asset.caip} - no address/xpub found for network ${asset.networkId}`;
5302
- console.error(tag5, errorMsg);
5303
- console.error(tag5, "Available networks in pubkeys:", [
5395
+ console.error(tag6, errorMsg);
5396
+ console.error(tag6, "Available networks in pubkeys:", [
5304
5397
  ...new Set(this.pubkeys.flatMap((p2) => p2.networks || []))
5305
5398
  ]);
5306
5399
  throw new Error(errorMsg);
@@ -5310,43 +5403,43 @@ class SDK {
5310
5403
  const xpubFound = pubkeysForNetwork.some((p2) => p2.type === "xpub" && p2.pubkey);
5311
5404
  if (!xpubFound) {
5312
5405
  const errorMsg = `Cannot set asset context for UTXO chain ${asset.caip} - xpub required but not found`;
5313
- console.error(tag5, errorMsg);
5406
+ console.error(tag6, errorMsg);
5314
5407
  throw new Error(errorMsg);
5315
5408
  }
5316
5409
  }
5317
5410
  const hasValidAddress = pubkeysForNetwork.some((p2) => p2.address || p2.master || p2.pubkey);
5318
5411
  if (!hasValidAddress) {
5319
5412
  const errorMsg = `Cannot set asset context for ${asset.caip} - no valid address found in pubkeys`;
5320
- console.error(tag5, errorMsg);
5413
+ console.error(tag6, errorMsg);
5321
5414
  throw new Error(errorMsg);
5322
5415
  }
5323
- console.log(tag5, `✅ Validated: Found ${pubkeysForNetwork.length} addresses for ${asset.networkId}`);
5416
+ console.log(tag6, `✅ Validated: Found ${pubkeysForNetwork.length} addresses for ${asset.networkId}`);
5324
5417
  let freshPriceUsd = 0;
5325
5418
  try {
5326
5419
  if (!asset.caip || typeof asset.caip !== "string" || !asset.caip.includes(":")) {
5327
- 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);
5328
5421
  } else {
5329
- console.log(tag5, "Fetching fresh market price for:", asset.caip);
5422
+ console.log(tag6, "Fetching fresh market price for:", asset.caip);
5330
5423
  const marketData = await this.pioneer.GetMarketInfo([asset.caip]);
5331
- console.log(tag5, "Market data response:", marketData);
5424
+ console.log(tag6, "Market data response:", marketData);
5332
5425
  if (marketData && marketData.data && marketData.data.length > 0) {
5333
5426
  freshPriceUsd = marketData.data[0];
5334
- console.log(tag5, "✅ Fresh market price:", freshPriceUsd);
5427
+ console.log(tag6, "✅ Fresh market price:", freshPriceUsd);
5335
5428
  } else {
5336
- console.warn(tag5, "No market data returned for:", asset.caip);
5429
+ console.warn(tag6, "No market data returned for:", asset.caip);
5337
5430
  }
5338
5431
  }
5339
5432
  } catch (marketError) {
5340
- console.error(tag5, "Error fetching market price:", marketError);
5433
+ console.error(tag6, "Error fetching market price:", marketError);
5341
5434
  }
5342
5435
  let assetInfo = this.assetsMap.get(asset.caip.toLowerCase());
5343
- console.log(tag5, "assetInfo: ", assetInfo);
5436
+ console.log(tag6, "assetInfo: ", assetInfo);
5344
5437
  let assetInfoDiscovery = import_pioneer_discovery2.assetData[asset.caip];
5345
- console.log(tag5, "assetInfoDiscovery: ", assetInfoDiscovery);
5438
+ console.log(tag6, "assetInfoDiscovery: ", assetInfoDiscovery);
5346
5439
  if (assetInfoDiscovery)
5347
5440
  assetInfo = assetInfoDiscovery;
5348
5441
  if (!assetInfo) {
5349
- console.log(tag5, "Building placeholder asset!");
5442
+ console.log(tag6, "Building placeholder asset!");
5350
5443
  assetInfo = {
5351
5444
  caip: asset.caip.toLowerCase(),
5352
5445
  networkId: asset.networkId,
@@ -5363,30 +5456,30 @@ class SDK {
5363
5456
  const valueUsd = parseFloat(matchingBalances[0].valueUsd);
5364
5457
  if (balance > 0 && valueUsd > 0) {
5365
5458
  priceValue = valueUsd / balance;
5366
- console.log(tag5, "calculated priceUsd from valueUsd/balance:", priceValue);
5459
+ console.log(tag6, "calculated priceUsd from valueUsd/balance:", priceValue);
5367
5460
  }
5368
5461
  }
5369
5462
  if (priceValue && priceValue > 0) {
5370
- console.log(tag5, "detected priceUsd from balance:", priceValue);
5463
+ console.log(tag6, "detected priceUsd from balance:", priceValue);
5371
5464
  assetInfo.priceUsd = priceValue;
5372
5465
  }
5373
5466
  }
5374
5467
  if (freshPriceUsd && freshPriceUsd > 0) {
5375
5468
  assetInfo.priceUsd = freshPriceUsd;
5376
- console.log(tag5, "✅ Using fresh market price:", freshPriceUsd);
5469
+ console.log(tag6, "✅ Using fresh market price:", freshPriceUsd);
5377
5470
  let totalBalance = 0;
5378
5471
  let totalValueUsd = 0;
5379
- console.log(tag5, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5472
+ console.log(tag6, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5380
5473
  for (const balanceEntry of matchingBalances) {
5381
5474
  const balance = parseFloat(balanceEntry.balance) || 0;
5382
5475
  const valueUsd = parseFloat(balanceEntry.valueUsd) || 0;
5383
5476
  totalBalance += balance;
5384
5477
  totalValueUsd += valueUsd;
5385
- console.log(tag5, ` Balance entry: ${balance} (${valueUsd} USD)`);
5478
+ console.log(tag6, ` Balance entry: ${balance} (${valueUsd} USD)`);
5386
5479
  }
5387
5480
  assetInfo.balance = totalBalance.toString();
5388
5481
  assetInfo.valueUsd = totalValueUsd.toFixed(2);
5389
- console.log(tag5, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5482
+ console.log(tag6, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5390
5483
  }
5391
5484
  const assetBalances = this.balances.filter((b2) => b2.caip === asset.caip);
5392
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")));
@@ -5406,7 +5499,7 @@ class SDK {
5406
5499
  const balanceAmount = parseFloat(balance.balance || 0);
5407
5500
  balance.valueUsd = (balanceAmount * freshPriceUsd).toString();
5408
5501
  }
5409
- console.log(tag5, "Updated all balances with fresh price data");
5502
+ console.log(tag6, "Updated all balances with fresh price data");
5410
5503
  }
5411
5504
  this.assetContext = finalAssetContext;
5412
5505
  if (asset.isToken || asset.type === "token" || assetInfo.isToken || assetInfo.type === "token") {
@@ -5458,20 +5551,20 @@ class SDK {
5458
5551
  const currentContextValid = this.pubkeyContext?.networks?.includes(networkId);
5459
5552
  if (!this.pubkeyContext || !currentContextValid) {
5460
5553
  this.pubkeyContext = assetPubkeys[0];
5461
- 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);
5462
5555
  } else {
5463
- 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(", ")}])`);
5464
5557
  }
5465
5558
  }
5466
5559
  this.events.emit("SET_ASSET_CONTEXT", this.assetContext);
5467
5560
  return this.assetContext;
5468
5561
  } catch (e) {
5469
- console.error(tag5, "e: ", e);
5562
+ console.error(tag6, "e: ", e);
5470
5563
  throw e;
5471
5564
  }
5472
5565
  };
5473
5566
  this.setPubkeyContext = async function(pubkey) {
5474
- let tag5 = `${TAG9} | setPubkeyContext | `;
5567
+ let tag6 = `${TAG9} | setPubkeyContext | `;
5475
5568
  try {
5476
5569
  if (!pubkey)
5477
5570
  throw Error("pubkey is required");
@@ -5479,31 +5572,31 @@ class SDK {
5479
5572
  throw Error("invalid pubkey: missing pubkey or address");
5480
5573
  const exists = this.pubkeys.some((pk) => pk.pubkey === pubkey.pubkey || pk.address === pubkey.address || pk.pubkey === pubkey.address);
5481
5574
  if (!exists) {
5482
- console.warn(tag5, "Pubkey not found in current pubkeys array");
5575
+ console.warn(tag6, "Pubkey not found in current pubkeys array");
5483
5576
  }
5484
5577
  this.pubkeyContext = pubkey;
5485
- 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);
5486
5579
  return true;
5487
5580
  } catch (e) {
5488
- console.error(tag5, "e: ", e);
5581
+ console.error(tag6, "e: ", e);
5489
5582
  throw e;
5490
5583
  }
5491
5584
  };
5492
5585
  this.setOutboundAssetContext = async function(asset) {
5493
- const tag5 = `${TAG9} | setOutputAssetContext | `;
5586
+ const tag6 = `${TAG9} | setOutputAssetContext | `;
5494
5587
  try {
5495
- console.log(tag5, "0. asset: ", asset);
5588
+ console.log(tag6, "0. asset: ", asset);
5496
5589
  if (!asset) {
5497
5590
  this.outboundAssetContext = null;
5498
5591
  return;
5499
5592
  }
5500
- console.log(tag5, "1 asset: ", asset);
5593
+ console.log(tag6, "1 asset: ", asset);
5501
5594
  if (!asset.caip)
5502
5595
  throw Error("Invalid Asset! missing caip!");
5503
5596
  if (!asset.networkId)
5504
5597
  asset.networkId = import_pioneer_caip7.caipToNetworkId(asset.caip);
5505
- console.log(tag5, "networkId: ", asset.networkId);
5506
- console.log(tag5, "this.pubkeys: ", this.pubkeys);
5598
+ console.log(tag6, "networkId: ", asset.networkId);
5599
+ console.log(tag6, "this.pubkeys: ", this.pubkeys);
5507
5600
  const pubkey = this.pubkeys.find((p2) => {
5508
5601
  if (!p2.networks || !Array.isArray(p2.networks))
5509
5602
  return false;
@@ -5518,23 +5611,23 @@ class SDK {
5518
5611
  let freshPriceUsd = 0;
5519
5612
  try {
5520
5613
  if (!asset.caip || typeof asset.caip !== "string" || !asset.caip.includes(":")) {
5521
- 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);
5522
5615
  } else {
5523
- console.log(tag5, "Fetching fresh market price for:", asset.caip);
5616
+ console.log(tag6, "Fetching fresh market price for:", asset.caip);
5524
5617
  const marketData = await this.pioneer.GetMarketInfo([asset.caip]);
5525
- console.log(tag5, "Market data response:", marketData);
5618
+ console.log(tag6, "Market data response:", marketData);
5526
5619
  if (marketData && marketData.data && marketData.data.length > 0) {
5527
5620
  freshPriceUsd = marketData.data[0];
5528
- console.log(tag5, "✅ Fresh market price:", freshPriceUsd);
5621
+ console.log(tag6, "✅ Fresh market price:", freshPriceUsd);
5529
5622
  } else {
5530
- console.warn(tag5, "No market data returned for:", asset.caip);
5623
+ console.warn(tag6, "No market data returned for:", asset.caip);
5531
5624
  }
5532
5625
  }
5533
5626
  } catch (marketError) {
5534
- console.error(tag5, "Error fetching market price:", marketError);
5627
+ console.error(tag6, "Error fetching market price:", marketError);
5535
5628
  }
5536
5629
  let assetInfo = this.assetsMap.get(asset.caip.toLowerCase());
5537
- console.log(tag5, "assetInfo: ", assetInfo);
5630
+ console.log(tag6, "assetInfo: ", assetInfo);
5538
5631
  if (!assetInfo) {
5539
5632
  assetInfo = {
5540
5633
  caip: asset.caip.toLowerCase(),
@@ -5552,45 +5645,45 @@ class SDK {
5552
5645
  const valueUsd = parseFloat(matchingBalances[0].valueUsd);
5553
5646
  if (balance > 0 && valueUsd > 0) {
5554
5647
  priceValue = valueUsd / balance;
5555
- console.log(tag5, "calculated priceUsd from valueUsd/balance:", priceValue);
5648
+ console.log(tag6, "calculated priceUsd from valueUsd/balance:", priceValue);
5556
5649
  }
5557
5650
  }
5558
5651
  if (priceValue && priceValue > 0) {
5559
- console.log(tag5, "detected priceUsd from balance:", priceValue);
5652
+ console.log(tag6, "detected priceUsd from balance:", priceValue);
5560
5653
  assetInfo.priceUsd = priceValue;
5561
5654
  }
5562
5655
  }
5563
5656
  if (freshPriceUsd && freshPriceUsd > 0) {
5564
5657
  assetInfo.priceUsd = freshPriceUsd;
5565
- console.log(tag5, "✅ Using fresh market price:", freshPriceUsd);
5658
+ console.log(tag6, "✅ Using fresh market price:", freshPriceUsd);
5566
5659
  let totalBalance = 0;
5567
5660
  let totalValueUsd = 0;
5568
- console.log(tag5, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5661
+ console.log(tag6, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5569
5662
  for (const balanceEntry of matchingBalances) {
5570
5663
  const balance = parseFloat(balanceEntry.balance) || 0;
5571
5664
  const valueUsd = parseFloat(balanceEntry.valueUsd) || 0;
5572
5665
  totalBalance += balance;
5573
5666
  totalValueUsd += valueUsd;
5574
- console.log(tag5, ` Balance entry: ${balance} (${valueUsd} USD)`);
5667
+ console.log(tag6, ` Balance entry: ${balance} (${valueUsd} USD)`);
5575
5668
  }
5576
5669
  assetInfo.balance = totalBalance.toString();
5577
5670
  assetInfo.valueUsd = totalValueUsd.toFixed(2);
5578
- console.log(tag5, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5671
+ console.log(tag6, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5579
5672
  }
5580
- console.log(tag5, "CHECKPOINT 1");
5673
+ console.log(tag6, "CHECKPOINT 1");
5581
5674
  this.outboundAssetContext = { ...assetInfo, ...asset, ...pubkey };
5582
- console.log(tag5, "CHECKPOINT 3");
5583
- console.log(tag5, "outboundAssetContext: assetInfo: ", assetInfo);
5675
+ console.log(tag6, "CHECKPOINT 3");
5676
+ console.log(tag6, "outboundAssetContext: assetInfo: ", assetInfo);
5584
5677
  if (asset.caip) {
5585
5678
  this.outboundBlockchainContext = import_pioneer_caip7.caipToNetworkId(asset.caip);
5586
5679
  } else if (asset.networkId) {
5587
5680
  this.outboundBlockchainContext = asset.networkId;
5588
5681
  }
5589
- console.log(tag5, "CHECKPOINT 4");
5682
+ console.log(tag6, "CHECKPOINT 4");
5590
5683
  this.events.emit("SET_OUTBOUND_ASSET_CONTEXT", this.outboundAssetContext);
5591
5684
  return this.outboundAssetContext;
5592
5685
  } catch (e) {
5593
- console.error(tag5, "e: ", e);
5686
+ console.error(tag6, "e: ", e);
5594
5687
  throw e;
5595
5688
  }
5596
5689
  };