@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.js CHANGED
@@ -243,7 +243,7 @@ var require_lib = __commonJS((exports) => {
243
243
  this.spec = spec;
244
244
  this.queryKey = config.queryKey;
245
245
  this.pioneer = {};
246
- this.timeout = config.queryKey || 45000;
246
+ this.timeout = config.timeout || 45000;
247
247
  }
248
248
  Pioneer2.prototype.init = function() {
249
249
  return __awaiter(this, undefined, undefined, function() {
@@ -837,21 +837,101 @@ function createBalanceIdentifier(caip, pubkey) {
837
837
  return `${caip}:${pubkey}`;
838
838
  }
839
839
 
840
+ // src/charts/custom-tokens.ts
841
+ var tag = "| charts-custom-tokens |";
842
+ async function fetchCustomTokens(params, balances) {
843
+ const { pioneer, pubkeys, blockchains, context } = params;
844
+ console.log(tag, "Fetching custom tokens...");
845
+ const evmPubkey = pubkeys.find((e) => e.networks && Array.isArray(e.networks) && e.networks.includes("eip155:*"));
846
+ const primaryAddress = evmPubkey?.address || evmPubkey?.master;
847
+ if (!primaryAddress) {
848
+ console.log(tag, "No EVM address found, skipping custom tokens");
849
+ return;
850
+ }
851
+ console.log(tag, "Using EVM address for custom tokens:", primaryAddress);
852
+ const supportedNetworks = blockchains.filter((net) => net.startsWith("eip155:"));
853
+ if (supportedNetworks.length === 0) {
854
+ console.log(tag, "No EVM networks for custom tokens");
855
+ return;
856
+ }
857
+ console.log(tag, `Checking custom tokens on ${supportedNetworks.length} networks`);
858
+ for (const networkId of supportedNetworks) {
859
+ try {
860
+ const response = await pioneer.GetCustomTokens({ networkId, address: primaryAddress });
861
+ const customTokens = response?.data?.tokens || [];
862
+ console.log(tag, `Found ${customTokens.length} custom tokens on ${networkId}`);
863
+ for (const token of customTokens) {
864
+ const chartBalance = processCustomToken(token, primaryAddress, context, blockchains);
865
+ if (chartBalance && !checkDuplicateBalance(balances, chartBalance.caip, chartBalance.pubkey)) {
866
+ balances.push(chartBalance);
867
+ console.log(tag, `Added custom token: ${chartBalance.symbol} = ${chartBalance.balance}`);
868
+ }
869
+ }
870
+ } catch (error) {
871
+ console.error(tag, `Error fetching custom tokens for ${networkId}:`, error.message);
872
+ }
873
+ }
874
+ console.log(tag, `Custom tokens complete. Total balances: ${balances.length}`);
875
+ }
876
+ function processCustomToken(token, primaryAddress, context, blockchains) {
877
+ if (!token.assetCaip || !token.networkId) {
878
+ return null;
879
+ }
880
+ let extractedNetworkId = token.networkId;
881
+ if (token.assetCaip.includes("/denom:")) {
882
+ const parts = token.assetCaip.split("/denom:");
883
+ if (parts.length > 0) {
884
+ extractedNetworkId = parts[0];
885
+ }
886
+ } else if (token.networkId && token.networkId.includes("/")) {
887
+ extractedNetworkId = token.networkId.split("/")[0];
888
+ }
889
+ const isEip155 = extractedNetworkId.startsWith("eip155:");
890
+ if (!isEip155 && !blockchains.includes(extractedNetworkId)) {
891
+ return null;
892
+ }
893
+ const tokenAssetInfo = hydrateAssetData(token.assetCaip);
894
+ const tokenPubkey = token.pubkey || primaryAddress;
895
+ const chartBalance = {
896
+ context,
897
+ chart: "pioneer",
898
+ contextType: context.split(":")[0],
899
+ name: tokenAssetInfo?.name || token.token?.name || "Unknown Custom Token",
900
+ caip: token.assetCaip,
901
+ icon: tokenAssetInfo?.icon || token.token?.icon || "",
902
+ pubkey: tokenPubkey,
903
+ ticker: tokenAssetInfo?.symbol || token.token?.symbol || "UNK",
904
+ ref: `${context}${token.assetCaip}`,
905
+ identifier: createBalanceIdentifier(token.assetCaip, tokenPubkey),
906
+ networkId: extractedNetworkId,
907
+ symbol: tokenAssetInfo?.symbol || token.token?.symbol || "UNK",
908
+ type: tokenAssetInfo?.type || "erc20",
909
+ token: true,
910
+ decimal: tokenAssetInfo?.decimal || token.token?.decimal,
911
+ balance: token.token?.balance?.toString() || "0",
912
+ priceUsd: token.token?.price || 0,
913
+ valueUsd: token.token?.balanceUSD || 0,
914
+ updated: new Date().getTime()
915
+ };
916
+ return chartBalance;
917
+ }
918
+
840
919
  // src/charts/evm.ts
841
- var tag = "| charts-evm |";
920
+ var tag2 = "| charts-evm |";
842
921
  async function getEvmCharts(params) {
843
922
  const { blockchains, pioneer, pubkeys, context } = params;
844
923
  const balances = [];
845
924
  const evmPubkey = pubkeys.find((e) => e.networks && Array.isArray(e.networks) && e.networks.includes("eip155:*"));
846
925
  const primaryAddress = evmPubkey?.address || evmPubkey?.master;
847
- console.log(tag, "Total pubkeys available:", pubkeys.length);
848
- console.log(tag, "Blockchains to process:", blockchains);
926
+ console.log(tag2, "Total pubkeys available:", pubkeys.length);
927
+ console.log(tag2, "Blockchains to process:", blockchains);
849
928
  if (!primaryAddress) {
850
- console.log(tag, "No EVM address found, skipping portfolio lookup (Zapper only supports Ethereum)");
929
+ console.log(tag2, "No EVM address found, skipping portfolio lookup (Zapper only supports Ethereum)");
851
930
  return balances;
852
931
  }
853
- console.log(tag, "Using EVM address for portfolio:", primaryAddress);
932
+ console.log(tag2, "Using EVM address for portfolio:", primaryAddress);
854
933
  await fetchStableCoins(pioneer, primaryAddress, blockchains, balances, context);
934
+ await fetchCustomTokens({ blockchains, pioneer, pubkeys, context }, balances);
855
935
  try {
856
936
  let portfolio = await pioneer.GetPortfolio({
857
937
  networkId: "eip155:1",
@@ -859,10 +939,10 @@ async function getEvmCharts(params) {
859
939
  });
860
940
  portfolio = portfolio.data?.data || portfolio.data;
861
941
  if (!portfolio || !portfolio.balances) {
862
- console.error(tag, "No portfolio.balances found:", portfolio);
942
+ console.error(tag2, "No portfolio.balances found:", portfolio);
863
943
  return balances;
864
944
  }
865
- console.log(tag, `Portfolio returned ${portfolio.balances.length} balances`);
945
+ console.log(tag2, `Portfolio returned ${portfolio.balances.length} balances`);
866
946
  let processedCount = 0;
867
947
  let skippedCount = 0;
868
948
  for (const balance of portfolio.balances) {
@@ -876,9 +956,9 @@ async function getEvmCharts(params) {
876
956
  skippedCount++;
877
957
  }
878
958
  }
879
- console.log(tag, `Processed ${processedCount} balances, skipped ${skippedCount}`);
959
+ console.log(tag2, `Processed ${processedCount} balances, skipped ${skippedCount}`);
880
960
  if (portfolio.tokens && portfolio.tokens.length > 0) {
881
- console.log(tag, "Processing portfolio.tokens:", portfolio.tokens.length);
961
+ console.log(tag2, "Processing portfolio.tokens:", portfolio.tokens.length);
882
962
  for (const token of portfolio.tokens) {
883
963
  const processedToken = processPortfolioToken(token, primaryAddress, context, blockchains);
884
964
  if (processedToken && !checkDuplicateBalance(balances, processedToken.caip, processedToken.pubkey)) {
@@ -887,13 +967,13 @@ async function getEvmCharts(params) {
887
967
  }
888
968
  }
889
969
  } catch (e) {
890
- console.error(tag, "Error fetching portfolio:", e);
970
+ console.error(tag2, "Error fetching portfolio:", e);
891
971
  }
892
972
  return balances;
893
973
  }
894
974
  function processPortfolioBalance(balance, primaryAddress, context, blockchains) {
895
975
  if (!balance.caip) {
896
- console.error(tag, "No caip found for:", balance);
976
+ console.error(tag2, "No caip found for:", balance);
897
977
  return null;
898
978
  }
899
979
  const networkId = balance.caip.split("/")[0];
@@ -911,7 +991,7 @@ function processPortfolioBalance(balance, primaryAddress, context, blockchains)
911
991
  const valueNum = parseFloat(balance.valueUsd.toString());
912
992
  if (balanceNum > 0 && valueNum > 0) {
913
993
  calculatedPrice = valueNum / balanceNum;
914
- console.log(tag, `Calculated price from value/balance: ${calculatedPrice} for ${balance.caip}`);
994
+ console.log(tag2, `Calculated price from value/balance: ${calculatedPrice} for ${balance.caip}`);
915
995
  }
916
996
  }
917
997
  const chartBalance = {
@@ -985,70 +1065,70 @@ function processPortfolioToken(token, primaryAddress, context, blockchains) {
985
1065
  return chartBalance;
986
1066
  }
987
1067
  async function fetchStableCoins(pioneer, primaryAddress, blockchains, balances, context) {
988
- console.log(tag, "Fetching stable coins for redundancy...");
1068
+ console.log(tag2, "Fetching stable coins for redundancy...");
989
1069
  const supportedNetworks = ["eip155:1", "eip155:137", "eip155:8453", "eip155:56"];
990
1070
  const networksToCheck = blockchains.filter((net) => supportedNetworks.includes(net));
991
1071
  if (networksToCheck.length === 0) {
992
- console.log(tag, "No supported networks for stable coins");
1072
+ console.log(tag2, "No supported networks for stable coins");
993
1073
  return;
994
1074
  }
995
- console.log(tag, `Checking stable coins on ${networksToCheck.length} networks`);
1075
+ console.log(tag2, `Checking stable coins on ${networksToCheck.length} networks`);
996
1076
  for (const networkId of networksToCheck) {
997
1077
  try {
998
1078
  const response = await pioneer.GetStableCoins({ networkId, address: primaryAddress });
999
1079
  const stableCoins = response?.data?.tokens || [];
1000
- console.log(tag, `Found ${stableCoins.length} stable coins on ${networkId}`);
1080
+ console.log(tag2, `Found ${stableCoins.length} stable coins on ${networkId}`);
1001
1081
  for (const token of stableCoins) {
1002
1082
  const chartBalance = processPortfolioToken(token, primaryAddress, context, blockchains);
1003
1083
  if (chartBalance && !checkDuplicateBalance(balances, chartBalance.caip, chartBalance.pubkey)) {
1004
1084
  balances.push(chartBalance);
1005
- console.log(tag, `Added stable coin: ${chartBalance.symbol} = ${chartBalance.balance}`);
1085
+ console.log(tag2, `Added stable coin: ${chartBalance.symbol} = ${chartBalance.balance}`);
1006
1086
  }
1007
1087
  }
1008
1088
  } catch (error) {
1009
- console.error(tag, `Error fetching stable coins for ${networkId}:`, error.message);
1089
+ console.error(tag2, `Error fetching stable coins for ${networkId}:`, error.message);
1010
1090
  }
1011
1091
  }
1012
- console.log(tag, `Stable coin redundancy complete. Total balances: ${balances.length}`);
1092
+ console.log(tag2, `Stable coin redundancy complete. Total balances: ${balances.length}`);
1013
1093
  }
1014
1094
 
1015
1095
  // src/charts/maya.ts
1016
- var tag2 = "| charts-maya |";
1096
+ var tag3 = "| charts-maya |";
1017
1097
  async function getMayaCharts(params, existingBalances) {
1018
1098
  const { blockchains, pioneer, pubkeys, context } = params;
1019
1099
  const balances = [];
1020
1100
  try {
1021
1101
  const mayaPubkey = pubkeys.find((p) => p.networks && Array.isArray(p.networks) && p.networks.includes("cosmos:mayachain-mainnet-v1"));
1022
1102
  if (!mayaPubkey || !mayaPubkey.address) {
1023
- console.log(tag2, "No MAYA pubkey found, skipping MAYA token fetch");
1103
+ console.log(tag3, "No MAYA pubkey found, skipping MAYA token fetch");
1024
1104
  return balances;
1025
1105
  }
1026
1106
  if (!blockchains.includes("cosmos:mayachain-mainnet-v1")) {
1027
- console.log(tag2, "MAYA network not in blockchains list, skipping MAYA token fetch");
1107
+ console.log(tag3, "MAYA network not in blockchains list, skipping MAYA token fetch");
1028
1108
  return balances;
1029
1109
  }
1030
1110
  const hasMayaToken = existingBalances.some((b2) => b2.caip === "cosmos:mayachain-mainnet-v1/denom:maya");
1031
1111
  if (hasMayaToken) {
1032
- console.log(tag2, "MAYA token already exists in balances, skipping");
1112
+ console.log(tag3, "MAYA token already exists in balances, skipping");
1033
1113
  return balances;
1034
1114
  }
1035
- console.log(tag2, "MAYA token not found in portfolio, fetching separately...");
1036
- console.log(tag2, "MAYA pubkey address:", mayaPubkey.address);
1115
+ console.log(tag3, "MAYA token not found in portfolio, fetching separately...");
1116
+ console.log(tag3, "MAYA pubkey address:", mayaPubkey.address);
1037
1117
  const mayaBalanceResponse = await pioneer.GetPortfolioBalances([
1038
1118
  {
1039
1119
  caip: "cosmos:mayachain-mainnet-v1/denom:maya",
1040
1120
  pubkey: mayaPubkey.address
1041
1121
  }
1042
1122
  ]);
1043
- console.log(tag2, "MAYA balance response:", JSON.stringify(mayaBalanceResponse?.data, null, 2));
1123
+ console.log(tag3, "MAYA balance response:", JSON.stringify(mayaBalanceResponse?.data, null, 2));
1044
1124
  if (!mayaBalanceResponse?.data || mayaBalanceResponse.data.length === 0) {
1045
- console.log(tag2, "No MAYA token balance returned from GetPortfolioBalances API");
1125
+ console.log(tag3, "No MAYA token balance returned from GetPortfolioBalances API");
1046
1126
  return balances;
1047
1127
  }
1048
- console.log(tag2, "Found MAYA token balances:", mayaBalanceResponse.data.length);
1128
+ console.log(tag3, "Found MAYA token balances:", mayaBalanceResponse.data.length);
1049
1129
  for (const mayaBalance of mayaBalanceResponse.data) {
1050
1130
  if (mayaBalance.caip !== "cosmos:mayachain-mainnet-v1/denom:maya") {
1051
- console.log(tag2, "Unexpected balance in MAYA response:", mayaBalance);
1131
+ console.log(tag3, "Unexpected balance in MAYA response:", mayaBalance);
1052
1132
  continue;
1053
1133
  }
1054
1134
  const mayaAssetInfo = hydrateAssetData(mayaBalance.caip);
@@ -1074,28 +1154,28 @@ async function getMayaCharts(params, existingBalances) {
1074
1154
  valueUsd: parseFloat(mayaBalance.valueUsd) || 0,
1075
1155
  updated: new Date().getTime()
1076
1156
  };
1077
- console.log(tag2, "Adding MAYA token to balances:", mayaTokenBalance);
1157
+ console.log(tag3, "Adding MAYA token to balances:", mayaTokenBalance);
1078
1158
  balances.push(mayaTokenBalance);
1079
1159
  }
1080
1160
  } catch (mayaError) {
1081
- console.error(tag2, "Error fetching MAYA token balance:", mayaError);
1161
+ console.error(tag3, "Error fetching MAYA token balance:", mayaError);
1082
1162
  }
1083
1163
  return balances;
1084
1164
  }
1085
1165
 
1086
1166
  // src/charts/cosmos-staking.ts
1087
- var tag3 = "| charts-cosmos-staking |";
1167
+ var tag4 = "| charts-cosmos-staking |";
1088
1168
  async function getCosmosStakingCharts(params) {
1089
1169
  const { blockchains, pioneer, pubkeys, context } = params;
1090
1170
  const balances = [];
1091
1171
  try {
1092
- console.log(tag3, "Adding Cosmos staking positions to charts...");
1172
+ console.log(tag4, "Adding Cosmos staking positions to charts...");
1093
1173
  const cosmosPubkeys = pubkeys.filter((p) => p.networks && Array.isArray(p.networks) && p.networks.some((n) => n.includes("cosmos:cosmoshub") || n.includes("cosmos:osmosis")));
1094
1174
  if (cosmosPubkeys.length === 0) {
1095
- console.log(tag3, "No cosmos pubkeys found for staking positions");
1175
+ console.log(tag4, "No cosmos pubkeys found for staking positions");
1096
1176
  return balances;
1097
1177
  }
1098
- console.log(tag3, "Found cosmos pubkeys for staking:", cosmosPubkeys.length);
1178
+ console.log(tag4, "Found cosmos pubkeys for staking:", cosmosPubkeys.length);
1099
1179
  for (const cosmosPubkey of cosmosPubkeys) {
1100
1180
  if (!cosmosPubkey.address) {
1101
1181
  continue;
@@ -1109,20 +1189,20 @@ async function getCosmosStakingCharts(params) {
1109
1189
  }
1110
1190
  }
1111
1191
  } catch (e) {
1112
- console.error(tag3, "Error adding cosmos staking positions:", e);
1192
+ console.error(tag4, "Error adding cosmos staking positions:", e);
1113
1193
  }
1114
1194
  return balances;
1115
1195
  }
1116
1196
  async function fetchStakingPositionsForNetwork(networkId, address, context, pioneer, balances) {
1117
1197
  try {
1118
- console.log(tag3, `Fetching staking positions for ${address} on ${networkId}...`);
1198
+ console.log(tag4, `Fetching staking positions for ${address} on ${networkId}...`);
1119
1199
  let network;
1120
1200
  if (networkId === "cosmos:cosmoshub-4") {
1121
1201
  network = "cosmos";
1122
1202
  } else if (networkId === "cosmos:osmosis-1") {
1123
1203
  network = "osmosis";
1124
1204
  } else {
1125
- console.error(tag3, `Unsupported networkId for staking: ${networkId}`);
1205
+ console.error(tag4, `Unsupported networkId for staking: ${networkId}`);
1126
1206
  return;
1127
1207
  }
1128
1208
  const stakingResponse = await pioneer.GetStakingPositions({
@@ -1130,15 +1210,15 @@ async function fetchStakingPositionsForNetwork(networkId, address, context, pion
1130
1210
  address
1131
1211
  });
1132
1212
  if (!stakingResponse?.data || !Array.isArray(stakingResponse.data)) {
1133
- console.log(tag3, `No staking positions found for ${address} on ${networkId}`);
1213
+ console.log(tag4, `No staking positions found for ${address} on ${networkId}`);
1134
1214
  return;
1135
1215
  }
1136
- console.log(tag3, `Found ${stakingResponse.data.length} staking positions for ${networkId}`);
1216
+ console.log(tag4, `Found ${stakingResponse.data.length} staking positions for ${networkId}`);
1137
1217
  for (const position of stakingResponse.data) {
1138
1218
  const processedPosition = processStakingPosition(position, address, context, networkId);
1139
1219
  if (processedPosition && !checkDuplicateBalance(balances, processedPosition.caip, processedPosition.pubkey, processedPosition.validator)) {
1140
1220
  balances.push(processedPosition);
1141
- console.log(tag3, `Added ${position.type} position:`, {
1221
+ console.log(tag4, `Added ${position.type} position:`, {
1142
1222
  balance: processedPosition.balance,
1143
1223
  ticker: processedPosition.ticker,
1144
1224
  valueUsd: processedPosition.valueUsd,
@@ -1147,7 +1227,7 @@ async function fetchStakingPositionsForNetwork(networkId, address, context, pion
1147
1227
  }
1148
1228
  }
1149
1229
  } catch (stakingError) {
1150
- console.error(tag3, `Error fetching staking positions for ${address} on ${networkId}:`, stakingError);
1230
+ console.error(tag4, `Error fetching staking positions for ${address} on ${networkId}:`, stakingError);
1151
1231
  }
1152
1232
  }
1153
1233
  function processStakingPosition(position, address, context, networkId) {
@@ -1182,11 +1262,11 @@ function processStakingPosition(position, address, context, networkId) {
1182
1262
  }
1183
1263
 
1184
1264
  // src/charts/index.ts
1185
- var tag4 = "| getCharts |";
1265
+ var tag5 = "| getCharts |";
1186
1266
  var getCharts = async (blockchains, pioneer, pubkeys, context) => {
1187
1267
  try {
1188
1268
  const balances = [];
1189
- console.log(tag4, "init");
1269
+ console.log(tag5, "init");
1190
1270
  const params = {
1191
1271
  blockchains,
1192
1272
  pioneer,
@@ -1201,7 +1281,7 @@ var getCharts = async (blockchains, pioneer, pubkeys, context) => {
1201
1281
  balances.push(...stakingBalances);
1202
1282
  return balances;
1203
1283
  } catch (error) {
1204
- console.error(tag4, "Error processing charts:", error);
1284
+ console.error(tag5, "Error processing charts:", error);
1205
1285
  throw error;
1206
1286
  }
1207
1287
  };
@@ -1983,7 +2063,7 @@ async function fetchTokenPriceInUsd(pioneer, caip) {
1983
2063
  }
1984
2064
  }
1985
2065
  async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pubkeyContext, isMax, feeLevel = 5) {
1986
- const tag5 = TAG + " | createUnsignedEvmTx | ";
2066
+ const tag6 = TAG + " | createUnsignedEvmTx | ";
1987
2067
  try {
1988
2068
  if (!pioneer)
1989
2069
  throw new Error("Failed to initialize Pioneer");
@@ -2004,11 +2084,11 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2004
2084
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
2005
2085
  }
2006
2086
  const address = pubkeyContext.address || pubkeyContext.pubkey;
2007
- console.log(tag5, "✅ Using FROM address from pubkeyContext:", address, "note:", pubkeyContext.note);
2087
+ console.log(tag6, "✅ Using FROM address from pubkeyContext:", address, "note:", pubkeyContext.note);
2008
2088
  if (!address)
2009
2089
  throw new Error("No address found for the specified network");
2010
2090
  const gasPriceData = await pioneer.GetGasPriceByNetwork({ networkId });
2011
- console.log(tag5, "Gas price data from API:", JSON.stringify(gasPriceData.data));
2091
+ console.log(tag6, "Gas price data from API:", JSON.stringify(gasPriceData.data));
2012
2092
  let gasPrice;
2013
2093
  const defaultGasPrices = {
2014
2094
  1: 30,
@@ -2024,74 +2104,75 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2024
2104
  let selectedGasPrice;
2025
2105
  if (feeLevel <= 2) {
2026
2106
  selectedGasPrice = gasPriceData.data.slow || gasPriceData.data.average || gasPriceData.data.fastest;
2027
- console.log(tag5, "Selecting SLOW gas price from API");
2107
+ console.log(tag6, "Selecting SLOW gas price from API");
2028
2108
  } else if (feeLevel >= 8) {
2029
2109
  selectedGasPrice = gasPriceData.data.fastest || gasPriceData.data.fast || gasPriceData.data.average;
2030
- console.log(tag5, "Selecting FAST gas price from API");
2110
+ console.log(tag6, "Selecting FAST gas price from API");
2031
2111
  } else {
2032
2112
  selectedGasPrice = gasPriceData.data.average || gasPriceData.data.fast || gasPriceData.data.fastest;
2033
- console.log(tag5, "Selecting AVERAGE gas price from API");
2113
+ console.log(tag6, "Selecting AVERAGE gas price from API");
2034
2114
  }
2035
2115
  let gasPriceNum;
2036
2116
  if (selectedGasPrice === undefined || selectedGasPrice === null) {
2037
- console.warn(tag5, "No valid gas price found in API response, using fallback:", fallbackGasGwei, "gwei");
2117
+ console.warn(tag6, "No valid gas price found in API response, using fallback:", fallbackGasGwei, "gwei");
2038
2118
  gasPriceNum = fallbackGasGwei;
2039
2119
  } else {
2040
2120
  gasPriceNum = typeof selectedGasPrice === "string" ? parseFloat(selectedGasPrice) : selectedGasPrice;
2041
2121
  if (isNaN(gasPriceNum) || !isFinite(gasPriceNum)) {
2042
- console.warn(tag5, "Invalid gas price (NaN or Infinite):", selectedGasPrice, "- using fallback:", fallbackGasGwei, "gwei");
2122
+ console.warn(tag6, "Invalid gas price (NaN or Infinite):", selectedGasPrice, "- using fallback:", fallbackGasGwei, "gwei");
2043
2123
  gasPriceNum = fallbackGasGwei;
2044
2124
  }
2045
2125
  }
2046
2126
  gasPrice = BigInt(Math.round(gasPriceNum * 1e9));
2047
2127
  if (gasPrice < MIN_GAS_PRICE_WEI) {
2048
- console.warn(tag5, "Gas price from API too low:", gasPrice.toString(), "wei - using minimum:", MIN_GAS_PRICE_WEI.toString());
2128
+ console.warn(tag6, "Gas price from API too low:", gasPrice.toString(), "wei - using minimum:", MIN_GAS_PRICE_WEI.toString());
2049
2129
  gasPrice = MIN_GAS_PRICE_WEI;
2050
2130
  }
2051
2131
  } else {
2052
2132
  let gasPriceNum;
2053
2133
  if (gasPriceData.data === undefined || gasPriceData.data === null) {
2054
- console.warn(tag5, "Gas price API returned null/undefined, using fallback:", fallbackGasGwei, "gwei");
2134
+ console.warn(tag6, "Gas price API returned null/undefined, using fallback:", fallbackGasGwei, "gwei");
2055
2135
  gasPriceNum = fallbackGasGwei;
2056
2136
  } else {
2057
2137
  gasPriceNum = typeof gasPriceData.data === "string" ? parseFloat(gasPriceData.data) : gasPriceData.data;
2058
2138
  if (isNaN(gasPriceNum) || !isFinite(gasPriceNum)) {
2059
- console.warn(tag5, "Invalid gas price (NaN or Infinite):", gasPriceData.data, "- using fallback:", fallbackGasGwei, "gwei");
2139
+ console.warn(tag6, "Invalid gas price (NaN or Infinite):", gasPriceData.data, "- using fallback:", fallbackGasGwei, "gwei");
2060
2140
  gasPriceNum = fallbackGasGwei;
2061
2141
  }
2062
2142
  }
2063
2143
  const baseGasPrice = BigInt(Math.round(gasPriceNum * 1e9));
2064
2144
  if (feeLevel <= 2) {
2065
2145
  gasPrice = baseGasPrice * BigInt(80) / BigInt(100);
2066
- console.log(tag5, "Using SLOW gas price (80% of base)");
2146
+ console.log(tag6, "Using SLOW gas price (80% of base)");
2067
2147
  } else if (feeLevel >= 8) {
2068
2148
  gasPrice = baseGasPrice * BigInt(150) / BigInt(100);
2069
- console.log(tag5, "Using FAST gas price (150% of base)");
2149
+ console.log(tag6, "Using FAST gas price (150% of base)");
2070
2150
  } else {
2071
2151
  gasPrice = baseGasPrice;
2072
- console.log(tag5, "Using AVERAGE gas price (100% of base)");
2152
+ console.log(tag6, "Using AVERAGE gas price (100% of base)");
2073
2153
  }
2074
2154
  if (gasPrice < MIN_GAS_PRICE_WEI) {
2075
- console.warn(tag5, "Gas price too low:", gasPrice.toString(), "wei - using minimum:", MIN_GAS_PRICE_WEI.toString());
2155
+ console.warn(tag6, "Gas price too low:", gasPrice.toString(), "wei - using minimum:", MIN_GAS_PRICE_WEI.toString());
2076
2156
  gasPrice = MIN_GAS_PRICE_WEI;
2077
2157
  }
2078
2158
  }
2079
- console.log(tag5, "Final gasPrice:", gasPrice.toString(), "wei (", Number(gasPrice) / 1e9, "gwei)");
2159
+ console.log(tag6, "Final gasPrice:", gasPrice.toString(), "wei (", Number(gasPrice) / 1e9, "gwei)");
2080
2160
  let nonce;
2081
2161
  try {
2082
2162
  const nonceData = await pioneer.GetNonceByNetwork({ networkId, address });
2083
2163
  nonce = nonceData.data.nonce;
2084
2164
  if (nonce === undefined || nonce === null) {
2085
- console.log(tag5, "No nonce found for address (likely fresh address), defaulting to 0");
2165
+ console.log(tag6, "No nonce found for address (likely fresh address), defaulting to 0");
2086
2166
  nonce = 0;
2087
2167
  }
2088
2168
  } catch (nonceError) {
2089
- console.log(tag5, "Failed to fetch nonce (likely fresh address):", nonceError.message, "- defaulting to 0");
2169
+ console.log(tag6, "Failed to fetch nonce (likely fresh address):", nonceError.message, "- defaulting to 0");
2090
2170
  nonce = 0;
2091
2171
  }
2092
2172
  const balanceData = await pioneer.GetBalanceAddressByNetwork({ networkId, address });
2093
- const balanceEth = parseFloat(balanceData.data.balance);
2173
+ const balanceEth = parseFloat(balanceData.data.nativeBalance || balanceData.data.balance || "0");
2094
2174
  const balance = BigInt(Math.round(balanceEth * 1000000000000000000));
2175
+ console.log(tag6, "Native ETH balance from API:", balanceData.data.nativeBalance || balanceData.data.balance, "ETH (", balance.toString(), "wei)");
2095
2176
  if (balance <= 0n)
2096
2177
  throw new Error("Wallet balance is zero");
2097
2178
  const assetType = classifyCaipEvm(caip);
@@ -2104,7 +2185,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2104
2185
  let gasLimit;
2105
2186
  if (isThorchainOperation) {
2106
2187
  gasLimit = BigInt(120000);
2107
- console.log(tag5, "Using higher gas limit for THORChain swap:", gasLimit.toString());
2188
+ console.log(tag6, "Using higher gas limit for THORChain swap:", gasLimit.toString());
2108
2189
  } else {
2109
2190
  gasLimit = chainId === 1 ? BigInt(21000) : BigInt(25000);
2110
2191
  }
@@ -2120,7 +2201,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2120
2201
  }
2121
2202
  const buffer = BigInt(100);
2122
2203
  amountWei = balance - gasFee - buffer;
2123
- console.log(tag5, "isMax calculation - balance:", balance.toString(), "gasFee:", gasFee.toString(), "buffer:", buffer.toString(), "amountWei:", amountWei.toString());
2204
+ console.log(tag6, "isMax calculation - balance:", balance.toString(), "gasFee:", gasFee.toString(), "buffer:", buffer.toString(), "amountWei:", amountWei.toString());
2124
2205
  } else {
2125
2206
  amountWei = BigInt(Math.round(amount * 1000000000000000000));
2126
2207
  if (amountWei + gasFee > balance) {
@@ -2130,14 +2211,14 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2130
2211
  const isThorchainSwap = memo && (memo.startsWith("=") || memo.startsWith("SWAP") || memo.includes(":"));
2131
2212
  let txData = "0x";
2132
2213
  if (isThorchainSwap) {
2133
- console.log(tag5, "Detected THORChain swap, encoding deposit data for memo:", memo);
2214
+ console.log(tag6, "Detected THORChain swap, encoding deposit data for memo:", memo);
2134
2215
  let fixedMemo = memo;
2135
2216
  if (memo.startsWith("=:b:") || memo.startsWith("=:btc:")) {
2136
2217
  fixedMemo = memo.replace(/^=:(b|btc):/, "=:BTC.BTC:");
2137
- console.log(tag5, "Fixed Bitcoin swap memo from:", memo, "to:", fixedMemo);
2218
+ console.log(tag6, "Fixed Bitcoin swap memo from:", memo, "to:", fixedMemo);
2138
2219
  } else if (memo.startsWith("=:e:") || memo.startsWith("=:eth:")) {
2139
2220
  fixedMemo = memo.replace(/^=:(e|eth):/, "=:ETH.ETH:");
2140
- console.log(tag5, "Fixed Ethereum swap memo from:", memo, "to:", fixedMemo);
2221
+ console.log(tag6, "Fixed Ethereum swap memo from:", memo, "to:", fixedMemo);
2141
2222
  }
2142
2223
  if (fixedMemo.length > 250) {
2143
2224
  throw new Error(`Memo too long for THORChain: ${fixedMemo.length} bytes (max 250)`);
@@ -2153,14 +2234,14 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2153
2234
  if (ethInbound) {
2154
2235
  vaultAddress = ethInbound.address;
2155
2236
  routerAddress = ethInbound.router || to;
2156
- console.log(tag5, "Using THORChain inbound addresses - vault:", vaultAddress, "router:", routerAddress);
2237
+ console.log(tag6, "Using THORChain inbound addresses - vault:", vaultAddress, "router:", routerAddress);
2157
2238
  to = routerAddress;
2158
2239
  } else {
2159
2240
  throw new Error("ETH inbound is halted or not found - cannot proceed with swap");
2160
2241
  }
2161
2242
  }
2162
2243
  } catch (fetchError) {
2163
- console.error(tag5, "Failed to fetch inbound addresses:", fetchError);
2244
+ console.error(tag6, "Failed to fetch inbound addresses:", fetchError);
2164
2245
  throw new Error(`Cannot proceed with THORChain swap - failed to fetch inbound addresses: ${fetchError.message}`);
2165
2246
  }
2166
2247
  if (vaultAddress === "0x0000000000000000000000000000000000000000") {
@@ -2180,7 +2261,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2180
2261
  const paddingLength = (32 - memoBytes.length % 32) % 32;
2181
2262
  const memoPadded = memoHex + "0".repeat(paddingLength * 2);
2182
2263
  txData = "0x" + functionSelector + vaultPadded + assetPadded + amountPadded + stringOffset + expiryPadded + stringLength + memoPadded;
2183
- console.log(tag5, "Encoded THORChain depositWithExpiry data:", {
2264
+ console.log(tag6, "Encoded THORChain depositWithExpiry data:", {
2184
2265
  functionSelector: "0x" + functionSelector,
2185
2266
  vault: vaultAddress,
2186
2267
  asset: assetAddress,
@@ -2190,9 +2271,9 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2190
2271
  stringOffset: "0x" + stringOffset,
2191
2272
  fullData: txData
2192
2273
  });
2193
- console.log(tag5, "Native ETH swap - value will be set to:", amountWei.toString(), "wei");
2274
+ console.log(tag6, "Native ETH swap - value will be set to:", amountWei.toString(), "wei");
2194
2275
  } catch (error) {
2195
- console.error(tag5, "Error encoding THORChain deposit:", error);
2276
+ console.error(tag6, "Error encoding THORChain deposit:", error);
2196
2277
  throw new Error(`Failed to encode THORChain swap: ${error.message}`);
2197
2278
  }
2198
2279
  } else if (memo) {
@@ -2211,19 +2292,19 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2211
2292
  }
2212
2293
  case "erc20": {
2213
2294
  const contractAddress = extractContractAddressFromCaip(caip);
2214
- console.log(tag5, "Fetching token decimals from contract:", contractAddress, "on network:", networkId);
2295
+ console.log(tag6, "Fetching token decimals from contract:", contractAddress, "on network:", networkId);
2215
2296
  let tokenDecimals;
2216
2297
  try {
2217
- console.log(tag5, "Fetching token decimals via pioneer-server API for", contractAddress, "on", networkId);
2298
+ console.log(tag6, "Fetching token decimals via pioneer-server API for", contractAddress, "on", networkId);
2218
2299
  const decimalsResponse = await pioneer.GetTokenDecimals({
2219
2300
  networkId,
2220
2301
  contractAddress
2221
2302
  });
2222
2303
  tokenDecimals = Number(decimalsResponse.data.decimals);
2223
- console.log(tag5, "✅ Fetched decimals from pioneer-server:", tokenDecimals);
2304
+ console.log(tag6, "✅ Fetched decimals from pioneer-server:", tokenDecimals);
2224
2305
  } catch (error) {
2225
- console.error(tag5, "Failed to fetch token decimals from pioneer-server:", error);
2226
- console.warn(tag5, "⚠️ FALLBACK: Using default 18 decimals - THIS MAY BE INCORRECT!");
2306
+ console.error(tag6, "Failed to fetch token decimals from pioneer-server:", error);
2307
+ console.warn(tag6, "⚠️ FALLBACK: Using default 18 decimals - THIS MAY BE INCORRECT!");
2227
2308
  tokenDecimals = 18;
2228
2309
  }
2229
2310
  const tokenMultiplier = 10n ** BigInt(tokenDecimals);
@@ -2244,14 +2325,16 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2244
2325
  amountWei = tokenBalance;
2245
2326
  } else {
2246
2327
  amountWei = BigInt(Math.round(amount * Number(tokenMultiplier)));
2247
- console.log(tag5, "Token amount calculation:", {
2328
+ console.log(tag6, "Token amount calculation:", {
2248
2329
  inputAmount: amount,
2249
2330
  decimals: tokenDecimals,
2250
2331
  multiplier: tokenMultiplier,
2251
2332
  resultWei: amountWei.toString()
2252
2333
  });
2253
2334
  }
2254
- if (gasFee > balance) {
2335
+ const estimatedGasForCheck = BigInt(25000);
2336
+ const estimatedGasFee = gasPrice * estimatedGasForCheck;
2337
+ if (estimatedGasFee > balance) {
2255
2338
  throw new Error("Insufficient ETH balance to cover gas fees");
2256
2339
  }
2257
2340
  const data = encodeTransferData(to, amountWei);
@@ -2278,23 +2361,23 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2278
2361
  }
2279
2362
  if (pubkeyContext.addressNListMaster) {
2280
2363
  unsignedTx.addressNList = pubkeyContext.addressNListMaster;
2281
- console.log(tag5, "✅ Using addressNListMaster from pubkey context:", unsignedTx.addressNList, "for address:", address);
2364
+ console.log(tag6, "✅ Using addressNListMaster from pubkey context:", unsignedTx.addressNList, "for address:", address);
2282
2365
  } else if (pubkeyContext.pathMaster) {
2283
2366
  unsignedTx.addressNList = bip32ToAddressNList(pubkeyContext.pathMaster);
2284
- console.log(tag5, "✅ Converted pathMaster to addressNList:", pubkeyContext.pathMaster, "→", unsignedTx.addressNList);
2367
+ console.log(tag6, "✅ Converted pathMaster to addressNList:", pubkeyContext.pathMaster, "→", unsignedTx.addressNList);
2285
2368
  } else if (pubkeyContext.addressNList) {
2286
2369
  unsignedTx.addressNList = pubkeyContext.addressNList;
2287
- console.log(tag5, "✅ Using addressNList from pubkey context:", unsignedTx.addressNList);
2370
+ console.log(tag6, "✅ Using addressNList from pubkey context:", unsignedTx.addressNList);
2288
2371
  } else if (pubkeyContext.path) {
2289
2372
  unsignedTx.addressNList = bip32ToAddressNList(pubkeyContext.path);
2290
- console.log(tag5, "⚠️ Using regular path (not master):", pubkeyContext.path, "→", unsignedTx.addressNList);
2373
+ console.log(tag6, "⚠️ Using regular path (not master):", pubkeyContext.path, "→", unsignedTx.addressNList);
2291
2374
  } else {
2292
2375
  unsignedTx.addressNList = [2147483648 + 44, 2147483648 + 60, 2147483648, 0, 0];
2293
- console.warn(tag5, "⚠️ No path info in pubkey context, using default account 0");
2376
+ console.warn(tag6, "⚠️ No path info in pubkey context, using default account 0");
2294
2377
  }
2295
2378
  return unsignedTx;
2296
2379
  } catch (error) {
2297
- console.error(tag5, "Error:", error.message);
2380
+ console.error(tag6, "Error:", error.message);
2298
2381
  throw error;
2299
2382
  }
2300
2383
  }
@@ -2303,7 +2386,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2303
2386
  import { caipToNetworkId as caipToNetworkId2 } from "@pioneer-platform/pioneer-caip";
2304
2387
  var TAG2 = " | createUnsignedUxtoTx | ";
2305
2388
  async function createUnsignedRippleTx(caip, to, amount, memo, pubkeys, pioneer, pubkeyContext, isMax) {
2306
- let tag5 = TAG2 + " | createUnsignedRippleTx | ";
2389
+ let tag6 = TAG2 + " | createUnsignedRippleTx | ";
2307
2390
  try {
2308
2391
  if (!pioneer)
2309
2392
  throw new Error("Failed to init! pioneer");
@@ -2314,7 +2397,7 @@ async function createUnsignedRippleTx(caip, to, amount, memo, pubkeys, pioneer,
2314
2397
  if (!pubkeyContext.networks?.includes(networkId)) {
2315
2398
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
2316
2399
  }
2317
- console.log(tag5, `✅ Using pubkeyContext for network ${networkId}:`, {
2400
+ console.log(tag6, `✅ Using pubkeyContext for network ${networkId}:`, {
2318
2401
  address: pubkeyContext.address
2319
2402
  });
2320
2403
  const fromAddress = pubkeyContext.address || pubkeyContext.pubkey;
@@ -2382,7 +2465,7 @@ async function createUnsignedRippleTx(caip, to, amount, memo, pubkeys, pioneer,
2382
2465
  };
2383
2466
  return unsignedTx;
2384
2467
  } catch (error) {
2385
- console.error(tag5, "Error:", error);
2468
+ console.error(tag6, "Error:", error);
2386
2469
  throw error;
2387
2470
  }
2388
2471
  }
@@ -2522,7 +2605,7 @@ var thorchainDepositTemplate = (params) => ({
2522
2605
  // src/txbuilder/createUnsignedTendermintTx.ts
2523
2606
  var TAG3 = " | createUnsignedTendermintTx | ";
2524
2607
  async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pioneer, pubkeyContext, isMax, to) {
2525
- const tag5 = TAG3 + " | createUnsignedTendermintTx | ";
2608
+ const tag6 = TAG3 + " | createUnsignedTendermintTx | ";
2526
2609
  try {
2527
2610
  if (!pioneer)
2528
2611
  throw new Error("Failed to init! pioneer");
@@ -2533,7 +2616,7 @@ async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pio
2533
2616
  if (!pubkeyContext.networks?.includes(networkId)) {
2534
2617
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
2535
2618
  }
2536
- console.log(tag5, `✅ Using pubkeyContext for network ${networkId}:`, {
2619
+ console.log(tag6, `✅ Using pubkeyContext for network ${networkId}:`, {
2537
2620
  address: pubkeyContext.address,
2538
2621
  addressNList: pubkeyContext.addressNList || pubkeyContext.addressNListMaster
2539
2622
  });
@@ -2556,11 +2639,11 @@ async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pio
2556
2639
  }
2557
2640
  const fromAddress = pubkeyContext.address || pubkeyContext.pubkey;
2558
2641
  let asset = caip.split(":")[1];
2559
- console.log(tag5, `\uD83D\uDD0D Fetching account info for address: ${fromAddress}`);
2642
+ console.log(tag6, `\uD83D\uDD0D Fetching account info for address: ${fromAddress}`);
2560
2643
  const accountInfo = (await pioneer.GetAccountInfo({ network: chain, address: fromAddress })).data;
2561
- console.log(tag5, "\uD83D\uDCCB accountInfo:", JSON.stringify(accountInfo, null, 2));
2644
+ console.log(tag6, "\uD83D\uDCCB accountInfo:", JSON.stringify(accountInfo, null, 2));
2562
2645
  let balanceInfo = await pioneer.GetPubkeyBalance({ asset: chain, pubkey: fromAddress });
2563
- console.log(tag5, `\uD83D\uDCB0 balanceInfo:`, balanceInfo);
2646
+ console.log(tag6, `\uD83D\uDCB0 balanceInfo:`, balanceInfo);
2564
2647
  let account_number, sequence;
2565
2648
  if (accountInfo.account) {
2566
2649
  account_number = accountInfo.account.account_number || "0";
@@ -2571,13 +2654,13 @@ async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pio
2571
2654
  } else {
2572
2655
  throw new Error(`Unexpected account info format for ${networkId}: ${JSON.stringify(accountInfo)}`);
2573
2656
  }
2574
- console.log(tag5, `\uD83D\uDCCA Extracted account_number: ${account_number}, sequence: ${sequence}`);
2657
+ console.log(tag6, `\uD83D\uDCCA Extracted account_number: ${account_number}, sequence: ${sequence}`);
2575
2658
  if (account_number === "0" || account_number === 0) {
2576
- console.log(tag5, `⚠️ WARNING: Account number is 0 from Pioneer API`);
2577
- console.log(tag5, ` This is likely due to stale Pioneer API cache`);
2578
- console.log(tag5, ` The mayachain-network module queries nodes directly but Pioneer API may be cached`);
2579
- console.log(tag5, ` Proceeding with account_number: 0 but transaction will likely fail`);
2580
- console.log(tag5, ` TODO: Fix Pioneer API to use fresh data from mayachain-network module`);
2659
+ console.log(tag6, `⚠️ WARNING: Account number is 0 from Pioneer API`);
2660
+ console.log(tag6, ` This is likely due to stale Pioneer API cache`);
2661
+ console.log(tag6, ` The mayachain-network module queries nodes directly but Pioneer API may be cached`);
2662
+ console.log(tag6, ` Proceeding with account_number: 0 but transaction will likely fail`);
2663
+ console.log(tag6, ` TODO: Fix Pioneer API to use fresh data from mayachain-network module`);
2581
2664
  }
2582
2665
  const fees = {
2583
2666
  "cosmos:thorchain-mainnet-v1": 0.02,
@@ -2732,7 +2815,7 @@ async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pio
2732
2815
  }
2733
2816
  }
2734
2817
  } catch (error) {
2735
- console.error(tag5, "Error:", error);
2818
+ console.error(tag6, "Error:", error);
2736
2819
  throw error;
2737
2820
  }
2738
2821
  }
@@ -2761,7 +2844,7 @@ function getCoinTypeFromNetworkId(networkId) {
2761
2844
  return coinType;
2762
2845
  }
2763
2846
  async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pubkeyContext, isMax, feeLevel = 5, changeScriptType) {
2764
- let tag5 = " | createUnsignedUxtoTx | ";
2847
+ let tag6 = " | createUnsignedUxtoTx | ";
2765
2848
  try {
2766
2849
  if (!pioneer)
2767
2850
  throw Error("Failed to init! pioneer");
@@ -2772,7 +2855,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2772
2855
  if (!pubkeyContext.networks?.includes(networkId)) {
2773
2856
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
2774
2857
  }
2775
- console.log(tag5, `✅ Using pubkeyContext for network ${networkId}:`, {
2858
+ console.log(tag6, `✅ Using pubkeyContext for network ${networkId}:`, {
2776
2859
  address: pubkeyContext.address,
2777
2860
  scriptType: pubkeyContext.scriptType
2778
2861
  });
@@ -2783,15 +2866,15 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2783
2866
  const isSegwit = segwitNetworks.includes(networkId);
2784
2867
  let chain = NetworkIdToChain[networkId];
2785
2868
  const coinType = getCoinTypeFromNetworkId(networkId);
2786
- console.log(`${tag5}: Using SLIP-44 coin type ${coinType} for ${chain}`);
2869
+ console.log(`${tag6}: Using SLIP-44 coin type ${coinType} for ${chain}`);
2787
2870
  const utxos = [];
2788
2871
  for (const pubkey of relevantPubkeys) {
2789
2872
  try {
2790
2873
  let utxosResp = await pioneer.ListUnspent({ network: chain, xpub: pubkey.pubkey });
2791
2874
  utxosResp = utxosResp.data;
2792
- console.log(`${tag5}: ListUnspent response for ${pubkey.scriptType}:`, utxosResp?.length || 0, "UTXOs");
2875
+ console.log(`${tag6}: ListUnspent response for ${pubkey.scriptType}:`, utxosResp?.length || 0, "UTXOs");
2793
2876
  if (!utxosResp || !Array.isArray(utxosResp)) {
2794
- console.warn(`${tag5}: Invalid or empty UTXO response for ${pubkey.pubkey}`);
2877
+ console.warn(`${tag6}: Invalid or empty UTXO response for ${pubkey.pubkey}`);
2795
2878
  continue;
2796
2879
  }
2797
2880
  let scriptType = pubkey.scriptType;
@@ -2800,10 +2883,10 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2800
2883
  }
2801
2884
  utxos.push(...utxosResp);
2802
2885
  } catch (error) {
2803
- console.error(`${tag5}: Failed to fetch UTXOs for ${pubkey.pubkey}:`, error);
2886
+ console.error(`${tag6}: Failed to fetch UTXOs for ${pubkey.pubkey}:`, error);
2804
2887
  }
2805
2888
  }
2806
- console.log(`${tag5}: Total UTXOs collected:`, utxos.length);
2889
+ console.log(`${tag6}: Total UTXOs collected:`, utxos.length);
2807
2890
  if (!utxos || utxos.length === 0)
2808
2891
  throw Error("No UTXOs found across all addresses");
2809
2892
  for (const utxo of utxos) {
@@ -2816,14 +2899,14 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2816
2899
  }, {});
2817
2900
  const mostCommonInputType = Object.entries(scriptTypeCount).sort(([, a2], [, b3]) => b3 - a2)[0]?.[0] || "p2pkh";
2818
2901
  const actualChangeScriptType = changeScriptType || mostCommonInputType || relevantPubkeys[0]?.scriptType || "p2pkh";
2819
- console.log(`${tag5}: Input script types:`, scriptTypeCount);
2820
- console.log(`${tag5}: Using change script type: ${actualChangeScriptType} (matches inputs: ${mostCommonInputType})`);
2902
+ console.log(`${tag6}: Input script types:`, scriptTypeCount);
2903
+ console.log(`${tag6}: Using change script type: ${actualChangeScriptType} (matches inputs: ${mostCommonInputType})`);
2821
2904
  const changeXpubInfo = relevantPubkeys.find((pk) => pk.scriptType === actualChangeScriptType);
2822
2905
  if (!changeXpubInfo) {
2823
2906
  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.`);
2824
2907
  }
2825
2908
  const changeXpub = changeXpubInfo.pubkey;
2826
- console.log(`${tag5}: Change xpub selected for ${actualChangeScriptType}:`, changeXpub?.substring(0, 10) + "...");
2909
+ console.log(`${tag6}: Change xpub selected for ${actualChangeScriptType}:`, changeXpub?.substring(0, 10) + "...");
2827
2910
  let changeAddressIndex = await pioneer.GetChangeAddress({
2828
2911
  network: chain,
2829
2912
  xpub: changeXpub
@@ -2843,7 +2926,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2843
2926
  break;
2844
2927
  }
2845
2928
  const path = bipPath;
2846
- console.log(`${tag5}: Change address path: ${path} (coin type: ${coinType}, index: ${changeAddressIndex})`);
2929
+ console.log(`${tag6}: Change address path: ${path} (coin type: ${coinType}, index: ${changeAddressIndex})`);
2847
2930
  const changeAddress = {
2848
2931
  path,
2849
2932
  isChange: true,
@@ -2853,7 +2936,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2853
2936
  };
2854
2937
  let feeRateFromNode;
2855
2938
  if (networkId === "bip122:00000000001a91e3dace36e2be3bf030") {
2856
- console.log(`${tag5}: Using hardcoded fees for DOGE (10 sat/byte)`);
2939
+ console.log(`${tag6}: Using hardcoded fees for DOGE (10 sat/byte)`);
2857
2940
  feeRateFromNode = {
2858
2941
  slow: 10,
2859
2942
  average: 10,
@@ -2866,19 +2949,19 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2866
2949
  try {
2867
2950
  let feeResponse;
2868
2951
  if (pioneer.GetFeeRateByNetwork) {
2869
- console.log(`${tag5}: Trying GetFeeRateByNetwork for ${networkId}`);
2952
+ console.log(`${tag6}: Trying GetFeeRateByNetwork for ${networkId}`);
2870
2953
  feeResponse = await pioneer.GetFeeRateByNetwork({ networkId });
2871
2954
  } else {
2872
- console.log(`${tag5}: Using GetFeeRate for ${networkId}`);
2955
+ console.log(`${tag6}: Using GetFeeRate for ${networkId}`);
2873
2956
  feeResponse = await pioneer.GetFeeRate({ networkId });
2874
2957
  }
2875
2958
  feeRateFromNode = feeResponse.data;
2876
- console.log(`${tag5}: Got fee rates from API:`, JSON.stringify(feeRateFromNode, null, 2));
2959
+ console.log(`${tag6}: Got fee rates from API:`, JSON.stringify(feeRateFromNode, null, 2));
2877
2960
  const conversionThreshold = 500;
2878
2961
  const needsConversion = feeRateFromNode.slow && feeRateFromNode.slow > conversionThreshold || feeRateFromNode.average && feeRateFromNode.average > conversionThreshold || feeRateFromNode.fast && feeRateFromNode.fast > conversionThreshold || feeRateFromNode.fastest && feeRateFromNode.fastest > conversionThreshold;
2879
2962
  if (needsConversion) {
2880
- console.warn(`${tag5}: Detected wrong units - values appear to be in sat/kB instead of sat/byte`);
2881
- console.warn(`${tag5}: Original values:`, {
2963
+ console.warn(`${tag6}: Detected wrong units - values appear to be in sat/kB instead of sat/byte`);
2964
+ console.warn(`${tag6}: Original values:`, {
2882
2965
  slow: feeRateFromNode.slow,
2883
2966
  average: feeRateFromNode.average,
2884
2967
  fast: feeRateFromNode.fast,
@@ -2892,12 +2975,12 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2892
2975
  feeRateFromNode.fast = feeRateFromNode.fast / 1000;
2893
2976
  if (feeRateFromNode.fastest)
2894
2977
  feeRateFromNode.fastest = feeRateFromNode.fastest / 1000;
2895
- console.warn(`${tag5}: Converted to sat/byte:`, feeRateFromNode);
2978
+ console.warn(`${tag6}: Converted to sat/byte:`, feeRateFromNode);
2896
2979
  }
2897
2980
  if (!feeRateFromNode || typeof feeRateFromNode !== "object") {
2898
2981
  throw new Error(`Invalid fee rate response from API: ${JSON.stringify(feeRateFromNode)}`);
2899
2982
  }
2900
- console.log(`${tag5}: Available fee rates:`, {
2983
+ console.log(`${tag6}: Available fee rates:`, {
2901
2984
  slow: feeRateFromNode.slow,
2902
2985
  average: feeRateFromNode.average,
2903
2986
  fast: feeRateFromNode.fast,
@@ -2907,33 +2990,33 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2907
2990
  throw new Error(`No valid fee rates in API response: ${JSON.stringify(feeRateFromNode)}`);
2908
2991
  }
2909
2992
  } catch (error) {
2910
- console.error(`${tag5}: Failed to get fee rates from Pioneer API:`, error.message || error);
2993
+ console.error(`${tag6}: Failed to get fee rates from Pioneer API:`, error.message || error);
2911
2994
  throw new Error(`Unable to get fee rate for network ${networkId}: ${error.message || "API unavailable"}`);
2912
2995
  }
2913
2996
  }
2914
2997
  let effectiveFeeRate;
2915
- console.log(`${tag5}: Using fee level ${feeLevel}`);
2998
+ console.log(`${tag6}: Using fee level ${feeLevel}`);
2916
2999
  switch (feeLevel) {
2917
3000
  case 1:
2918
3001
  case 2:
2919
3002
  effectiveFeeRate = feeRateFromNode.slow || feeRateFromNode.average;
2920
- console.log(`${tag5}: Using SLOW fee rate: ${effectiveFeeRate} sat/vB`);
3003
+ console.log(`${tag6}: Using SLOW fee rate: ${effectiveFeeRate} sat/vB`);
2921
3004
  break;
2922
3005
  case 3:
2923
3006
  case 4:
2924
3007
  effectiveFeeRate = feeRateFromNode.average || feeRateFromNode.fast;
2925
- console.log(`${tag5}: Using AVERAGE fee rate: ${effectiveFeeRate} sat/vB`);
3008
+ console.log(`${tag6}: Using AVERAGE fee rate: ${effectiveFeeRate} sat/vB`);
2926
3009
  break;
2927
3010
  case 5:
2928
3011
  effectiveFeeRate = feeRateFromNode.fastest || feeRateFromNode.fast;
2929
- console.log(`${tag5}: Using FASTEST fee rate: ${effectiveFeeRate} sat/vB`);
3012
+ console.log(`${tag6}: Using FASTEST fee rate: ${effectiveFeeRate} sat/vB`);
2930
3013
  break;
2931
3014
  default:
2932
3015
  throw new Error(`Invalid fee level: ${feeLevel}. Must be 1-5`);
2933
3016
  }
2934
3017
  if (!effectiveFeeRate)
2935
3018
  throw new Error("Unable to get fee rate for network");
2936
- console.log(`${tag5}: Using fee rate from API:`, {
3019
+ console.log(`${tag6}: Using fee rate from API:`, {
2937
3020
  feeLevel,
2938
3021
  selectedRate: effectiveFeeRate,
2939
3022
  description: feeLevel <= 2 ? "slow" : feeLevel <= 4 ? "average" : "fast"
@@ -2943,22 +3026,22 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2943
3026
  effectiveFeeRate = Math.ceil(effectiveFeeRate);
2944
3027
  const MIN_RELAY_FEE_RATE = 3;
2945
3028
  if (effectiveFeeRate < MIN_RELAY_FEE_RATE) {
2946
- console.log(`${tag5}: Fee rate ${effectiveFeeRate} is below minimum relay fee, increasing to ${MIN_RELAY_FEE_RATE} sat/vB`);
3029
+ console.log(`${tag6}: Fee rate ${effectiveFeeRate} is below minimum relay fee, increasing to ${MIN_RELAY_FEE_RATE} sat/vB`);
2947
3030
  effectiveFeeRate = MIN_RELAY_FEE_RATE;
2948
3031
  }
2949
- console.log(`${tag5}: Final fee rate to use (rounded, with minimums): ${effectiveFeeRate} sat/vB`);
3032
+ console.log(`${tag6}: Final fee rate to use (rounded, with minimums): ${effectiveFeeRate} sat/vB`);
2950
3033
  amount = parseInt(String(amount * 1e8));
2951
3034
  if (amount <= 0 && !isMax)
2952
3035
  throw Error("Invalid amount! 0");
2953
3036
  const totalBalance = utxos.reduce((sum, utxo) => sum + utxo.value, 0);
2954
- console.log(`${tag5}: Coin selection inputs:`, {
3037
+ console.log(`${tag6}: Coin selection inputs:`, {
2955
3038
  utxoCount: utxos.length,
2956
3039
  totalBalance: totalBalance / 1e8,
2957
3040
  requestedAmount: amount / 1e8,
2958
3041
  isMax,
2959
3042
  feeRate: effectiveFeeRate
2960
3043
  });
2961
- console.log(`${tag5}: UTXO details for coin selection:`, utxos.map((u) => ({
3044
+ console.log(`${tag6}: UTXO details for coin selection:`, utxos.map((u) => ({
2962
3045
  value: u.value,
2963
3046
  txid: u.txid?.substring(0, 10) + "...",
2964
3047
  vout: u.vout,
@@ -2972,8 +3055,8 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2972
3055
  } else {
2973
3056
  result = import_coinselect.default(utxos, [{ address: to, value: amount }], effectiveFeeRate);
2974
3057
  }
2975
- console.log(tag5, "coinSelect result object:", result);
2976
- console.log(tag5, "coinSelect result.inputs:", result?.inputs);
3058
+ console.log(tag6, "coinSelect result object:", result);
3059
+ console.log(tag6, "coinSelect result.inputs:", result?.inputs);
2977
3060
  if (!result || !result.inputs) {
2978
3061
  const errorDetails = {
2979
3062
  utxoCount: utxos.length,
@@ -2982,7 +3065,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2982
3065
  feeRate: effectiveFeeRate,
2983
3066
  insufficientFunds: totalBalance < amount
2984
3067
  };
2985
- console.error(`${tag5}: Coin selection failed:`, errorDetails);
3068
+ console.error(`${tag6}: Coin selection failed:`, errorDetails);
2986
3069
  if (utxos.length === 0) {
2987
3070
  throw Error("No UTXOs available for coin selection");
2988
3071
  } else if (totalBalance < amount) {
@@ -2998,7 +3081,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2998
3081
  throw Error("Failed to create transaction: Missing outputs");
2999
3082
  if (fee === undefined)
3000
3083
  throw Error("Failed to calculate transaction fee");
3001
- console.log(`${tag5}: Transaction built with:`, {
3084
+ console.log(`${tag6}: Transaction built with:`, {
3002
3085
  feeLevel,
3003
3086
  effectiveFeeRate: `${effectiveFeeRate} sat/vB`,
3004
3087
  calculatedFee: `${fee} satoshis`,
@@ -3006,8 +3089,8 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
3006
3089
  outputCount: outputs.length
3007
3090
  });
3008
3091
  const uniqueInputSet = new Set;
3009
- console.log(tag5, "inputs:", inputs);
3010
- console.log(tag5, "inputs:", inputs[0]);
3092
+ console.log(tag6, "inputs:", inputs);
3093
+ console.log(tag6, "inputs:", inputs[0]);
3011
3094
  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 }) => ({
3012
3095
  addressNList: bip32ToAddressNList2(path2),
3013
3096
  scriptType,
@@ -3115,7 +3198,7 @@ class TransactionManager {
3115
3198
  throw new Error(`Unsupported CAIP: ${caip}`);
3116
3199
  }
3117
3200
  async transfer({ caip, to, amount, memo, isMax = false, feeLevel = 5, changeScriptType }) {
3118
- let tag5 = TAG4 + " | transfer | ";
3201
+ let tag6 = TAG4 + " | transfer | ";
3119
3202
  try {
3120
3203
  if (!this.pioneer)
3121
3204
  throw Error("Failed to init! pioneer");
@@ -3153,12 +3236,12 @@ class TransactionManager {
3153
3236
  }
3154
3237
  return unsignedTx;
3155
3238
  } catch (e) {
3156
- console.error(tag5, e);
3239
+ console.error(tag6, e);
3157
3240
  throw e;
3158
3241
  }
3159
3242
  }
3160
3243
  async sign({ caip, unsignedTx }) {
3161
- let tag5 = TAG4 + " | sign | ";
3244
+ let tag6 = TAG4 + " | sign | ";
3162
3245
  try {
3163
3246
  if (!this.pioneer)
3164
3247
  throw Error("Failed to init! pioneer");
@@ -3244,20 +3327,20 @@ class TransactionManager {
3244
3327
  }
3245
3328
  case "cosmos:mayachain-mainnet-v1/slip44:931":
3246
3329
  case "cosmos:mayachain-mainnet-v1/denom:maya": {
3247
- console.log(tag5, "\uD83D\uDD0D ===== MAYACHAIN SIGNING AUDIT =====");
3248
- console.log(tag5, "\uD83D\uDCCB unsignedTx:", JSON.stringify(unsignedTx, null, 2));
3249
- console.log(tag5, "\uD83D\uDD11 unsignedTx.addressNList:", unsignedTx.addressNList);
3250
- console.log(tag5, "\uD83D\uDCCD unsignedTx.signerAddress:", unsignedTx.signerAddress);
3251
- console.log(tag5, "\uD83C\uDF10 pubkeyContext:", this.pubkeyContext);
3252
- console.log(tag5, "\uD83D\uDD10 pubkeyContext.addressNList:", this.pubkeyContext?.addressNList);
3253
- console.log(tag5, "\uD83D\uDD10 pubkeyContext.addressNListMaster:", this.pubkeyContext?.addressNListMaster);
3254
- console.log(tag5, "\uD83D\uDCEC pubkeyContext.address:", this.pubkeyContext?.address);
3255
- console.log(tag5, "=======================================");
3330
+ console.log(tag6, "\uD83D\uDD0D ===== MAYACHAIN SIGNING AUDIT =====");
3331
+ console.log(tag6, "\uD83D\uDCCB unsignedTx:", JSON.stringify(unsignedTx, null, 2));
3332
+ console.log(tag6, "\uD83D\uDD11 unsignedTx.addressNList:", unsignedTx.addressNList);
3333
+ console.log(tag6, "\uD83D\uDCCD unsignedTx.signerAddress:", unsignedTx.signerAddress);
3334
+ console.log(tag6, "\uD83C\uDF10 pubkeyContext:", this.pubkeyContext);
3335
+ console.log(tag6, "\uD83D\uDD10 pubkeyContext.addressNList:", this.pubkeyContext?.addressNList);
3336
+ console.log(tag6, "\uD83D\uDD10 pubkeyContext.addressNListMaster:", this.pubkeyContext?.addressNListMaster);
3337
+ console.log(tag6, "\uD83D\uDCEC pubkeyContext.address:", this.pubkeyContext?.address);
3338
+ console.log(tag6, "=======================================");
3256
3339
  if (unsignedTx.signDoc.msgs[0].type === "mayachain/MsgSend") {
3257
3340
  const responseSign = await this.keepKeySdk.mayachain.mayachainSignAminoTransfer(unsignedTx);
3258
3341
  signedTx = responseSign.serialized;
3259
- console.log(tag5, "✅ Signing completed");
3260
- console.log(tag5, "\uD83D\uDCE6 responseSign:", responseSign);
3342
+ console.log(tag6, "✅ Signing completed");
3343
+ console.log(tag6, "\uD83D\uDCE6 responseSign:", responseSign);
3261
3344
  } else if (unsignedTx.signDoc.msgs[0].type === "mayachain/MsgDeposit") {
3262
3345
  const responseSign = await this.keepKeySdk.mayachain.mayachainSignAminoDeposit(unsignedTx);
3263
3346
  signedTx = responseSign.serialized;
@@ -3279,11 +3362,11 @@ class TransactionManager {
3279
3362
  if (serialized.length > 140) {
3280
3363
  signedTx = serialized;
3281
3364
  } else {
3282
- console.error(tag5, "EIP155 signing returned incomplete transaction - only signature components");
3365
+ console.error(tag6, "EIP155 signing returned incomplete transaction - only signature components");
3283
3366
  throw new Error("KeepKey returned incomplete transaction - cannot reconstruct without r,s,v components");
3284
3367
  }
3285
3368
  } else {
3286
- console.error(tag5, "EIP155 signing failed - no valid signature in response:", responseSign);
3369
+ console.error(tag6, "EIP155 signing failed - no valid signature in response:", responseSign);
3287
3370
  throw new Error("Failed to sign transaction - no valid signature in response");
3288
3371
  }
3289
3372
  break;
@@ -3304,19 +3387,19 @@ class TransactionManager {
3304
3387
  }
3305
3388
  }
3306
3389
  if (!signedTx) {
3307
- console.error(tag5, "CRITICAL ERROR: signedTx is missing after signing process");
3308
- console.error(tag5, "CAIP:", caip);
3309
- console.error(tag5, "Type:", type);
3390
+ console.error(tag6, "CRITICAL ERROR: signedTx is missing after signing process");
3391
+ console.error(tag6, "CAIP:", caip);
3392
+ console.error(tag6, "Type:", type);
3310
3393
  throw Error("Failed to sign! missing signedTx");
3311
3394
  }
3312
3395
  return signedTx;
3313
3396
  } catch (e) {
3314
- console.error(tag5, e);
3397
+ console.error(tag6, e);
3315
3398
  throw e;
3316
3399
  }
3317
3400
  }
3318
3401
  async broadcast({ networkId, serialized }) {
3319
- let tag5 = TAG4 + " | broadcast | ";
3402
+ let tag6 = TAG4 + " | broadcast | ";
3320
3403
  try {
3321
3404
  if (!this.pioneer)
3322
3405
  throw Error("Failed to init! pioneer");
@@ -3330,7 +3413,7 @@ class TransactionManager {
3330
3413
  return result.txid;
3331
3414
  }
3332
3415
  } catch (e) {
3333
- console.error(tag5, e);
3416
+ console.error(tag6, e);
3334
3417
  throw e;
3335
3418
  }
3336
3419
  }
@@ -3450,7 +3533,7 @@ var cosmosClaimAllRewardsTemplate = (params) => ({
3450
3533
  // src/txbuilder/createUnsignedStakingTx.ts
3451
3534
  var TAG5 = " | createUnsignedStakingTx | ";
3452
3535
  async function createUnsignedStakingTx(caip, params, pubkeys, pioneer, pubkeyContext) {
3453
- const tag5 = TAG5 + " | createUnsignedStakingTx | ";
3536
+ const tag6 = TAG5 + " | createUnsignedStakingTx | ";
3454
3537
  try {
3455
3538
  if (!pioneer)
3456
3539
  throw new Error("Failed to init! pioneer");
@@ -3461,7 +3544,7 @@ async function createUnsignedStakingTx(caip, params, pubkeys, pioneer, pubkeyCon
3461
3544
  if (!pubkeyContext.networks?.includes(networkId)) {
3462
3545
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
3463
3546
  }
3464
- console.log(tag5, `✅ Using pubkeyContext for network ${networkId}:`, {
3547
+ console.log(tag6, `✅ Using pubkeyContext for network ${networkId}:`, {
3465
3548
  address: pubkeyContext.address
3466
3549
  });
3467
3550
  let chain;
@@ -3493,10 +3576,10 @@ async function createUnsignedStakingTx(caip, params, pubkeys, pioneer, pubkeyCon
3493
3576
  default:
3494
3577
  throw new Error(`Unsupported networkId for staking: ${networkId}`);
3495
3578
  }
3496
- console.log(tag5, `Building ${params.type} transaction for ${chain}`);
3579
+ console.log(tag6, `Building ${params.type} transaction for ${chain}`);
3497
3580
  const fromAddress = pubkeyContext.address || pubkeyContext.pubkey;
3498
3581
  const accountInfo = (await pioneer.GetAccountInfo({ network: chain, address: fromAddress })).data;
3499
- console.log(tag5, "accountInfo: ", accountInfo);
3582
+ console.log(tag6, "accountInfo: ", accountInfo);
3500
3583
  let account_number;
3501
3584
  let sequence;
3502
3585
  if (networkId === "cosmos:cosmoshub-4" || networkId === "cosmos:osmosis-1") {
@@ -3578,7 +3661,7 @@ async function createUnsignedStakingTx(caip, params, pubkeys, pioneer, pubkeyCon
3578
3661
  throw new Error(`Unsupported staking transaction type: ${params.type}`);
3579
3662
  }
3580
3663
  } catch (error) {
3581
- console.error(tag5, "Error:", error);
3664
+ console.error(tag6, "Error:", error);
3582
3665
  throw error;
3583
3666
  }
3584
3667
  }
@@ -3624,16 +3707,16 @@ function withTimeout(promise, timeoutMs) {
3624
3707
  ]);
3625
3708
  }
3626
3709
  async function getFees(pioneer, networkId) {
3627
- const tag5 = TAG6 + " | getFees | ";
3710
+ const tag6 = TAG6 + " | getFees | ";
3628
3711
  try {
3629
- console.log(tag5, `Fetching fees for network: ${networkId}`);
3712
+ console.log(tag6, `Fetching fees for network: ${networkId}`);
3630
3713
  const networkType = getNetworkType(networkId);
3631
3714
  if (networkType === "COSMOS") {
3632
- console.log(tag5, "Using hardcoded fees for Cosmos network:", networkId);
3715
+ console.log(tag6, "Using hardcoded fees for Cosmos network:", networkId);
3633
3716
  return getCosmosFees(networkId);
3634
3717
  }
3635
3718
  if (networkId === "bip122:00000000001a91e3dace36e2be3bf030") {
3636
- console.log(tag5, "Using hardcoded fees for Dogecoin: 10 sat/byte");
3719
+ console.log(tag6, "Using hardcoded fees for Dogecoin: 10 sat/byte");
3637
3720
  return {
3638
3721
  slow: {
3639
3722
  label: "Slow",
@@ -3670,7 +3753,7 @@ async function getFees(pioneer, networkId) {
3670
3753
  const apiCall = pioneer.GetFeeRateByNetwork ? pioneer.GetFeeRateByNetwork({ networkId }) : pioneer.GetFeeRate({ networkId });
3671
3754
  feeResponse = await withTimeout(apiCall, 3000);
3672
3755
  } catch (timeoutError) {
3673
- console.warn(tag5, "Dash fee API timeout, using fallback fees");
3756
+ console.warn(tag6, "Dash fee API timeout, using fallback fees");
3674
3757
  return {
3675
3758
  slow: {
3676
3759
  label: "Economy",
@@ -3708,17 +3791,17 @@ async function getFees(pioneer, networkId) {
3708
3791
  throw new Error(`No fee data returned for ${networkId}`);
3709
3792
  }
3710
3793
  const feeData = feeResponse.data;
3711
- console.log(tag5, "Raw fee data:", feeData);
3794
+ console.log(tag6, "Raw fee data:", feeData);
3712
3795
  const networkName = getNetworkName(networkId);
3713
3796
  let normalizedFees = normalizeFeeData(feeData, networkType, networkName, networkId);
3714
3797
  normalizedFees = ensureFeeDifferentiation(normalizedFees, networkType);
3715
3798
  normalizedFees.networkId = networkId;
3716
3799
  normalizedFees.networkType = networkType;
3717
3800
  normalizedFees.raw = feeData;
3718
- console.log(tag5, "Normalized fees:", normalizedFees);
3801
+ console.log(tag6, "Normalized fees:", normalizedFees);
3719
3802
  return normalizedFees;
3720
3803
  } catch (error) {
3721
- console.error(tag5, "Failed to fetch fees:", error);
3804
+ console.error(tag6, "Failed to fetch fees:", error);
3722
3805
  return getFallbackFees(networkId);
3723
3806
  }
3724
3807
  }
@@ -4027,7 +4110,7 @@ function estimateTransactionFee(feeRate, unit, networkType, txSize) {
4027
4110
 
4028
4111
  // src/utils/kkapi-detection.ts
4029
4112
  async function detectKkApiAvailability(forceLocalhost) {
4030
- const tag5 = " | detectKkApiAvailability | ";
4113
+ const tag6 = " | detectKkApiAvailability | ";
4031
4114
  try {
4032
4115
  const isTauri = typeof window !== "undefined" && "__TAURI__" in window;
4033
4116
  const isBrowser = typeof window !== "undefined";
@@ -4155,11 +4238,17 @@ function buildDashboardFromBalances(balances, blockchains, assetsMap) {
4155
4238
  return sum + balanceNum;
4156
4239
  }, 0).toString();
4157
4240
  const assetInfo = nativeAssetCaip ? assetsMap.get(nativeAssetCaip) : null;
4241
+ console.log(TAG7, `[DEBUG] Network: ${blockchain}`);
4242
+ console.log(TAG7, `[DEBUG] nativeAssetCaip: ${nativeAssetCaip}`);
4243
+ console.log(TAG7, `[DEBUG] assetInfo:`, assetInfo);
4244
+ console.log(TAG7, `[DEBUG] gasAsset:`, gasAsset);
4245
+ console.log(TAG7, `[DEBUG] Resolved name: ${gasAsset?.name || assetInfo?.name || "NO NAME"}`);
4158
4246
  networksTemp.push({
4159
4247
  networkId: blockchain,
4160
4248
  totalValueUsd: networkTotal,
4161
4249
  gasAssetCaip: nativeAssetCaip || null,
4162
4250
  gasAssetSymbol: gasAsset?.ticker || gasAsset?.symbol || assetInfo?.symbol || null,
4251
+ gasAssetName: gasAsset?.name || assetInfo?.name || null,
4163
4252
  icon: gasAsset?.icon || assetInfo?.icon || null,
4164
4253
  color: gasAsset?.color || assetInfo?.color || null,
4165
4254
  totalNativeBalance
@@ -4179,11 +4268,11 @@ function buildDashboardFromBalances(balances, blockchains, assetsMap) {
4179
4268
  // src/utils/sync-market.ts
4180
4269
  var TAG8 = " | sync-market | ";
4181
4270
  async function syncMarket(balances, pioneer) {
4182
- const tag5 = `${TAG8} | syncMarket | `;
4271
+ const tag6 = `${TAG8} | syncMarket | `;
4183
4272
  try {
4184
4273
  const invalidBalances = balances.filter((b3) => !b3 || !b3.caip || typeof b3.caip !== "string" || !b3.caip.includes(":"));
4185
4274
  if (invalidBalances.length > 0) {
4186
- console.warn(tag5, `Found ${invalidBalances.length} balances with invalid CAIPs:`, invalidBalances.map((b3) => ({
4275
+ console.warn(tag6, `Found ${invalidBalances.length} balances with invalid CAIPs:`, invalidBalances.map((b3) => ({
4187
4276
  caip: b3?.caip,
4188
4277
  type: typeof b3?.caip,
4189
4278
  symbol: b3?.symbol,
@@ -4198,7 +4287,7 @@ async function syncMarket(balances, pioneer) {
4198
4287
  console.log("GetMarketInfo: payload length: ", allCaips.length);
4199
4288
  const invalidEntries = allCaips.filter((caip) => typeof caip !== "string");
4200
4289
  if (invalidEntries.length > 0) {
4201
- console.error(tag5, "CRITICAL: Invalid entries detected in allCaips:", invalidEntries);
4290
+ console.error(tag6, "CRITICAL: Invalid entries detected in allCaips:", invalidEntries);
4202
4291
  throw new Error("Invalid CAIP entries detected - aborting market sync");
4203
4292
  }
4204
4293
  if (allCaips && allCaips.length > 0) {
@@ -4219,13 +4308,13 @@ async function syncMarket(balances, pioneer) {
4219
4308
  }
4220
4309
  }
4221
4310
  } catch (apiError) {
4222
- console.error(tag5, "API error fetching market info:", apiError);
4223
- console.warn(tag5, "Continuing without market prices");
4311
+ console.error(tag6, "API error fetching market info:", apiError);
4312
+ console.warn(tag6, "Continuing without market prices");
4224
4313
  }
4225
4314
  }
4226
4315
  return true;
4227
4316
  } catch (e) {
4228
- console.error(tag5, "e:", e);
4317
+ console.error(tag6, "e:", e);
4229
4318
  throw e;
4230
4319
  }
4231
4320
  }
@@ -4395,7 +4484,7 @@ class SDK {
4395
4484
  return true;
4396
4485
  };
4397
4486
  this.setPubkeys = (newPubkeys) => {
4398
- const tag5 = `${TAG9} | setPubkeys | `;
4487
+ const tag6 = `${TAG9} | setPubkeys | `;
4399
4488
  this.pubkeys = [];
4400
4489
  this.pubkeySet.clear();
4401
4490
  let added = 0;
@@ -4406,7 +4495,7 @@ class SDK {
4406
4495
  }
4407
4496
  };
4408
4497
  this.getUnifiedPortfolio = async function() {
4409
- const tag5 = `${TAG9} | getUnifiedPortfolio | `;
4498
+ const tag6 = `${TAG9} | getUnifiedPortfolio | `;
4410
4499
  try {
4411
4500
  const startTime = performance.now();
4412
4501
  try {
@@ -4417,17 +4506,17 @@ class SDK {
4417
4506
  signal: AbortSignal.timeout(2000)
4418
4507
  });
4419
4508
  if (!portfolioResponse.ok) {
4420
- console.warn(tag5, "Portfolio endpoint returned", portfolioResponse.status);
4509
+ console.warn(tag6, "Portfolio endpoint returned", portfolioResponse.status);
4421
4510
  return null;
4422
4511
  }
4423
4512
  const portfolioData = await portfolioResponse.json();
4424
4513
  const loadTime = performance.now() - startTime;
4425
4514
  if (!portfolioData.success) {
4426
- console.warn(tag5, "Portfolio API returned success=false");
4515
+ console.warn(tag6, "Portfolio API returned success=false");
4427
4516
  return null;
4428
4517
  }
4429
4518
  if (portfolioData.totalValueUsd === 0 || !portfolioData.totalValueUsd) {
4430
- console.warn(tag5, "Portfolio value is $0.00 - may need device connection or sync");
4519
+ console.warn(tag6, "Portfolio value is $0.00 - may need device connection or sync");
4431
4520
  return null;
4432
4521
  }
4433
4522
  let allBalances = [];
@@ -4502,19 +4591,19 @@ class SDK {
4502
4591
  };
4503
4592
  } catch (fetchError) {
4504
4593
  if (fetchError.name === "AbortError") {
4505
- console.log(tag5, "Unified portfolio request timed out (this is normal if vault not running)");
4594
+ console.log(tag6, "Unified portfolio request timed out (this is normal if vault not running)");
4506
4595
  } else {
4507
- console.log(tag5, "Failed to fetch unified portfolio:", fetchError.message);
4596
+ console.log(tag6, "Failed to fetch unified portfolio:", fetchError.message);
4508
4597
  }
4509
4598
  return null;
4510
4599
  }
4511
4600
  } catch (e) {
4512
- console.error(tag5, "Error:", e);
4601
+ console.error(tag6, "Error:", e);
4513
4602
  return null;
4514
4603
  }
4515
4604
  };
4516
4605
  this.init = async function(walletsVerbose, setup) {
4517
- const tag5 = `${TAG9} | init | `;
4606
+ const tag6 = `${TAG9} | init | `;
4518
4607
  try {
4519
4608
  if (!this.username)
4520
4609
  throw Error("username required!");
@@ -4597,7 +4686,7 @@ class SDK {
4597
4686
  }
4598
4687
  return this.pioneer;
4599
4688
  } catch (e) {
4600
- console.error(tag5, "e: ", e);
4689
+ console.error(tag6, "e: ", e);
4601
4690
  throw e;
4602
4691
  }
4603
4692
  };
@@ -4608,7 +4697,7 @@ class SDK {
4608
4697
  return syncMarket(this.balances, this.pioneer);
4609
4698
  };
4610
4699
  this.sync = async function() {
4611
- const tag5 = `${TAG9} | sync | `;
4700
+ const tag6 = `${TAG9} | sync | `;
4612
4701
  try {
4613
4702
  const matchesNetwork = (item, networkId) => {
4614
4703
  if (!item.networks || !Array.isArray(item.networks))
@@ -4660,16 +4749,16 @@ class SDK {
4660
4749
  let totalPortfolioValue = 0;
4661
4750
  const networksTemp = [];
4662
4751
  const uniqueBlockchains = [...new Set(this.blockchains)];
4663
- console.log(tag5, "uniqueBlockchains: ", uniqueBlockchains);
4752
+ console.log(tag6, "uniqueBlockchains: ", uniqueBlockchains);
4664
4753
  for (const blockchain of uniqueBlockchains) {
4665
4754
  const filteredBalances = this.balances.filter((b3) => {
4666
4755
  const networkId = caipToNetworkId7(b3.caip);
4667
4756
  return networkId === blockchain || blockchain === "eip155:*" && networkId.startsWith("eip155:");
4668
4757
  });
4669
- console.log(tag5, `Filtering for blockchain: ${blockchain}`);
4670
- console.log(tag5, `Found ${filteredBalances.length} balances before deduplication`);
4758
+ console.log(tag6, `Filtering for blockchain: ${blockchain}`);
4759
+ console.log(tag6, `Found ${filteredBalances.length} balances before deduplication`);
4671
4760
  filteredBalances.forEach((balance, idx) => {
4672
- console.log(tag5, `Balance[${idx}]:`, {
4761
+ console.log(tag6, `Balance[${idx}]:`, {
4673
4762
  caip: balance.caip,
4674
4763
  pubkey: balance.pubkey,
4675
4764
  balance: balance.balance,
@@ -4679,7 +4768,7 @@ class SDK {
4679
4768
  const balanceMap = new Map;
4680
4769
  const isBitcoin = blockchain.includes("bip122:000000000019d6689c085ae165831e93");
4681
4770
  if (isBitcoin) {
4682
- console.log(tag5, "Bitcoin network detected - checking for duplicate balances");
4771
+ console.log(tag6, "Bitcoin network detected - checking for duplicate balances");
4683
4772
  const bitcoinByValue = new Map;
4684
4773
  filteredBalances.forEach((balance) => {
4685
4774
  const valueKey = `${balance.balance}_${balance.valueUsd}`;
@@ -4690,7 +4779,7 @@ class SDK {
4690
4779
  });
4691
4780
  for (const [valueKey, balances] of bitcoinByValue.entries()) {
4692
4781
  if (balances.length === 3 && parseFloat(balances[0].valueUsd || "0") > 0) {
4693
- console.log(tag5, "BITCOIN API BUG DETECTED: All 3 address types have same balance, keeping only xpub");
4782
+ console.log(tag6, "BITCOIN API BUG DETECTED: All 3 address types have same balance, keeping only xpub");
4694
4783
  const xpubBalance = balances.find((b3) => b3.pubkey?.startsWith("xpub")) || balances[0];
4695
4784
  const key = `${xpubBalance.caip}_${xpubBalance.pubkey || "default"}`;
4696
4785
  balanceMap.set(key, xpubBalance);
@@ -4710,13 +4799,13 @@ class SDK {
4710
4799
  });
4711
4800
  }
4712
4801
  const networkBalances = Array.from(balanceMap.values());
4713
- console.log(tag5, "networkBalances (deduplicated): ", networkBalances);
4714
- console.log(tag5, "networkBalances count: ", networkBalances.length);
4802
+ console.log(tag6, "networkBalances (deduplicated): ", networkBalances);
4803
+ console.log(tag6, "networkBalances count: ", networkBalances.length);
4715
4804
  const networkTotal = networkBalances.reduce((sum, balance, idx) => {
4716
4805
  const valueUsd = typeof balance.valueUsd === "string" ? parseFloat(balance.valueUsd) : balance.valueUsd || 0;
4717
- console.log(tag5, `[${idx}] valueUsd:`, balance.valueUsd, "→ parsed:", valueUsd, "| running sum:", sum + valueUsd);
4806
+ console.log(tag6, `[${idx}] valueUsd:`, balance.valueUsd, "→ parsed:", valueUsd, "| running sum:", sum + valueUsd);
4718
4807
  if (blockchain.includes("bip122:000000000019d6689c085ae165831e93")) {
4719
- console.log(tag5, `[BITCOIN DEBUG ${idx}] pubkey:`, balance.pubkey?.substring(0, 10) + "...", "| balance:", balance.balance, "| valueUsd:", balance.valueUsd, "→ parsed:", valueUsd);
4808
+ console.log(tag6, `[BITCOIN DEBUG ${idx}] pubkey:`, balance.pubkey?.substring(0, 10) + "...", "| balance:", balance.balance, "| valueUsd:", balance.valueUsd, "→ parsed:", valueUsd);
4720
4809
  }
4721
4810
  return sum + valueUsd;
4722
4811
  }, 0);
@@ -4747,7 +4836,7 @@ class SDK {
4747
4836
  this.dashboard = dashboardData;
4748
4837
  return true;
4749
4838
  } catch (e) {
4750
- console.error(tag5, "Error in sync:", e);
4839
+ console.error(tag6, "Error in sync:", e);
4751
4840
  throw e;
4752
4841
  }
4753
4842
  };
@@ -4761,7 +4850,7 @@ class SDK {
4761
4850
  }
4762
4851
  };
4763
4852
  this.buildTx = async function(sendPayload) {
4764
- let tag5 = TAG9 + " | buildTx | ";
4853
+ let tag6 = TAG9 + " | buildTx | ";
4765
4854
  try {
4766
4855
  const transactionDependencies = {
4767
4856
  context: this.context,
@@ -4775,7 +4864,7 @@ class SDK {
4775
4864
  };
4776
4865
  let txManager = new TransactionManager(transactionDependencies, this.events);
4777
4866
  let unsignedTx = await txManager.transfer(sendPayload);
4778
- console.log(tag5, "unsignedTx: ", unsignedTx);
4867
+ console.log(tag6, "unsignedTx: ", unsignedTx);
4779
4868
  return unsignedTx;
4780
4869
  } catch (e) {
4781
4870
  console.error(e);
@@ -4783,14 +4872,14 @@ class SDK {
4783
4872
  }
4784
4873
  };
4785
4874
  this.buildDelegateTx = async function(caip, params) {
4786
- let tag5 = TAG9 + " | buildDelegateTx | ";
4875
+ let tag6 = TAG9 + " | buildDelegateTx | ";
4787
4876
  try {
4788
4877
  const delegateParams = {
4789
4878
  ...params,
4790
4879
  type: "delegate"
4791
4880
  };
4792
4881
  let unsignedTx = await createUnsignedStakingTx(caip, delegateParams, this.pubkeys, this.pioneer, this.pubkeyContext);
4793
- console.log(tag5, "unsignedTx: ", unsignedTx);
4882
+ console.log(tag6, "unsignedTx: ", unsignedTx);
4794
4883
  return unsignedTx;
4795
4884
  } catch (e) {
4796
4885
  console.error(e);
@@ -4798,14 +4887,14 @@ class SDK {
4798
4887
  }
4799
4888
  };
4800
4889
  this.buildUndelegateTx = async function(caip, params) {
4801
- let tag5 = TAG9 + " | buildUndelegateTx | ";
4890
+ let tag6 = TAG9 + " | buildUndelegateTx | ";
4802
4891
  try {
4803
4892
  const undelegateParams = {
4804
4893
  ...params,
4805
4894
  type: "undelegate"
4806
4895
  };
4807
4896
  let unsignedTx = await createUnsignedStakingTx(caip, undelegateParams, this.pubkeys, this.pioneer, this.pubkeyContext);
4808
- console.log(tag5, "unsignedTx: ", unsignedTx);
4897
+ console.log(tag6, "unsignedTx: ", unsignedTx);
4809
4898
  return unsignedTx;
4810
4899
  } catch (e) {
4811
4900
  console.error(e);
@@ -4813,14 +4902,14 @@ class SDK {
4813
4902
  }
4814
4903
  };
4815
4904
  this.buildClaimRewardsTx = async function(caip, params) {
4816
- let tag5 = TAG9 + " | buildClaimRewardsTx | ";
4905
+ let tag6 = TAG9 + " | buildClaimRewardsTx | ";
4817
4906
  try {
4818
4907
  const claimParams = {
4819
4908
  ...params,
4820
4909
  type: "claim_rewards"
4821
4910
  };
4822
4911
  let unsignedTx = await createUnsignedStakingTx(caip, claimParams, this.pubkeys, this.pioneer, this.pubkeyContext);
4823
- console.log(tag5, "unsignedTx: ", unsignedTx);
4912
+ console.log(tag6, "unsignedTx: ", unsignedTx);
4824
4913
  return unsignedTx;
4825
4914
  } catch (e) {
4826
4915
  console.error(e);
@@ -4828,7 +4917,7 @@ class SDK {
4828
4917
  }
4829
4918
  };
4830
4919
  this.buildClaimAllRewardsTx = async function(caip, params) {
4831
- let tag5 = TAG9 + " | buildClaimAllRewardsTx | ";
4920
+ let tag6 = TAG9 + " | buildClaimAllRewardsTx | ";
4832
4921
  try {
4833
4922
  const claimAllParams = {
4834
4923
  ...params,
@@ -4841,8 +4930,8 @@ class SDK {
4841
4930
  throw e;
4842
4931
  }
4843
4932
  };
4844
- this.signTx = async function(unsignedTx) {
4845
- let tag5 = TAG9 + " | signTx | ";
4933
+ this.signTx = async function(caip, unsignedTx) {
4934
+ let tag6 = TAG9 + " | signTx | ";
4846
4935
  try {
4847
4936
  const transactionDependencies = {
4848
4937
  context: this.context,
@@ -4855,7 +4944,7 @@ class SDK {
4855
4944
  keepKeySdk: this.keepKeySdk
4856
4945
  };
4857
4946
  let txManager = new TransactionManager(transactionDependencies, this.events);
4858
- let signedTx = await txManager.sign(unsignedTx);
4947
+ let signedTx = await txManager.sign({ caip, unsignedTx });
4859
4948
  return signedTx;
4860
4949
  } catch (e) {
4861
4950
  console.error(e);
@@ -4863,7 +4952,7 @@ class SDK {
4863
4952
  }
4864
4953
  };
4865
4954
  this.broadcastTx = async function(caip, signedTx) {
4866
- let tag5 = TAG9 + " | broadcastTx | ";
4955
+ let tag6 = TAG9 + " | broadcastTx | ";
4867
4956
  try {
4868
4957
  const transactionDependencies = {
4869
4958
  context: this.context,
@@ -4887,7 +4976,7 @@ class SDK {
4887
4976
  }
4888
4977
  };
4889
4978
  this.swap = async function(swapPayload) {
4890
- let tag5 = `${TAG9} | swap | `;
4979
+ let tag6 = `${TAG9} | swap | `;
4891
4980
  try {
4892
4981
  if (!swapPayload)
4893
4982
  throw Error("swapPayload required!");
@@ -4936,15 +5025,15 @@ class SDK {
4936
5025
  throw new Error(`Cannot use max amount: no balance found for ${swapPayload.caipIn}`);
4937
5026
  }
4938
5027
  let totalBalance = 0;
4939
- console.log(tag5, `Found ${inputBalances.length} balance entries for ${swapPayload.caipIn}`);
5028
+ console.log(tag6, `Found ${inputBalances.length} balance entries for ${swapPayload.caipIn}`);
4940
5029
  for (const balanceEntry of inputBalances) {
4941
5030
  const balance = parseFloat(balanceEntry.balance) || 0;
4942
5031
  totalBalance += balance;
4943
- console.log(tag5, ` - ${balanceEntry.pubkey || balanceEntry.identifier}: ${balance}`);
5032
+ console.log(tag6, ` - ${balanceEntry.pubkey || balanceEntry.identifier}: ${balance}`);
4944
5033
  }
4945
5034
  this.assetContext.balance = totalBalance.toString();
4946
5035
  this.assetContext.valueUsd = (totalBalance * parseFloat(this.assetContext.priceUsd || "0")).toFixed(2);
4947
- console.log(tag5, `Updated assetContext balance to aggregated total: ${totalBalance}`);
5036
+ console.log(tag6, `Updated assetContext balance to aggregated total: ${totalBalance}`);
4948
5037
  const feeReserves = {
4949
5038
  "bip122:000000000019d6689c085ae165831e93/slip44:0": 0.00005,
4950
5039
  "eip155:1/slip44:60": 0.001,
@@ -4955,7 +5044,7 @@ class SDK {
4955
5044
  };
4956
5045
  const reserve = feeReserves[swapPayload.caipIn] || 0.0001;
4957
5046
  inputAmount = Math.max(0, totalBalance - reserve);
4958
- console.log(tag5, `Using max amount for swap: ${inputAmount} (total balance: ${totalBalance}, reserve: ${reserve})`);
5047
+ console.log(tag6, `Using max amount for swap: ${inputAmount} (total balance: ${totalBalance}, reserve: ${reserve})`);
4959
5048
  } else {
4960
5049
  inputAmount = typeof swapPayload.amount === "string" ? parseFloat(swapPayload.amount) : swapPayload.amount;
4961
5050
  if (isNaN(inputAmount) || inputAmount <= 0) {
@@ -4963,23 +5052,23 @@ class SDK {
4963
5052
  }
4964
5053
  }
4965
5054
  let quote = {
4966
- affiliate: "0x658DE0443259a1027caA976ef9a42E6982037A03",
4967
- sellAsset: this.assetContext,
5055
+ sellAsset: this.assetContext.caip,
4968
5056
  sellAmount: inputAmount.toPrecision(8),
4969
- buyAsset: this.outboundAssetContext,
5057
+ buyAsset: this.outboundAssetContext.caip,
4970
5058
  recipientAddress,
4971
5059
  senderAddress,
4972
- slippage: "3"
5060
+ slippage: swapPayload.slippagePercentage || 3
4973
5061
  };
4974
5062
  let result;
4975
5063
  try {
4976
5064
  result = await this.pioneer.Quote(quote);
4977
5065
  result = result.data;
4978
5066
  } catch (e) {
4979
- console.error(tag5, "Failed to get quote: ", e);
5067
+ console.error(tag6, "Failed to get quote: ", e);
5068
+ throw Error("Quote API failed for path: " + quote.sellAsset + " -> " + quote.buyAsset + ". Error: " + e);
4980
5069
  }
4981
- if (result.length === 0)
4982
- throw Error("No quotes available! path: " + quote.sellAsset.caip + " -> " + quote.buyAsset.caip);
5070
+ if (!result || result.length === 0)
5071
+ throw Error("No quotes available! path: " + quote.sellAsset + " -> " + quote.buyAsset);
4983
5072
  let selected = result[0];
4984
5073
  let txs = selected.quote.txs;
4985
5074
  if (!txs)
@@ -4992,6 +5081,7 @@ class SDK {
4992
5081
  balances: this.balances,
4993
5082
  pioneer: this.pioneer,
4994
5083
  pubkeys: this.pubkeys,
5084
+ pubkeyContext: this.pubkeyContext,
4995
5085
  nodes: this.nodes,
4996
5086
  keepKeySdk: this.keepKeySdk
4997
5087
  };
@@ -4999,7 +5089,10 @@ class SDK {
4999
5089
  let caip = swapPayload.caipIn;
5000
5090
  let unsignedTx;
5001
5091
  if (tx.type === "deposit") {
5002
- unsignedTx = await createUnsignedTendermintTx(caip, tx.type, tx.txParams.amount, tx.txParams.memo, this.pubkeys, this.pioneer, this.keepKeySdk, false, undefined);
5092
+ unsignedTx = await createUnsignedTendermintTx(caip, tx.type, tx.txParams.amount, tx.txParams.memo, this.pubkeys, this.pioneer, this.pubkeyContext, false, undefined);
5093
+ } else if (tx.type === "EVM" || tx.type === "evm") {
5094
+ console.log(tag6, "Using pre-built EVM transaction from integration");
5095
+ unsignedTx = tx.txParams;
5003
5096
  } else {
5004
5097
  if (!tx.txParams.memo)
5005
5098
  throw Error("memo required on swaps!");
@@ -5017,12 +5110,12 @@ class SDK {
5017
5110
  return unsignedTx;
5018
5111
  }
5019
5112
  } catch (e) {
5020
- console.error(tag5, "Error: ", e);
5113
+ console.error(tag6, "Error: ", e);
5021
5114
  throw e;
5022
5115
  }
5023
5116
  };
5024
5117
  this.transfer = async function(sendPayload) {
5025
- let tag5 = `${TAG9} | transfer | `;
5118
+ let tag6 = `${TAG9} | transfer | `;
5026
5119
  try {
5027
5120
  if (!sendPayload)
5028
5121
  throw Error("sendPayload required!");
@@ -5056,15 +5149,15 @@ class SDK {
5056
5149
  return { txid, events: this.events };
5057
5150
  } catch (error) {
5058
5151
  if (error instanceof Error) {
5059
- console.error(tag5, "An error occurred during the transfer process:", error.message);
5152
+ console.error(tag6, "An error occurred during the transfer process:", error.message);
5060
5153
  } else {
5061
- console.error(tag5, "An unknown error occurred during the transfer process");
5154
+ console.error(tag6, "An unknown error occurred during the transfer process");
5062
5155
  }
5063
5156
  throw error;
5064
5157
  }
5065
5158
  };
5066
5159
  this.followTransaction = async function(caip, txid) {
5067
- let tag5 = " | followTransaction | ";
5160
+ let tag6 = " | followTransaction | ";
5068
5161
  try {
5069
5162
  const finalConfirmationBlocksByCaip = {
5070
5163
  dogecoin: 3,
@@ -5094,7 +5187,7 @@ class SDK {
5094
5187
  }
5095
5188
  }
5096
5189
  } catch (error) {
5097
- console.error(tag5, "Error:", error);
5190
+ console.error(tag6, "Error:", error);
5098
5191
  }
5099
5192
  if (!isConfirmed) {
5100
5193
  await new Promise((resolve) => setTimeout(resolve, 8000));
@@ -5112,18 +5205,18 @@ class SDK {
5112
5205
  requiredConfirmations
5113
5206
  };
5114
5207
  } catch (error) {
5115
- console.error(tag5, "Error:", error);
5208
+ console.error(tag6, "Error:", error);
5116
5209
  throw new Error("Failed to follow transaction");
5117
5210
  }
5118
5211
  };
5119
5212
  this.setBlockchains = async function(blockchains) {
5120
- const tag5 = `${TAG9} | setBlockchains | `;
5213
+ const tag6 = `${TAG9} | setBlockchains | `;
5121
5214
  try {
5122
5215
  if (!blockchains)
5123
5216
  throw Error("blockchains required!");
5124
5217
  const uniqueBlockchains = [...new Set(blockchains)];
5125
5218
  if (blockchains.length !== uniqueBlockchains.length) {
5126
- console.warn(tag5, `Removed ${blockchains.length - uniqueBlockchains.length} duplicate blockchains`);
5219
+ console.warn(tag6, `Removed ${blockchains.length - uniqueBlockchains.length} duplicate blockchains`);
5127
5220
  }
5128
5221
  this.blockchains = uniqueBlockchains;
5129
5222
  this.events.emit("SET_BLOCKCHAINS", this.blockchains);
@@ -5133,7 +5226,7 @@ class SDK {
5133
5226
  }
5134
5227
  };
5135
5228
  this.addAsset = async function(caip, data) {
5136
- let tag5 = TAG9 + " | addAsset | ";
5229
+ let tag6 = TAG9 + " | addAsset | ";
5137
5230
  try {
5138
5231
  let success = false;
5139
5232
  if (!caip)
@@ -5171,22 +5264,22 @@ class SDK {
5171
5264
  }
5172
5265
  };
5173
5266
  this.clearWalletState = async function() {
5174
- const tag5 = `${TAG9} | clearWalletState | `;
5267
+ const tag6 = `${TAG9} | clearWalletState | `;
5175
5268
  try {
5176
5269
  this.context = null;
5177
5270
  this.paths = [];
5178
5271
  this.blockchains = [];
5179
5272
  this.pubkeys = [];
5180
5273
  this.pubkeySet.clear();
5181
- console.log(tag5, "Cleared wallet state including pubkeys and tracking set");
5274
+ console.log(tag6, "Cleared wallet state including pubkeys and tracking set");
5182
5275
  return true;
5183
5276
  } catch (e) {
5184
- console.error(tag5, "e: ", e);
5277
+ console.error(tag6, "e: ", e);
5185
5278
  throw e;
5186
5279
  }
5187
5280
  };
5188
5281
  this.addPath = async function(path) {
5189
- const tag5 = `${TAG9} | addPath | `;
5282
+ const tag6 = `${TAG9} | addPath | `;
5190
5283
  try {
5191
5284
  this.paths.push(path);
5192
5285
  const pubkey = await getPubkey(path.networks[0], path, this.keepKeySdk, this.context);
@@ -5195,14 +5288,14 @@ class SDK {
5195
5288
  this.buildDashboardFromBalances();
5196
5289
  return { success: true, pubkey };
5197
5290
  } catch (e) {
5198
- console.error(tag5, "Failed:", e);
5291
+ console.error(tag6, "Failed:", e);
5199
5292
  throw e;
5200
5293
  }
5201
5294
  };
5202
5295
  this.addPaths = async function(paths) {
5203
- const tag5 = `${TAG9} | addPaths | `;
5296
+ const tag6 = `${TAG9} | addPaths | `;
5204
5297
  try {
5205
- console.log(tag5, `Adding ${paths.length} paths in batch mode...`);
5298
+ console.log(tag6, `Adding ${paths.length} paths in batch mode...`);
5206
5299
  this.paths.push(...paths);
5207
5300
  const newPubkeys = [];
5208
5301
  for (const path of paths) {
@@ -5211,10 +5304,10 @@ class SDK {
5211
5304
  this.addPubkey(pubkey);
5212
5305
  newPubkeys.push(pubkey);
5213
5306
  } catch (error) {
5214
- console.warn(tag5, `Failed to get pubkey for path ${path.note}:`, error.message);
5307
+ console.warn(tag6, `Failed to get pubkey for path ${path.note}:`, error.message);
5215
5308
  }
5216
5309
  }
5217
- console.log(tag5, `Successfully added ${newPubkeys.length} pubkeys`);
5310
+ console.log(tag6, `Successfully added ${newPubkeys.length} pubkeys`);
5218
5311
  const networkSet = new Set;
5219
5312
  for (const path of paths) {
5220
5313
  if (path.networks && Array.isArray(path.networks)) {
@@ -5222,13 +5315,13 @@ class SDK {
5222
5315
  }
5223
5316
  }
5224
5317
  const uniqueNetworks = [...networkSet];
5225
- console.log(tag5, `Fetching balances for ${uniqueNetworks.length} unique networks in single API call...`);
5318
+ console.log(tag6, `Fetching balances for ${uniqueNetworks.length} unique networks in single API call...`);
5226
5319
  await this.getBalancesForNetworks(uniqueNetworks);
5227
5320
  this.buildDashboardFromBalances();
5228
- console.log(tag5, `Batch add complete: ${paths.length} paths, ${newPubkeys.length} pubkeys, ${this.balances?.length || 0} balances`);
5321
+ console.log(tag6, `Batch add complete: ${paths.length} paths, ${newPubkeys.length} pubkeys, ${this.balances?.length || 0} balances`);
5229
5322
  return { success: true, pubkeys: newPubkeys };
5230
5323
  } catch (e) {
5231
- console.error(tag5, "Failed:", e);
5324
+ console.error(tag6, "Failed:", e);
5232
5325
  throw e;
5233
5326
  }
5234
5327
  };
@@ -5236,7 +5329,7 @@ class SDK {
5236
5329
  return this.getGasAssets();
5237
5330
  };
5238
5331
  this.getGasAssets = async function() {
5239
- const tag5 = `${TAG9} | getGasAssets | `;
5332
+ const tag6 = `${TAG9} | getGasAssets | `;
5240
5333
  try {
5241
5334
  for (let i = 0;i < this.blockchains.length; i++) {
5242
5335
  let networkId = this.blockchains[i];
@@ -5270,7 +5363,7 @@ class SDK {
5270
5363
  denom: "maya"
5271
5364
  };
5272
5365
  this.assetsMap.set(mayaTokenCaip, mayaToken);
5273
- console.log(tag5, "Added MAYA token to assetsMap");
5366
+ console.log(tag6, "Added MAYA token to assetsMap");
5274
5367
  }
5275
5368
  return this.assetsMap;
5276
5369
  } catch (e) {
@@ -5279,7 +5372,7 @@ class SDK {
5279
5372
  }
5280
5373
  };
5281
5374
  this.getPubkeys = async function() {
5282
- const tag5 = `${TAG9} | getPubkeys | `;
5375
+ const tag6 = `${TAG9} | getPubkeys | `;
5283
5376
  try {
5284
5377
  if (this.paths.length === 0)
5285
5378
  throw new Error("No paths found!");
@@ -5295,15 +5388,15 @@ class SDK {
5295
5388
  return pubkeys;
5296
5389
  } catch (error) {
5297
5390
  console.error("Error in getPubkeys:", error);
5298
- console.error(tag5, "Error in getPubkeys:", error);
5391
+ console.error(tag6, "Error in getPubkeys:", error);
5299
5392
  throw error;
5300
5393
  }
5301
5394
  };
5302
5395
  this.getBalancesForNetworks = async function(networkIds) {
5303
- const tag5 = `${TAG9} | getBalancesForNetworks | `;
5396
+ const tag6 = `${TAG9} | getBalancesForNetworks | `;
5304
5397
  try {
5305
5398
  if (!this.pioneer) {
5306
- console.error(tag5, "ERROR: Pioneer client not initialized! this.pioneer is:", this.pioneer);
5399
+ console.error(tag6, "ERROR: Pioneer client not initialized! this.pioneer is:", this.pioneer);
5307
5400
  throw new Error("Pioneer client not initialized. Call init() first.");
5308
5401
  }
5309
5402
  const assetQuery = [];
@@ -5341,48 +5434,48 @@ class SDK {
5341
5434
  identifier: `${balance.caip}:${balance.pubkey}`
5342
5435
  });
5343
5436
  }
5344
- console.log(tag5, "balances: ", balances);
5437
+ console.log(tag6, "balances: ", balances);
5345
5438
  this.balances = balances;
5346
5439
  this.events.emit("SET_BALANCES", this.balances);
5347
5440
  return this.balances;
5348
5441
  } catch (apiError) {
5349
- console.error(tag5, "GetPortfolioBalances API call failed:", apiError);
5442
+ console.error(tag6, "GetPortfolioBalances API call failed:", apiError);
5350
5443
  throw new Error(`GetPortfolioBalances API call failed: ${apiError?.message || "Unknown error"}`);
5351
5444
  }
5352
5445
  } catch (e) {
5353
- console.error(tag5, "Error: ", e);
5446
+ console.error(tag6, "Error: ", e);
5354
5447
  throw e;
5355
5448
  }
5356
5449
  };
5357
5450
  this.getBalances = async function() {
5358
- const tag5 = `${TAG9} | getBalances | `;
5451
+ const tag6 = `${TAG9} | getBalances | `;
5359
5452
  try {
5360
5453
  return await this.getBalancesForNetworks(this.blockchains);
5361
5454
  } catch (e) {
5362
- console.error(tag5, "Error in getBalances: ", e);
5455
+ console.error(tag6, "Error in getBalances: ", e);
5363
5456
  throw e;
5364
5457
  }
5365
5458
  };
5366
5459
  this.getBalance = async function(networkId) {
5367
- const tag5 = `${TAG9} | getBalance | `;
5460
+ const tag6 = `${TAG9} | getBalance | `;
5368
5461
  try {
5369
5462
  const results = await this.getBalancesForNetworks([networkId]);
5370
5463
  const filtered = results.filter(async (b3) => b3.networkId === await networkIdToCaip2(networkId));
5371
5464
  return filtered;
5372
5465
  } catch (e) {
5373
- console.error(tag5, "Error: ", e);
5466
+ console.error(tag6, "Error: ", e);
5374
5467
  throw e;
5375
5468
  }
5376
5469
  };
5377
5470
  this.getFees = async function(networkId) {
5378
- const tag5 = `${TAG9} | getFees | `;
5471
+ const tag6 = `${TAG9} | getFees | `;
5379
5472
  try {
5380
5473
  if (!this.pioneer) {
5381
5474
  throw new Error("Pioneer client not initialized. Call init() first.");
5382
5475
  }
5383
5476
  return await getFees(this.pioneer, networkId);
5384
5477
  } catch (e) {
5385
- console.error(tag5, "Error getting fees: ", e);
5478
+ console.error(tag6, "Error getting fees: ", e);
5386
5479
  throw e;
5387
5480
  }
5388
5481
  };
@@ -5390,11 +5483,11 @@ class SDK {
5390
5483
  return estimateTransactionFee(feeRate, unit, networkType, txSize);
5391
5484
  };
5392
5485
  this.getCharts = async function() {
5393
- const tag5 = `${TAG9} | getCharts | `;
5486
+ const tag6 = `${TAG9} | getCharts | `;
5394
5487
  try {
5395
- console.log(tag5, "Fetching charts");
5488
+ console.log(tag6, "Fetching charts");
5396
5489
  const newBalances = await getCharts(this.blockchains, this.pioneer, this.pubkeys, this.context);
5397
- console.log(tag5, "newBalances: ", newBalances);
5490
+ console.log(tag6, "newBalances: ", newBalances);
5398
5491
  const uniqueBalances = new Map([...this.balances, ...newBalances].map((balance) => [
5399
5492
  balance.identifier,
5400
5493
  {
@@ -5402,17 +5495,17 @@ class SDK {
5402
5495
  type: balance.type || "balance"
5403
5496
  }
5404
5497
  ]));
5405
- console.log(tag5, "uniqueBalances: ", uniqueBalances);
5498
+ console.log(tag6, "uniqueBalances: ", uniqueBalances);
5406
5499
  this.balances = Array.from(uniqueBalances.values());
5407
- console.log(tag5, "Updated this.balances: ", this.balances);
5500
+ console.log(tag6, "Updated this.balances: ", this.balances);
5408
5501
  return this.balances;
5409
5502
  } catch (e) {
5410
- console.error(tag5, "Error in getCharts:", e);
5503
+ console.error(tag6, "Error in getCharts:", e);
5411
5504
  throw e;
5412
5505
  }
5413
5506
  };
5414
5507
  this.setContext = async (context) => {
5415
- const tag5 = `${TAG9} | setContext | `;
5508
+ const tag6 = `${TAG9} | setContext | `;
5416
5509
  try {
5417
5510
  if (!context)
5418
5511
  throw Error("context required!");
@@ -5420,12 +5513,12 @@ class SDK {
5420
5513
  this.events.emit("SET_CONTEXT", context);
5421
5514
  return { success: true };
5422
5515
  } catch (e) {
5423
- console.error(tag5, "e: ", e);
5516
+ console.error(tag6, "e: ", e);
5424
5517
  return { success: false };
5425
5518
  }
5426
5519
  };
5427
5520
  this.setContextType = async (contextType) => {
5428
- const tag5 = `${TAG9} | setContextType | `;
5521
+ const tag6 = `${TAG9} | setContextType | `;
5429
5522
  try {
5430
5523
  if (!contextType)
5431
5524
  throw Error("contextType required!");
@@ -5433,22 +5526,22 @@ class SDK {
5433
5526
  this.events.emit("SET_CONTEXT_TYPE", contextType);
5434
5527
  return { success: true };
5435
5528
  } catch (e) {
5436
- console.error(tag5, "e: ", e);
5529
+ console.error(tag6, "e: ", e);
5437
5530
  return { success: false };
5438
5531
  }
5439
5532
  };
5440
5533
  this.refresh = async () => {
5441
- const tag5 = `${TAG9} | refresh | `;
5534
+ const tag6 = `${TAG9} | refresh | `;
5442
5535
  try {
5443
5536
  await this.sync();
5444
5537
  return this.balances;
5445
5538
  } catch (e) {
5446
- console.error(tag5, "e: ", e);
5539
+ console.error(tag6, "e: ", e);
5447
5540
  throw e;
5448
5541
  }
5449
5542
  };
5450
5543
  this.setAssetContext = async function(asset) {
5451
- const tag5 = `${TAG9} | setAssetContext | `;
5544
+ const tag6 = `${TAG9} | setAssetContext | `;
5452
5545
  try {
5453
5546
  if (!asset) {
5454
5547
  this.assetContext = null;
@@ -5460,7 +5553,7 @@ class SDK {
5460
5553
  asset.networkId = caipToNetworkId7(asset.caip);
5461
5554
  if (!this.pubkeys || this.pubkeys.length === 0) {
5462
5555
  const errorMsg = `Cannot set asset context for ${asset.caip} - no pubkeys loaded. Please initialize wallet first.`;
5463
- console.error(tag5, errorMsg);
5556
+ console.error(tag6, errorMsg);
5464
5557
  throw new Error(errorMsg);
5465
5558
  }
5466
5559
  const pubkeysForNetwork = this.pubkeys.filter((e) => {
@@ -5475,8 +5568,8 @@ class SDK {
5475
5568
  });
5476
5569
  if (pubkeysForNetwork.length === 0) {
5477
5570
  const errorMsg = `Cannot set asset context for ${asset.caip} - no address/xpub found for network ${asset.networkId}`;
5478
- console.error(tag5, errorMsg);
5479
- console.error(tag5, "Available networks in pubkeys:", [
5571
+ console.error(tag6, errorMsg);
5572
+ console.error(tag6, "Available networks in pubkeys:", [
5480
5573
  ...new Set(this.pubkeys.flatMap((p2) => p2.networks || []))
5481
5574
  ]);
5482
5575
  throw new Error(errorMsg);
@@ -5486,43 +5579,43 @@ class SDK {
5486
5579
  const xpubFound = pubkeysForNetwork.some((p2) => p2.type === "xpub" && p2.pubkey);
5487
5580
  if (!xpubFound) {
5488
5581
  const errorMsg = `Cannot set asset context for UTXO chain ${asset.caip} - xpub required but not found`;
5489
- console.error(tag5, errorMsg);
5582
+ console.error(tag6, errorMsg);
5490
5583
  throw new Error(errorMsg);
5491
5584
  }
5492
5585
  }
5493
5586
  const hasValidAddress = pubkeysForNetwork.some((p2) => p2.address || p2.master || p2.pubkey);
5494
5587
  if (!hasValidAddress) {
5495
5588
  const errorMsg = `Cannot set asset context for ${asset.caip} - no valid address found in pubkeys`;
5496
- console.error(tag5, errorMsg);
5589
+ console.error(tag6, errorMsg);
5497
5590
  throw new Error(errorMsg);
5498
5591
  }
5499
- console.log(tag5, `✅ Validated: Found ${pubkeysForNetwork.length} addresses for ${asset.networkId}`);
5592
+ console.log(tag6, `✅ Validated: Found ${pubkeysForNetwork.length} addresses for ${asset.networkId}`);
5500
5593
  let freshPriceUsd = 0;
5501
5594
  try {
5502
5595
  if (!asset.caip || typeof asset.caip !== "string" || !asset.caip.includes(":")) {
5503
- console.warn(tag5, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
5596
+ console.warn(tag6, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
5504
5597
  } else {
5505
- console.log(tag5, "Fetching fresh market price for:", asset.caip);
5598
+ console.log(tag6, "Fetching fresh market price for:", asset.caip);
5506
5599
  const marketData = await this.pioneer.GetMarketInfo([asset.caip]);
5507
- console.log(tag5, "Market data response:", marketData);
5600
+ console.log(tag6, "Market data response:", marketData);
5508
5601
  if (marketData && marketData.data && marketData.data.length > 0) {
5509
5602
  freshPriceUsd = marketData.data[0];
5510
- console.log(tag5, "✅ Fresh market price:", freshPriceUsd);
5603
+ console.log(tag6, "✅ Fresh market price:", freshPriceUsd);
5511
5604
  } else {
5512
- console.warn(tag5, "No market data returned for:", asset.caip);
5605
+ console.warn(tag6, "No market data returned for:", asset.caip);
5513
5606
  }
5514
5607
  }
5515
5608
  } catch (marketError) {
5516
- console.error(tag5, "Error fetching market price:", marketError);
5609
+ console.error(tag6, "Error fetching market price:", marketError);
5517
5610
  }
5518
5611
  let assetInfo = this.assetsMap.get(asset.caip.toLowerCase());
5519
- console.log(tag5, "assetInfo: ", assetInfo);
5612
+ console.log(tag6, "assetInfo: ", assetInfo);
5520
5613
  let assetInfoDiscovery = assetData2[asset.caip];
5521
- console.log(tag5, "assetInfoDiscovery: ", assetInfoDiscovery);
5614
+ console.log(tag6, "assetInfoDiscovery: ", assetInfoDiscovery);
5522
5615
  if (assetInfoDiscovery)
5523
5616
  assetInfo = assetInfoDiscovery;
5524
5617
  if (!assetInfo) {
5525
- console.log(tag5, "Building placeholder asset!");
5618
+ console.log(tag6, "Building placeholder asset!");
5526
5619
  assetInfo = {
5527
5620
  caip: asset.caip.toLowerCase(),
5528
5621
  networkId: asset.networkId,
@@ -5539,30 +5632,30 @@ class SDK {
5539
5632
  const valueUsd = parseFloat(matchingBalances[0].valueUsd);
5540
5633
  if (balance > 0 && valueUsd > 0) {
5541
5634
  priceValue = valueUsd / balance;
5542
- console.log(tag5, "calculated priceUsd from valueUsd/balance:", priceValue);
5635
+ console.log(tag6, "calculated priceUsd from valueUsd/balance:", priceValue);
5543
5636
  }
5544
5637
  }
5545
5638
  if (priceValue && priceValue > 0) {
5546
- console.log(tag5, "detected priceUsd from balance:", priceValue);
5639
+ console.log(tag6, "detected priceUsd from balance:", priceValue);
5547
5640
  assetInfo.priceUsd = priceValue;
5548
5641
  }
5549
5642
  }
5550
5643
  if (freshPriceUsd && freshPriceUsd > 0) {
5551
5644
  assetInfo.priceUsd = freshPriceUsd;
5552
- console.log(tag5, "✅ Using fresh market price:", freshPriceUsd);
5645
+ console.log(tag6, "✅ Using fresh market price:", freshPriceUsd);
5553
5646
  let totalBalance = 0;
5554
5647
  let totalValueUsd = 0;
5555
- console.log(tag5, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5648
+ console.log(tag6, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5556
5649
  for (const balanceEntry of matchingBalances) {
5557
5650
  const balance = parseFloat(balanceEntry.balance) || 0;
5558
5651
  const valueUsd = parseFloat(balanceEntry.valueUsd) || 0;
5559
5652
  totalBalance += balance;
5560
5653
  totalValueUsd += valueUsd;
5561
- console.log(tag5, ` Balance entry: ${balance} (${valueUsd} USD)`);
5654
+ console.log(tag6, ` Balance entry: ${balance} (${valueUsd} USD)`);
5562
5655
  }
5563
5656
  assetInfo.balance = totalBalance.toString();
5564
5657
  assetInfo.valueUsd = totalValueUsd.toFixed(2);
5565
- console.log(tag5, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5658
+ console.log(tag6, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5566
5659
  }
5567
5660
  const assetBalances = this.balances.filter((b3) => b3.caip === asset.caip);
5568
5661
  const assetPubkeys = this.pubkeys.filter((p2) => p2.networks && Array.isArray(p2.networks) && p2.networks.includes(caipToNetworkId7(asset.caip)) || caipToNetworkId7(asset.caip).includes("eip155") && p2.networks && Array.isArray(p2.networks) && p2.networks.some((n2) => n2.startsWith("eip155")));
@@ -5582,7 +5675,7 @@ class SDK {
5582
5675
  const balanceAmount = parseFloat(balance.balance || 0);
5583
5676
  balance.valueUsd = (balanceAmount * freshPriceUsd).toString();
5584
5677
  }
5585
- console.log(tag5, "Updated all balances with fresh price data");
5678
+ console.log(tag6, "Updated all balances with fresh price data");
5586
5679
  }
5587
5680
  this.assetContext = finalAssetContext;
5588
5681
  if (asset.isToken || asset.type === "token" || assetInfo.isToken || assetInfo.type === "token") {
@@ -5634,20 +5727,20 @@ class SDK {
5634
5727
  const currentContextValid = this.pubkeyContext?.networks?.includes(networkId);
5635
5728
  if (!this.pubkeyContext || !currentContextValid) {
5636
5729
  this.pubkeyContext = assetPubkeys[0];
5637
- console.log(tag5, "Auto-set pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey);
5730
+ console.log(tag6, "Auto-set pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey);
5638
5731
  } else {
5639
- console.log(tag5, "Preserving existing pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey, `(addressNList: [${(this.pubkeyContext.addressNList || this.pubkeyContext.addressNListMaster).join(", ")}])`);
5732
+ console.log(tag6, "Preserving existing pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey, `(addressNList: [${(this.pubkeyContext.addressNList || this.pubkeyContext.addressNListMaster).join(", ")}])`);
5640
5733
  }
5641
5734
  }
5642
5735
  this.events.emit("SET_ASSET_CONTEXT", this.assetContext);
5643
5736
  return this.assetContext;
5644
5737
  } catch (e) {
5645
- console.error(tag5, "e: ", e);
5738
+ console.error(tag6, "e: ", e);
5646
5739
  throw e;
5647
5740
  }
5648
5741
  };
5649
5742
  this.setPubkeyContext = async function(pubkey) {
5650
- let tag5 = `${TAG9} | setPubkeyContext | `;
5743
+ let tag6 = `${TAG9} | setPubkeyContext | `;
5651
5744
  try {
5652
5745
  if (!pubkey)
5653
5746
  throw Error("pubkey is required");
@@ -5655,31 +5748,31 @@ class SDK {
5655
5748
  throw Error("invalid pubkey: missing pubkey or address");
5656
5749
  const exists = this.pubkeys.some((pk) => pk.pubkey === pubkey.pubkey || pk.address === pubkey.address || pk.pubkey === pubkey.address);
5657
5750
  if (!exists) {
5658
- console.warn(tag5, "Pubkey not found in current pubkeys array");
5751
+ console.warn(tag6, "Pubkey not found in current pubkeys array");
5659
5752
  }
5660
5753
  this.pubkeyContext = pubkey;
5661
- console.log(tag5, "Pubkey context set to:", pubkey.address || pubkey.pubkey, "note:", pubkey.note, "addressNList:", pubkey.addressNList || pubkey.addressNListMaster);
5754
+ console.log(tag6, "Pubkey context set to:", pubkey.address || pubkey.pubkey, "note:", pubkey.note, "addressNList:", pubkey.addressNList || pubkey.addressNListMaster);
5662
5755
  return true;
5663
5756
  } catch (e) {
5664
- console.error(tag5, "e: ", e);
5757
+ console.error(tag6, "e: ", e);
5665
5758
  throw e;
5666
5759
  }
5667
5760
  };
5668
5761
  this.setOutboundAssetContext = async function(asset) {
5669
- const tag5 = `${TAG9} | setOutputAssetContext | `;
5762
+ const tag6 = `${TAG9} | setOutputAssetContext | `;
5670
5763
  try {
5671
- console.log(tag5, "0. asset: ", asset);
5764
+ console.log(tag6, "0. asset: ", asset);
5672
5765
  if (!asset) {
5673
5766
  this.outboundAssetContext = null;
5674
5767
  return;
5675
5768
  }
5676
- console.log(tag5, "1 asset: ", asset);
5769
+ console.log(tag6, "1 asset: ", asset);
5677
5770
  if (!asset.caip)
5678
5771
  throw Error("Invalid Asset! missing caip!");
5679
5772
  if (!asset.networkId)
5680
5773
  asset.networkId = caipToNetworkId7(asset.caip);
5681
- console.log(tag5, "networkId: ", asset.networkId);
5682
- console.log(tag5, "this.pubkeys: ", this.pubkeys);
5774
+ console.log(tag6, "networkId: ", asset.networkId);
5775
+ console.log(tag6, "this.pubkeys: ", this.pubkeys);
5683
5776
  const pubkey = this.pubkeys.find((p2) => {
5684
5777
  if (!p2.networks || !Array.isArray(p2.networks))
5685
5778
  return false;
@@ -5694,23 +5787,23 @@ class SDK {
5694
5787
  let freshPriceUsd = 0;
5695
5788
  try {
5696
5789
  if (!asset.caip || typeof asset.caip !== "string" || !asset.caip.includes(":")) {
5697
- console.warn(tag5, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
5790
+ console.warn(tag6, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
5698
5791
  } else {
5699
- console.log(tag5, "Fetching fresh market price for:", asset.caip);
5792
+ console.log(tag6, "Fetching fresh market price for:", asset.caip);
5700
5793
  const marketData = await this.pioneer.GetMarketInfo([asset.caip]);
5701
- console.log(tag5, "Market data response:", marketData);
5794
+ console.log(tag6, "Market data response:", marketData);
5702
5795
  if (marketData && marketData.data && marketData.data.length > 0) {
5703
5796
  freshPriceUsd = marketData.data[0];
5704
- console.log(tag5, "✅ Fresh market price:", freshPriceUsd);
5797
+ console.log(tag6, "✅ Fresh market price:", freshPriceUsd);
5705
5798
  } else {
5706
- console.warn(tag5, "No market data returned for:", asset.caip);
5799
+ console.warn(tag6, "No market data returned for:", asset.caip);
5707
5800
  }
5708
5801
  }
5709
5802
  } catch (marketError) {
5710
- console.error(tag5, "Error fetching market price:", marketError);
5803
+ console.error(tag6, "Error fetching market price:", marketError);
5711
5804
  }
5712
5805
  let assetInfo = this.assetsMap.get(asset.caip.toLowerCase());
5713
- console.log(tag5, "assetInfo: ", assetInfo);
5806
+ console.log(tag6, "assetInfo: ", assetInfo);
5714
5807
  if (!assetInfo) {
5715
5808
  assetInfo = {
5716
5809
  caip: asset.caip.toLowerCase(),
@@ -5728,45 +5821,45 @@ class SDK {
5728
5821
  const valueUsd = parseFloat(matchingBalances[0].valueUsd);
5729
5822
  if (balance > 0 && valueUsd > 0) {
5730
5823
  priceValue = valueUsd / balance;
5731
- console.log(tag5, "calculated priceUsd from valueUsd/balance:", priceValue);
5824
+ console.log(tag6, "calculated priceUsd from valueUsd/balance:", priceValue);
5732
5825
  }
5733
5826
  }
5734
5827
  if (priceValue && priceValue > 0) {
5735
- console.log(tag5, "detected priceUsd from balance:", priceValue);
5828
+ console.log(tag6, "detected priceUsd from balance:", priceValue);
5736
5829
  assetInfo.priceUsd = priceValue;
5737
5830
  }
5738
5831
  }
5739
5832
  if (freshPriceUsd && freshPriceUsd > 0) {
5740
5833
  assetInfo.priceUsd = freshPriceUsd;
5741
- console.log(tag5, "✅ Using fresh market price:", freshPriceUsd);
5834
+ console.log(tag6, "✅ Using fresh market price:", freshPriceUsd);
5742
5835
  let totalBalance = 0;
5743
5836
  let totalValueUsd = 0;
5744
- console.log(tag5, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5837
+ console.log(tag6, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5745
5838
  for (const balanceEntry of matchingBalances) {
5746
5839
  const balance = parseFloat(balanceEntry.balance) || 0;
5747
5840
  const valueUsd = parseFloat(balanceEntry.valueUsd) || 0;
5748
5841
  totalBalance += balance;
5749
5842
  totalValueUsd += valueUsd;
5750
- console.log(tag5, ` Balance entry: ${balance} (${valueUsd} USD)`);
5843
+ console.log(tag6, ` Balance entry: ${balance} (${valueUsd} USD)`);
5751
5844
  }
5752
5845
  assetInfo.balance = totalBalance.toString();
5753
5846
  assetInfo.valueUsd = totalValueUsd.toFixed(2);
5754
- console.log(tag5, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5847
+ console.log(tag6, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5755
5848
  }
5756
- console.log(tag5, "CHECKPOINT 1");
5849
+ console.log(tag6, "CHECKPOINT 1");
5757
5850
  this.outboundAssetContext = { ...assetInfo, ...asset, ...pubkey };
5758
- console.log(tag5, "CHECKPOINT 3");
5759
- console.log(tag5, "outboundAssetContext: assetInfo: ", assetInfo);
5851
+ console.log(tag6, "CHECKPOINT 3");
5852
+ console.log(tag6, "outboundAssetContext: assetInfo: ", assetInfo);
5760
5853
  if (asset.caip) {
5761
5854
  this.outboundBlockchainContext = caipToNetworkId7(asset.caip);
5762
5855
  } else if (asset.networkId) {
5763
5856
  this.outboundBlockchainContext = asset.networkId;
5764
5857
  }
5765
- console.log(tag5, "CHECKPOINT 4");
5858
+ console.log(tag6, "CHECKPOINT 4");
5766
5859
  this.events.emit("SET_OUTBOUND_ASSET_CONTEXT", this.outboundAssetContext);
5767
5860
  return this.outboundAssetContext;
5768
5861
  } catch (e) {
5769
- console.error(tag5, "e: ", e);
5862
+ console.error(tag6, "e: ", e);
5770
5863
  throw e;
5771
5864
  }
5772
5865
  };