@pioneer-platform/pioneer-sdk 4.21.1 → 4.21.3

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
@@ -140,46 +140,44 @@ var require_lib = __commonJS((exports) => {
140
140
  return { value: op[0] ? op[1] : undefined, done: true };
141
141
  }
142
142
  };
143
+ var __importDefault = exports && exports.__importDefault || function(mod) {
144
+ return mod && mod.__esModule ? mod : { default: mod };
145
+ };
143
146
  Object.defineProperty(exports, "__esModule", { value: true });
144
147
  exports.Pioneer = undefined;
145
- var Swagger;
146
- var log;
147
- if (typeof window === "undefined") {
148
- Swagger = __require("swagger-client");
149
- log = __require("@pioneer-platform/loggerdog")();
150
- } else {
151
- Swagger = null;
152
- log = {
153
- debug: function() {
154
- var args = [];
155
- for (var _i = 0;_i < arguments.length; _i++) {
156
- args[_i] = arguments[_i];
157
- }
158
- return console.debug.apply(console, args);
159
- },
160
- info: function() {
161
- var args = [];
162
- for (var _i = 0;_i < arguments.length; _i++) {
163
- args[_i] = arguments[_i];
164
- }
165
- return console.info.apply(console, args);
166
- },
167
- warn: function() {
168
- var args = [];
169
- for (var _i = 0;_i < arguments.length; _i++) {
170
- args[_i] = arguments[_i];
171
- }
172
- return console.warn.apply(console, args);
173
- },
174
- error: function() {
175
- var args = [];
176
- for (var _i = 0;_i < arguments.length; _i++) {
177
- args[_i] = arguments[_i];
178
- }
179
- return console.error.apply(console, args);
148
+ var swagger_client_1 = __importDefault(__require("swagger-client"));
149
+ var loggerdog_1 = __importDefault(__require("@pioneer-platform/loggerdog"));
150
+ var log = typeof window === "undefined" ? (0, loggerdog_1.default)() : {
151
+ debug: function() {
152
+ var args = [];
153
+ for (var _i = 0;_i < arguments.length; _i++) {
154
+ args[_i] = arguments[_i];
180
155
  }
181
- };
182
- }
156
+ return console.debug.apply(console, args);
157
+ },
158
+ info: function() {
159
+ var args = [];
160
+ for (var _i = 0;_i < arguments.length; _i++) {
161
+ args[_i] = arguments[_i];
162
+ }
163
+ return console.info.apply(console, args);
164
+ },
165
+ warn: function() {
166
+ var args = [];
167
+ for (var _i = 0;_i < arguments.length; _i++) {
168
+ args[_i] = arguments[_i];
169
+ }
170
+ return console.warn.apply(console, args);
171
+ },
172
+ error: function() {
173
+ var args = [];
174
+ for (var _i = 0;_i < arguments.length; _i++) {
175
+ args[_i] = arguments[_i];
176
+ }
177
+ return console.error.apply(console, args);
178
+ }
179
+ };
180
+ var Swagger = swagger_client_1.default;
183
181
  var TAG = " | Client | ";
184
182
  function customHttpClient(req) {
185
183
  var _this = this;
@@ -189,7 +187,7 @@ var require_lib = __commonJS((exports) => {
189
187
  }, 60000);
190
188
  log.debug(TAG, "HTTP request URL:", req.url);
191
189
  log.debug(TAG, "HTTP request details:", req);
192
- if (Swagger && Swagger.http) {
190
+ if (Swagger.http) {
193
191
  Swagger.http(req).then(function(response) {
194
192
  clearTimeout(timer);
195
193
  resolve(response);
@@ -243,11 +241,11 @@ var require_lib = __commonJS((exports) => {
243
241
  this.spec = spec;
244
242
  this.queryKey = config.queryKey;
245
243
  this.pioneer = {};
246
- this.timeout = config.queryKey || 45000;
244
+ this.timeout = config.timeout || 45000;
247
245
  }
248
246
  Pioneer2.prototype.init = function() {
249
247
  return __awaiter(this, undefined, undefined, function() {
250
- var tag, _a, specResponse, specData_1, e_1;
248
+ var tag, _a, e_1;
251
249
  var _this = this;
252
250
  return __generator(this, function(_b) {
253
251
  switch (_b.label) {
@@ -255,11 +253,9 @@ var require_lib = __commonJS((exports) => {
255
253
  tag = TAG + " | init | ";
256
254
  _b.label = 1;
257
255
  case 1:
258
- _b.trys.push([1, 7, , 8]);
256
+ _b.trys.push([1, 3, , 4]);
259
257
  if (!this.queryKey)
260
258
  throw Error(" You must create an api key! ");
261
- if (!Swagger)
262
- return [3, 3];
263
259
  _a = this;
264
260
  return [4, new Swagger({
265
261
  url: this.spec,
@@ -285,73 +281,6 @@ var require_lib = __commonJS((exports) => {
285
281
  })];
286
282
  case 2:
287
283
  _a.client = _b.sent();
288
- return [3, 6];
289
- case 3:
290
- return [4, fetch(this.spec)];
291
- case 4:
292
- specResponse = _b.sent();
293
- return [4, specResponse.json()];
294
- case 5:
295
- specData_1 = _b.sent();
296
- this.client = {
297
- spec: specData_1,
298
- execute: function(request) {
299
- return __awaiter(_this, undefined, undefined, function() {
300
- var operationId, parameters, requestBody, targetPath, targetMethod, path, method, baseUrl, finalPath, _i, _a2, _b2, key, value, placeholder, url, httpReq;
301
- return __generator(this, function(_c) {
302
- switch (_c.label) {
303
- case 0:
304
- operationId = request.operationId, parameters = request.parameters, requestBody = request.requestBody;
305
- targetPath = "";
306
- targetMethod = "";
307
- for (path in specData_1.paths) {
308
- for (method in specData_1.paths[path]) {
309
- if (specData_1.paths[path][method].operationId === operationId) {
310
- targetPath = path;
311
- targetMethod = method;
312
- break;
313
- }
314
- }
315
- if (targetPath)
316
- break;
317
- }
318
- if (!targetPath) {
319
- throw new Error("Operation ".concat(operationId, " not found in spec"));
320
- }
321
- baseUrl = this.spec.replace("/spec/swagger.json", "");
322
- if (specData_1.servers && specData_1.servers.length > 0) {
323
- baseUrl = specData_1.servers[0].url;
324
- }
325
- finalPath = targetPath;
326
- if (parameters) {
327
- for (_i = 0, _a2 = Object.entries(parameters);_i < _a2.length; _i++) {
328
- _b2 = _a2[_i], key = _b2[0], value = _b2[1];
329
- placeholder = "{".concat(key, "}");
330
- if (finalPath.includes(placeholder)) {
331
- finalPath = finalPath.replace(placeholder, encodeURIComponent(String(value)));
332
- }
333
- }
334
- }
335
- url = "".concat(baseUrl).concat(finalPath);
336
- httpReq = {
337
- method: targetMethod.toUpperCase(),
338
- url,
339
- headers: {
340
- Authorization: this.queryKey,
341
- "Content-Type": "application/json"
342
- },
343
- body: requestBody
344
- };
345
- return [4, customHttpClient(httpReq)];
346
- case 1:
347
- return [2, _c.sent()];
348
- }
349
- });
350
- });
351
- }
352
- };
353
- _b.label = 6;
354
- case 6:
355
284
  Object.keys(this.client.spec.paths).forEach(function(path) {
356
285
  Object.keys(_this.client.spec.paths[path]).forEach(function(method) {
357
286
  var operationId = _this.client.spec.paths[path][method].operationId;
@@ -409,11 +338,11 @@ var require_lib = __commonJS((exports) => {
409
338
  });
410
339
  });
411
340
  return [2, this.pioneer];
412
- case 7:
341
+ case 3:
413
342
  e_1 = _b.sent();
414
343
  log.error(TAG, "Initialization error:", e_1);
415
344
  throw e_1;
416
- case 8:
345
+ case 4:
417
346
  return [2];
418
347
  }
419
348
  });
@@ -837,21 +766,101 @@ function createBalanceIdentifier(caip, pubkey) {
837
766
  return `${caip}:${pubkey}`;
838
767
  }
839
768
 
769
+ // src/charts/custom-tokens.ts
770
+ var tag = "| charts-custom-tokens |";
771
+ async function fetchCustomTokens(params, balances) {
772
+ const { pioneer, pubkeys, blockchains, context } = params;
773
+ console.log(tag, "Fetching custom tokens...");
774
+ const evmPubkey = pubkeys.find((e) => e.networks && Array.isArray(e.networks) && e.networks.includes("eip155:*"));
775
+ const primaryAddress = evmPubkey?.address || evmPubkey?.master;
776
+ if (!primaryAddress) {
777
+ console.log(tag, "No EVM address found, skipping custom tokens");
778
+ return;
779
+ }
780
+ console.log(tag, "Using EVM address for custom tokens:", primaryAddress);
781
+ const supportedNetworks = blockchains.filter((net) => net.startsWith("eip155:"));
782
+ if (supportedNetworks.length === 0) {
783
+ console.log(tag, "No EVM networks for custom tokens");
784
+ return;
785
+ }
786
+ console.log(tag, `Checking custom tokens on ${supportedNetworks.length} networks`);
787
+ for (const networkId of supportedNetworks) {
788
+ try {
789
+ const response = await pioneer.GetCustomTokens({ networkId, address: primaryAddress });
790
+ const customTokens = response?.data?.tokens || [];
791
+ console.log(tag, `Found ${customTokens.length} custom tokens on ${networkId}`);
792
+ for (const token of customTokens) {
793
+ const chartBalance = processCustomToken(token, primaryAddress, context, blockchains);
794
+ if (chartBalance && !checkDuplicateBalance(balances, chartBalance.caip, chartBalance.pubkey)) {
795
+ balances.push(chartBalance);
796
+ console.log(tag, `Added custom token: ${chartBalance.symbol} = ${chartBalance.balance}`);
797
+ }
798
+ }
799
+ } catch (error) {
800
+ console.error(tag, `Error fetching custom tokens for ${networkId}:`, error.message);
801
+ }
802
+ }
803
+ console.log(tag, `Custom tokens complete. Total balances: ${balances.length}`);
804
+ }
805
+ function processCustomToken(token, primaryAddress, context, blockchains) {
806
+ if (!token.assetCaip || !token.networkId) {
807
+ return null;
808
+ }
809
+ let extractedNetworkId = token.networkId;
810
+ if (token.assetCaip.includes("/denom:")) {
811
+ const parts = token.assetCaip.split("/denom:");
812
+ if (parts.length > 0) {
813
+ extractedNetworkId = parts[0];
814
+ }
815
+ } else if (token.networkId && token.networkId.includes("/")) {
816
+ extractedNetworkId = token.networkId.split("/")[0];
817
+ }
818
+ const isEip155 = extractedNetworkId.startsWith("eip155:");
819
+ if (!isEip155 && !blockchains.includes(extractedNetworkId)) {
820
+ return null;
821
+ }
822
+ const tokenAssetInfo = hydrateAssetData(token.assetCaip);
823
+ const tokenPubkey = token.pubkey || primaryAddress;
824
+ const chartBalance = {
825
+ context,
826
+ chart: "pioneer",
827
+ contextType: context.split(":")[0],
828
+ name: tokenAssetInfo?.name || token.token?.name || "Unknown Custom Token",
829
+ caip: token.assetCaip,
830
+ icon: tokenAssetInfo?.icon || token.token?.icon || "",
831
+ pubkey: tokenPubkey,
832
+ ticker: tokenAssetInfo?.symbol || token.token?.symbol || "UNK",
833
+ ref: `${context}${token.assetCaip}`,
834
+ identifier: createBalanceIdentifier(token.assetCaip, tokenPubkey),
835
+ networkId: extractedNetworkId,
836
+ symbol: tokenAssetInfo?.symbol || token.token?.symbol || "UNK",
837
+ type: tokenAssetInfo?.type || "erc20",
838
+ token: true,
839
+ decimal: tokenAssetInfo?.decimal || token.token?.decimal,
840
+ balance: token.token?.balance?.toString() || "0",
841
+ priceUsd: token.token?.price || 0,
842
+ valueUsd: token.token?.balanceUSD || 0,
843
+ updated: new Date().getTime()
844
+ };
845
+ return chartBalance;
846
+ }
847
+
840
848
  // src/charts/evm.ts
841
- var tag = "| charts-evm |";
849
+ var tag2 = "| charts-evm |";
842
850
  async function getEvmCharts(params) {
843
851
  const { blockchains, pioneer, pubkeys, context } = params;
844
852
  const balances = [];
845
853
  const evmPubkey = pubkeys.find((e) => e.networks && Array.isArray(e.networks) && e.networks.includes("eip155:*"));
846
854
  const primaryAddress = evmPubkey?.address || evmPubkey?.master;
847
- console.log(tag, "Total pubkeys available:", pubkeys.length);
848
- console.log(tag, "Blockchains to process:", blockchains);
855
+ console.log(tag2, "Total pubkeys available:", pubkeys.length);
856
+ console.log(tag2, "Blockchains to process:", blockchains);
849
857
  if (!primaryAddress) {
850
- console.log(tag, "No EVM address found, skipping portfolio lookup (Zapper only supports Ethereum)");
858
+ console.log(tag2, "No EVM address found, skipping portfolio lookup (Zapper only supports Ethereum)");
851
859
  return balances;
852
860
  }
853
- console.log(tag, "Using EVM address for portfolio:", primaryAddress);
861
+ console.log(tag2, "Using EVM address for portfolio:", primaryAddress);
854
862
  await fetchStableCoins(pioneer, primaryAddress, blockchains, balances, context);
863
+ await fetchCustomTokens({ blockchains, pioneer, pubkeys, context }, balances);
855
864
  try {
856
865
  let portfolio = await pioneer.GetPortfolio({
857
866
  networkId: "eip155:1",
@@ -859,10 +868,10 @@ async function getEvmCharts(params) {
859
868
  });
860
869
  portfolio = portfolio.data?.data || portfolio.data;
861
870
  if (!portfolio || !portfolio.balances) {
862
- console.error(tag, "No portfolio.balances found:", portfolio);
871
+ console.error(tag2, "No portfolio.balances found:", portfolio);
863
872
  return balances;
864
873
  }
865
- console.log(tag, `Portfolio returned ${portfolio.balances.length} balances`);
874
+ console.log(tag2, `Portfolio returned ${portfolio.balances.length} balances`);
866
875
  let processedCount = 0;
867
876
  let skippedCount = 0;
868
877
  for (const balance of portfolio.balances) {
@@ -876,9 +885,9 @@ async function getEvmCharts(params) {
876
885
  skippedCount++;
877
886
  }
878
887
  }
879
- console.log(tag, `Processed ${processedCount} balances, skipped ${skippedCount}`);
888
+ console.log(tag2, `Processed ${processedCount} balances, skipped ${skippedCount}`);
880
889
  if (portfolio.tokens && portfolio.tokens.length > 0) {
881
- console.log(tag, "Processing portfolio.tokens:", portfolio.tokens.length);
890
+ console.log(tag2, "Processing portfolio.tokens:", portfolio.tokens.length);
882
891
  for (const token of portfolio.tokens) {
883
892
  const processedToken = processPortfolioToken(token, primaryAddress, context, blockchains);
884
893
  if (processedToken && !checkDuplicateBalance(balances, processedToken.caip, processedToken.pubkey)) {
@@ -887,13 +896,13 @@ async function getEvmCharts(params) {
887
896
  }
888
897
  }
889
898
  } catch (e) {
890
- console.error(tag, "Error fetching portfolio:", e);
899
+ console.error(tag2, "Error fetching portfolio:", e);
891
900
  }
892
901
  return balances;
893
902
  }
894
903
  function processPortfolioBalance(balance, primaryAddress, context, blockchains) {
895
904
  if (!balance.caip) {
896
- console.error(tag, "No caip found for:", balance);
905
+ console.error(tag2, "No caip found for:", balance);
897
906
  return null;
898
907
  }
899
908
  const networkId = balance.caip.split("/")[0];
@@ -911,7 +920,7 @@ function processPortfolioBalance(balance, primaryAddress, context, blockchains)
911
920
  const valueNum = parseFloat(balance.valueUsd.toString());
912
921
  if (balanceNum > 0 && valueNum > 0) {
913
922
  calculatedPrice = valueNum / balanceNum;
914
- console.log(tag, `Calculated price from value/balance: ${calculatedPrice} for ${balance.caip}`);
923
+ console.log(tag2, `Calculated price from value/balance: ${calculatedPrice} for ${balance.caip}`);
915
924
  }
916
925
  }
917
926
  const chartBalance = {
@@ -985,70 +994,70 @@ function processPortfolioToken(token, primaryAddress, context, blockchains) {
985
994
  return chartBalance;
986
995
  }
987
996
  async function fetchStableCoins(pioneer, primaryAddress, blockchains, balances, context) {
988
- console.log(tag, "Fetching stable coins for redundancy...");
997
+ console.log(tag2, "Fetching stable coins for redundancy...");
989
998
  const supportedNetworks = ["eip155:1", "eip155:137", "eip155:8453", "eip155:56"];
990
999
  const networksToCheck = blockchains.filter((net) => supportedNetworks.includes(net));
991
1000
  if (networksToCheck.length === 0) {
992
- console.log(tag, "No supported networks for stable coins");
1001
+ console.log(tag2, "No supported networks for stable coins");
993
1002
  return;
994
1003
  }
995
- console.log(tag, `Checking stable coins on ${networksToCheck.length} networks`);
1004
+ console.log(tag2, `Checking stable coins on ${networksToCheck.length} networks`);
996
1005
  for (const networkId of networksToCheck) {
997
1006
  try {
998
1007
  const response = await pioneer.GetStableCoins({ networkId, address: primaryAddress });
999
1008
  const stableCoins = response?.data?.tokens || [];
1000
- console.log(tag, `Found ${stableCoins.length} stable coins on ${networkId}`);
1009
+ console.log(tag2, `Found ${stableCoins.length} stable coins on ${networkId}`);
1001
1010
  for (const token of stableCoins) {
1002
1011
  const chartBalance = processPortfolioToken(token, primaryAddress, context, blockchains);
1003
1012
  if (chartBalance && !checkDuplicateBalance(balances, chartBalance.caip, chartBalance.pubkey)) {
1004
1013
  balances.push(chartBalance);
1005
- console.log(tag, `Added stable coin: ${chartBalance.symbol} = ${chartBalance.balance}`);
1014
+ console.log(tag2, `Added stable coin: ${chartBalance.symbol} = ${chartBalance.balance}`);
1006
1015
  }
1007
1016
  }
1008
1017
  } catch (error) {
1009
- console.error(tag, `Error fetching stable coins for ${networkId}:`, error.message);
1018
+ console.error(tag2, `Error fetching stable coins for ${networkId}:`, error.message);
1010
1019
  }
1011
1020
  }
1012
- console.log(tag, `Stable coin redundancy complete. Total balances: ${balances.length}`);
1021
+ console.log(tag2, `Stable coin redundancy complete. Total balances: ${balances.length}`);
1013
1022
  }
1014
1023
 
1015
1024
  // src/charts/maya.ts
1016
- var tag2 = "| charts-maya |";
1025
+ var tag3 = "| charts-maya |";
1017
1026
  async function getMayaCharts(params, existingBalances) {
1018
1027
  const { blockchains, pioneer, pubkeys, context } = params;
1019
1028
  const balances = [];
1020
1029
  try {
1021
1030
  const mayaPubkey = pubkeys.find((p) => p.networks && Array.isArray(p.networks) && p.networks.includes("cosmos:mayachain-mainnet-v1"));
1022
1031
  if (!mayaPubkey || !mayaPubkey.address) {
1023
- console.log(tag2, "No MAYA pubkey found, skipping MAYA token fetch");
1032
+ console.log(tag3, "No MAYA pubkey found, skipping MAYA token fetch");
1024
1033
  return balances;
1025
1034
  }
1026
1035
  if (!blockchains.includes("cosmos:mayachain-mainnet-v1")) {
1027
- console.log(tag2, "MAYA network not in blockchains list, skipping MAYA token fetch");
1036
+ console.log(tag3, "MAYA network not in blockchains list, skipping MAYA token fetch");
1028
1037
  return balances;
1029
1038
  }
1030
1039
  const hasMayaToken = existingBalances.some((b2) => b2.caip === "cosmos:mayachain-mainnet-v1/denom:maya");
1031
1040
  if (hasMayaToken) {
1032
- console.log(tag2, "MAYA token already exists in balances, skipping");
1041
+ console.log(tag3, "MAYA token already exists in balances, skipping");
1033
1042
  return balances;
1034
1043
  }
1035
- console.log(tag2, "MAYA token not found in portfolio, fetching separately...");
1036
- console.log(tag2, "MAYA pubkey address:", mayaPubkey.address);
1044
+ console.log(tag3, "MAYA token not found in portfolio, fetching separately...");
1045
+ console.log(tag3, "MAYA pubkey address:", mayaPubkey.address);
1037
1046
  const mayaBalanceResponse = await pioneer.GetPortfolioBalances([
1038
1047
  {
1039
1048
  caip: "cosmos:mayachain-mainnet-v1/denom:maya",
1040
1049
  pubkey: mayaPubkey.address
1041
1050
  }
1042
1051
  ]);
1043
- console.log(tag2, "MAYA balance response:", JSON.stringify(mayaBalanceResponse?.data, null, 2));
1052
+ console.log(tag3, "MAYA balance response:", JSON.stringify(mayaBalanceResponse?.data, null, 2));
1044
1053
  if (!mayaBalanceResponse?.data || mayaBalanceResponse.data.length === 0) {
1045
- console.log(tag2, "No MAYA token balance returned from GetPortfolioBalances API");
1054
+ console.log(tag3, "No MAYA token balance returned from GetPortfolioBalances API");
1046
1055
  return balances;
1047
1056
  }
1048
- console.log(tag2, "Found MAYA token balances:", mayaBalanceResponse.data.length);
1057
+ console.log(tag3, "Found MAYA token balances:", mayaBalanceResponse.data.length);
1049
1058
  for (const mayaBalance of mayaBalanceResponse.data) {
1050
1059
  if (mayaBalance.caip !== "cosmos:mayachain-mainnet-v1/denom:maya") {
1051
- console.log(tag2, "Unexpected balance in MAYA response:", mayaBalance);
1060
+ console.log(tag3, "Unexpected balance in MAYA response:", mayaBalance);
1052
1061
  continue;
1053
1062
  }
1054
1063
  const mayaAssetInfo = hydrateAssetData(mayaBalance.caip);
@@ -1074,28 +1083,28 @@ async function getMayaCharts(params, existingBalances) {
1074
1083
  valueUsd: parseFloat(mayaBalance.valueUsd) || 0,
1075
1084
  updated: new Date().getTime()
1076
1085
  };
1077
- console.log(tag2, "Adding MAYA token to balances:", mayaTokenBalance);
1086
+ console.log(tag3, "Adding MAYA token to balances:", mayaTokenBalance);
1078
1087
  balances.push(mayaTokenBalance);
1079
1088
  }
1080
1089
  } catch (mayaError) {
1081
- console.error(tag2, "Error fetching MAYA token balance:", mayaError);
1090
+ console.error(tag3, "Error fetching MAYA token balance:", mayaError);
1082
1091
  }
1083
1092
  return balances;
1084
1093
  }
1085
1094
 
1086
1095
  // src/charts/cosmos-staking.ts
1087
- var tag3 = "| charts-cosmos-staking |";
1096
+ var tag4 = "| charts-cosmos-staking |";
1088
1097
  async function getCosmosStakingCharts(params) {
1089
1098
  const { blockchains, pioneer, pubkeys, context } = params;
1090
1099
  const balances = [];
1091
1100
  try {
1092
- console.log(tag3, "Adding Cosmos staking positions to charts...");
1101
+ console.log(tag4, "Adding Cosmos staking positions to charts...");
1093
1102
  const cosmosPubkeys = pubkeys.filter((p) => p.networks && Array.isArray(p.networks) && p.networks.some((n) => n.includes("cosmos:cosmoshub") || n.includes("cosmos:osmosis")));
1094
1103
  if (cosmosPubkeys.length === 0) {
1095
- console.log(tag3, "No cosmos pubkeys found for staking positions");
1104
+ console.log(tag4, "No cosmos pubkeys found for staking positions");
1096
1105
  return balances;
1097
1106
  }
1098
- console.log(tag3, "Found cosmos pubkeys for staking:", cosmosPubkeys.length);
1107
+ console.log(tag4, "Found cosmos pubkeys for staking:", cosmosPubkeys.length);
1099
1108
  for (const cosmosPubkey of cosmosPubkeys) {
1100
1109
  if (!cosmosPubkey.address) {
1101
1110
  continue;
@@ -1109,20 +1118,20 @@ async function getCosmosStakingCharts(params) {
1109
1118
  }
1110
1119
  }
1111
1120
  } catch (e) {
1112
- console.error(tag3, "Error adding cosmos staking positions:", e);
1121
+ console.error(tag4, "Error adding cosmos staking positions:", e);
1113
1122
  }
1114
1123
  return balances;
1115
1124
  }
1116
1125
  async function fetchStakingPositionsForNetwork(networkId, address, context, pioneer, balances) {
1117
1126
  try {
1118
- console.log(tag3, `Fetching staking positions for ${address} on ${networkId}...`);
1127
+ console.log(tag4, `Fetching staking positions for ${address} on ${networkId}...`);
1119
1128
  let network;
1120
1129
  if (networkId === "cosmos:cosmoshub-4") {
1121
1130
  network = "cosmos";
1122
1131
  } else if (networkId === "cosmos:osmosis-1") {
1123
1132
  network = "osmosis";
1124
1133
  } else {
1125
- console.error(tag3, `Unsupported networkId for staking: ${networkId}`);
1134
+ console.error(tag4, `Unsupported networkId for staking: ${networkId}`);
1126
1135
  return;
1127
1136
  }
1128
1137
  const stakingResponse = await pioneer.GetStakingPositions({
@@ -1130,15 +1139,15 @@ async function fetchStakingPositionsForNetwork(networkId, address, context, pion
1130
1139
  address
1131
1140
  });
1132
1141
  if (!stakingResponse?.data || !Array.isArray(stakingResponse.data)) {
1133
- console.log(tag3, `No staking positions found for ${address} on ${networkId}`);
1142
+ console.log(tag4, `No staking positions found for ${address} on ${networkId}`);
1134
1143
  return;
1135
1144
  }
1136
- console.log(tag3, `Found ${stakingResponse.data.length} staking positions for ${networkId}`);
1145
+ console.log(tag4, `Found ${stakingResponse.data.length} staking positions for ${networkId}`);
1137
1146
  for (const position of stakingResponse.data) {
1138
1147
  const processedPosition = processStakingPosition(position, address, context, networkId);
1139
1148
  if (processedPosition && !checkDuplicateBalance(balances, processedPosition.caip, processedPosition.pubkey, processedPosition.validator)) {
1140
1149
  balances.push(processedPosition);
1141
- console.log(tag3, `Added ${position.type} position:`, {
1150
+ console.log(tag4, `Added ${position.type} position:`, {
1142
1151
  balance: processedPosition.balance,
1143
1152
  ticker: processedPosition.ticker,
1144
1153
  valueUsd: processedPosition.valueUsd,
@@ -1147,7 +1156,7 @@ async function fetchStakingPositionsForNetwork(networkId, address, context, pion
1147
1156
  }
1148
1157
  }
1149
1158
  } catch (stakingError) {
1150
- console.error(tag3, `Error fetching staking positions for ${address} on ${networkId}:`, stakingError);
1159
+ console.error(tag4, `Error fetching staking positions for ${address} on ${networkId}:`, stakingError);
1151
1160
  }
1152
1161
  }
1153
1162
  function processStakingPosition(position, address, context, networkId) {
@@ -1182,11 +1191,11 @@ function processStakingPosition(position, address, context, networkId) {
1182
1191
  }
1183
1192
 
1184
1193
  // src/charts/index.ts
1185
- var tag4 = "| getCharts |";
1194
+ var tag5 = "| getCharts |";
1186
1195
  var getCharts = async (blockchains, pioneer, pubkeys, context) => {
1187
1196
  try {
1188
1197
  const balances = [];
1189
- console.log(tag4, "init");
1198
+ console.log(tag5, "init");
1190
1199
  const params = {
1191
1200
  blockchains,
1192
1201
  pioneer,
@@ -1201,7 +1210,7 @@ var getCharts = async (blockchains, pioneer, pubkeys, context) => {
1201
1210
  balances.push(...stakingBalances);
1202
1211
  return balances;
1203
1212
  } catch (error) {
1204
- console.error(tag4, "Error processing charts:", error);
1213
+ console.error(tag5, "Error processing charts:", error);
1205
1214
  throw error;
1206
1215
  }
1207
1216
  };
@@ -1983,7 +1992,7 @@ async function fetchTokenPriceInUsd(pioneer, caip) {
1983
1992
  }
1984
1993
  }
1985
1994
  async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pubkeyContext, isMax, feeLevel = 5) {
1986
- const tag5 = TAG + " | createUnsignedEvmTx | ";
1995
+ const tag6 = TAG + " | createUnsignedEvmTx | ";
1987
1996
  try {
1988
1997
  if (!pioneer)
1989
1998
  throw new Error("Failed to initialize Pioneer");
@@ -2004,11 +2013,11 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2004
2013
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
2005
2014
  }
2006
2015
  const address = pubkeyContext.address || pubkeyContext.pubkey;
2007
- console.log(tag5, "✅ Using FROM address from pubkeyContext:", address, "note:", pubkeyContext.note);
2016
+ console.log(tag6, "✅ Using FROM address from pubkeyContext:", address, "note:", pubkeyContext.note);
2008
2017
  if (!address)
2009
2018
  throw new Error("No address found for the specified network");
2010
2019
  const gasPriceData = await pioneer.GetGasPriceByNetwork({ networkId });
2011
- console.log(tag5, "Gas price data from API:", JSON.stringify(gasPriceData.data));
2020
+ console.log(tag6, "Gas price data from API:", JSON.stringify(gasPriceData.data));
2012
2021
  let gasPrice;
2013
2022
  const defaultGasPrices = {
2014
2023
  1: 30,
@@ -2024,75 +2033,75 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2024
2033
  let selectedGasPrice;
2025
2034
  if (feeLevel <= 2) {
2026
2035
  selectedGasPrice = gasPriceData.data.slow || gasPriceData.data.average || gasPriceData.data.fastest;
2027
- console.log(tag5, "Selecting SLOW gas price from API");
2036
+ console.log(tag6, "Selecting SLOW gas price from API");
2028
2037
  } else if (feeLevel >= 8) {
2029
2038
  selectedGasPrice = gasPriceData.data.fastest || gasPriceData.data.fast || gasPriceData.data.average;
2030
- console.log(tag5, "Selecting FAST gas price from API");
2039
+ console.log(tag6, "Selecting FAST gas price from API");
2031
2040
  } else {
2032
2041
  selectedGasPrice = gasPriceData.data.average || gasPriceData.data.fast || gasPriceData.data.fastest;
2033
- console.log(tag5, "Selecting AVERAGE gas price from API");
2042
+ console.log(tag6, "Selecting AVERAGE gas price from API");
2034
2043
  }
2035
2044
  let gasPriceNum;
2036
2045
  if (selectedGasPrice === undefined || selectedGasPrice === null) {
2037
- console.warn(tag5, "No valid gas price found in API response, using fallback:", fallbackGasGwei, "gwei");
2046
+ console.warn(tag6, "No valid gas price found in API response, using fallback:", fallbackGasGwei, "gwei");
2038
2047
  gasPriceNum = fallbackGasGwei;
2039
2048
  } else {
2040
2049
  gasPriceNum = typeof selectedGasPrice === "string" ? parseFloat(selectedGasPrice) : selectedGasPrice;
2041
2050
  if (isNaN(gasPriceNum) || !isFinite(gasPriceNum)) {
2042
- console.warn(tag5, "Invalid gas price (NaN or Infinite):", selectedGasPrice, "- using fallback:", fallbackGasGwei, "gwei");
2051
+ console.warn(tag6, "Invalid gas price (NaN or Infinite):", selectedGasPrice, "- using fallback:", fallbackGasGwei, "gwei");
2043
2052
  gasPriceNum = fallbackGasGwei;
2044
2053
  }
2045
2054
  }
2046
2055
  gasPrice = BigInt(Math.round(gasPriceNum * 1e9));
2047
2056
  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());
2057
+ console.warn(tag6, "Gas price from API too low:", gasPrice.toString(), "wei - using minimum:", MIN_GAS_PRICE_WEI.toString());
2049
2058
  gasPrice = MIN_GAS_PRICE_WEI;
2050
2059
  }
2051
2060
  } else {
2052
2061
  let gasPriceNum;
2053
2062
  if (gasPriceData.data === undefined || gasPriceData.data === null) {
2054
- console.warn(tag5, "Gas price API returned null/undefined, using fallback:", fallbackGasGwei, "gwei");
2063
+ console.warn(tag6, "Gas price API returned null/undefined, using fallback:", fallbackGasGwei, "gwei");
2055
2064
  gasPriceNum = fallbackGasGwei;
2056
2065
  } else {
2057
2066
  gasPriceNum = typeof gasPriceData.data === "string" ? parseFloat(gasPriceData.data) : gasPriceData.data;
2058
2067
  if (isNaN(gasPriceNum) || !isFinite(gasPriceNum)) {
2059
- console.warn(tag5, "Invalid gas price (NaN or Infinite):", gasPriceData.data, "- using fallback:", fallbackGasGwei, "gwei");
2068
+ console.warn(tag6, "Invalid gas price (NaN or Infinite):", gasPriceData.data, "- using fallback:", fallbackGasGwei, "gwei");
2060
2069
  gasPriceNum = fallbackGasGwei;
2061
2070
  }
2062
2071
  }
2063
2072
  const baseGasPrice = BigInt(Math.round(gasPriceNum * 1e9));
2064
2073
  if (feeLevel <= 2) {
2065
2074
  gasPrice = baseGasPrice * BigInt(80) / BigInt(100);
2066
- console.log(tag5, "Using SLOW gas price (80% of base)");
2075
+ console.log(tag6, "Using SLOW gas price (80% of base)");
2067
2076
  } else if (feeLevel >= 8) {
2068
2077
  gasPrice = baseGasPrice * BigInt(150) / BigInt(100);
2069
- console.log(tag5, "Using FAST gas price (150% of base)");
2078
+ console.log(tag6, "Using FAST gas price (150% of base)");
2070
2079
  } else {
2071
2080
  gasPrice = baseGasPrice;
2072
- console.log(tag5, "Using AVERAGE gas price (100% of base)");
2081
+ console.log(tag6, "Using AVERAGE gas price (100% of base)");
2073
2082
  }
2074
2083
  if (gasPrice < MIN_GAS_PRICE_WEI) {
2075
- console.warn(tag5, "Gas price too low:", gasPrice.toString(), "wei - using minimum:", MIN_GAS_PRICE_WEI.toString());
2084
+ console.warn(tag6, "Gas price too low:", gasPrice.toString(), "wei - using minimum:", MIN_GAS_PRICE_WEI.toString());
2076
2085
  gasPrice = MIN_GAS_PRICE_WEI;
2077
2086
  }
2078
2087
  }
2079
- console.log(tag5, "Final gasPrice:", gasPrice.toString(), "wei (", Number(gasPrice) / 1e9, "gwei)");
2088
+ console.log(tag6, "Final gasPrice:", gasPrice.toString(), "wei (", Number(gasPrice) / 1e9, "gwei)");
2080
2089
  let nonce;
2081
2090
  try {
2082
2091
  const nonceData = await pioneer.GetNonceByNetwork({ networkId, address });
2083
2092
  nonce = nonceData.data.nonce;
2084
2093
  if (nonce === undefined || nonce === null) {
2085
- console.log(tag5, "No nonce found for address (likely fresh address), defaulting to 0");
2094
+ console.log(tag6, "No nonce found for address (likely fresh address), defaulting to 0");
2086
2095
  nonce = 0;
2087
2096
  }
2088
2097
  } catch (nonceError) {
2089
- console.log(tag5, "Failed to fetch nonce (likely fresh address):", nonceError.message, "- defaulting to 0");
2098
+ console.log(tag6, "Failed to fetch nonce (likely fresh address):", nonceError.message, "- defaulting to 0");
2090
2099
  nonce = 0;
2091
2100
  }
2092
2101
  const balanceData = await pioneer.GetBalanceAddressByNetwork({ networkId, address });
2093
2102
  const balanceEth = parseFloat(balanceData.data.nativeBalance || balanceData.data.balance || "0");
2094
2103
  const balance = BigInt(Math.round(balanceEth * 1000000000000000000));
2095
- console.log(tag5, "Native ETH balance from API:", balanceData.data.nativeBalance || balanceData.data.balance, "ETH (", balance.toString(), "wei)");
2104
+ console.log(tag6, "Native ETH balance from API:", balanceData.data.nativeBalance || balanceData.data.balance, "ETH (", balance.toString(), "wei)");
2096
2105
  if (balance <= 0n)
2097
2106
  throw new Error("Wallet balance is zero");
2098
2107
  const assetType = classifyCaipEvm(caip);
@@ -2105,7 +2114,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2105
2114
  let gasLimit;
2106
2115
  if (isThorchainOperation) {
2107
2116
  gasLimit = BigInt(120000);
2108
- console.log(tag5, "Using higher gas limit for THORChain swap:", gasLimit.toString());
2117
+ console.log(tag6, "Using higher gas limit for THORChain swap:", gasLimit.toString());
2109
2118
  } else {
2110
2119
  gasLimit = chainId === 1 ? BigInt(21000) : BigInt(25000);
2111
2120
  }
@@ -2121,7 +2130,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2121
2130
  }
2122
2131
  const buffer = BigInt(100);
2123
2132
  amountWei = balance - gasFee - buffer;
2124
- console.log(tag5, "isMax calculation - balance:", balance.toString(), "gasFee:", gasFee.toString(), "buffer:", buffer.toString(), "amountWei:", amountWei.toString());
2133
+ console.log(tag6, "isMax calculation - balance:", balance.toString(), "gasFee:", gasFee.toString(), "buffer:", buffer.toString(), "amountWei:", amountWei.toString());
2125
2134
  } else {
2126
2135
  amountWei = BigInt(Math.round(amount * 1000000000000000000));
2127
2136
  if (amountWei + gasFee > balance) {
@@ -2131,14 +2140,14 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2131
2140
  const isThorchainSwap = memo && (memo.startsWith("=") || memo.startsWith("SWAP") || memo.includes(":"));
2132
2141
  let txData = "0x";
2133
2142
  if (isThorchainSwap) {
2134
- console.log(tag5, "Detected THORChain swap, encoding deposit data for memo:", memo);
2143
+ console.log(tag6, "Detected THORChain swap, encoding deposit data for memo:", memo);
2135
2144
  let fixedMemo = memo;
2136
2145
  if (memo.startsWith("=:b:") || memo.startsWith("=:btc:")) {
2137
2146
  fixedMemo = memo.replace(/^=:(b|btc):/, "=:BTC.BTC:");
2138
- console.log(tag5, "Fixed Bitcoin swap memo from:", memo, "to:", fixedMemo);
2147
+ console.log(tag6, "Fixed Bitcoin swap memo from:", memo, "to:", fixedMemo);
2139
2148
  } else if (memo.startsWith("=:e:") || memo.startsWith("=:eth:")) {
2140
2149
  fixedMemo = memo.replace(/^=:(e|eth):/, "=:ETH.ETH:");
2141
- console.log(tag5, "Fixed Ethereum swap memo from:", memo, "to:", fixedMemo);
2150
+ console.log(tag6, "Fixed Ethereum swap memo from:", memo, "to:", fixedMemo);
2142
2151
  }
2143
2152
  if (fixedMemo.length > 250) {
2144
2153
  throw new Error(`Memo too long for THORChain: ${fixedMemo.length} bytes (max 250)`);
@@ -2154,14 +2163,14 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2154
2163
  if (ethInbound) {
2155
2164
  vaultAddress = ethInbound.address;
2156
2165
  routerAddress = ethInbound.router || to;
2157
- console.log(tag5, "Using THORChain inbound addresses - vault:", vaultAddress, "router:", routerAddress);
2166
+ console.log(tag6, "Using THORChain inbound addresses - vault:", vaultAddress, "router:", routerAddress);
2158
2167
  to = routerAddress;
2159
2168
  } else {
2160
2169
  throw new Error("ETH inbound is halted or not found - cannot proceed with swap");
2161
2170
  }
2162
2171
  }
2163
2172
  } catch (fetchError) {
2164
- console.error(tag5, "Failed to fetch inbound addresses:", fetchError);
2173
+ console.error(tag6, "Failed to fetch inbound addresses:", fetchError);
2165
2174
  throw new Error(`Cannot proceed with THORChain swap - failed to fetch inbound addresses: ${fetchError.message}`);
2166
2175
  }
2167
2176
  if (vaultAddress === "0x0000000000000000000000000000000000000000") {
@@ -2181,7 +2190,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2181
2190
  const paddingLength = (32 - memoBytes.length % 32) % 32;
2182
2191
  const memoPadded = memoHex + "0".repeat(paddingLength * 2);
2183
2192
  txData = "0x" + functionSelector + vaultPadded + assetPadded + amountPadded + stringOffset + expiryPadded + stringLength + memoPadded;
2184
- console.log(tag5, "Encoded THORChain depositWithExpiry data:", {
2193
+ console.log(tag6, "Encoded THORChain depositWithExpiry data:", {
2185
2194
  functionSelector: "0x" + functionSelector,
2186
2195
  vault: vaultAddress,
2187
2196
  asset: assetAddress,
@@ -2191,9 +2200,9 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2191
2200
  stringOffset: "0x" + stringOffset,
2192
2201
  fullData: txData
2193
2202
  });
2194
- console.log(tag5, "Native ETH swap - value will be set to:", amountWei.toString(), "wei");
2203
+ console.log(tag6, "Native ETH swap - value will be set to:", amountWei.toString(), "wei");
2195
2204
  } catch (error) {
2196
- console.error(tag5, "Error encoding THORChain deposit:", error);
2205
+ console.error(tag6, "Error encoding THORChain deposit:", error);
2197
2206
  throw new Error(`Failed to encode THORChain swap: ${error.message}`);
2198
2207
  }
2199
2208
  } else if (memo) {
@@ -2212,19 +2221,19 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2212
2221
  }
2213
2222
  case "erc20": {
2214
2223
  const contractAddress = extractContractAddressFromCaip(caip);
2215
- console.log(tag5, "Fetching token decimals from contract:", contractAddress, "on network:", networkId);
2224
+ console.log(tag6, "Fetching token decimals from contract:", contractAddress, "on network:", networkId);
2216
2225
  let tokenDecimals;
2217
2226
  try {
2218
- console.log(tag5, "Fetching token decimals via pioneer-server API for", contractAddress, "on", networkId);
2227
+ console.log(tag6, "Fetching token decimals via pioneer-server API for", contractAddress, "on", networkId);
2219
2228
  const decimalsResponse = await pioneer.GetTokenDecimals({
2220
2229
  networkId,
2221
2230
  contractAddress
2222
2231
  });
2223
2232
  tokenDecimals = Number(decimalsResponse.data.decimals);
2224
- console.log(tag5, "✅ Fetched decimals from pioneer-server:", tokenDecimals);
2233
+ console.log(tag6, "✅ Fetched decimals from pioneer-server:", tokenDecimals);
2225
2234
  } catch (error) {
2226
- console.error(tag5, "Failed to fetch token decimals from pioneer-server:", error);
2227
- console.warn(tag5, "⚠️ FALLBACK: Using default 18 decimals - THIS MAY BE INCORRECT!");
2235
+ console.error(tag6, "Failed to fetch token decimals from pioneer-server:", error);
2236
+ console.warn(tag6, "⚠️ FALLBACK: Using default 18 decimals - THIS MAY BE INCORRECT!");
2228
2237
  tokenDecimals = 18;
2229
2238
  }
2230
2239
  const tokenMultiplier = 10n ** BigInt(tokenDecimals);
@@ -2245,7 +2254,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2245
2254
  amountWei = tokenBalance;
2246
2255
  } else {
2247
2256
  amountWei = BigInt(Math.round(amount * Number(tokenMultiplier)));
2248
- console.log(tag5, "Token amount calculation:", {
2257
+ console.log(tag6, "Token amount calculation:", {
2249
2258
  inputAmount: amount,
2250
2259
  decimals: tokenDecimals,
2251
2260
  multiplier: tokenMultiplier,
@@ -2281,23 +2290,23 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2281
2290
  }
2282
2291
  if (pubkeyContext.addressNListMaster) {
2283
2292
  unsignedTx.addressNList = pubkeyContext.addressNListMaster;
2284
- console.log(tag5, "✅ Using addressNListMaster from pubkey context:", unsignedTx.addressNList, "for address:", address);
2293
+ console.log(tag6, "✅ Using addressNListMaster from pubkey context:", unsignedTx.addressNList, "for address:", address);
2285
2294
  } else if (pubkeyContext.pathMaster) {
2286
2295
  unsignedTx.addressNList = bip32ToAddressNList(pubkeyContext.pathMaster);
2287
- console.log(tag5, "✅ Converted pathMaster to addressNList:", pubkeyContext.pathMaster, "→", unsignedTx.addressNList);
2296
+ console.log(tag6, "✅ Converted pathMaster to addressNList:", pubkeyContext.pathMaster, "→", unsignedTx.addressNList);
2288
2297
  } else if (pubkeyContext.addressNList) {
2289
2298
  unsignedTx.addressNList = pubkeyContext.addressNList;
2290
- console.log(tag5, "✅ Using addressNList from pubkey context:", unsignedTx.addressNList);
2299
+ console.log(tag6, "✅ Using addressNList from pubkey context:", unsignedTx.addressNList);
2291
2300
  } else if (pubkeyContext.path) {
2292
2301
  unsignedTx.addressNList = bip32ToAddressNList(pubkeyContext.path);
2293
- console.log(tag5, "⚠️ Using regular path (not master):", pubkeyContext.path, "→", unsignedTx.addressNList);
2302
+ console.log(tag6, "⚠️ Using regular path (not master):", pubkeyContext.path, "→", unsignedTx.addressNList);
2294
2303
  } else {
2295
2304
  unsignedTx.addressNList = [2147483648 + 44, 2147483648 + 60, 2147483648, 0, 0];
2296
- console.warn(tag5, "⚠️ No path info in pubkey context, using default account 0");
2305
+ console.warn(tag6, "⚠️ No path info in pubkey context, using default account 0");
2297
2306
  }
2298
2307
  return unsignedTx;
2299
2308
  } catch (error) {
2300
- console.error(tag5, "Error:", error.message);
2309
+ console.error(tag6, "Error:", error.message);
2301
2310
  throw error;
2302
2311
  }
2303
2312
  }
@@ -2306,7 +2315,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2306
2315
  import { caipToNetworkId as caipToNetworkId2 } from "@pioneer-platform/pioneer-caip";
2307
2316
  var TAG2 = " | createUnsignedUxtoTx | ";
2308
2317
  async function createUnsignedRippleTx(caip, to, amount, memo, pubkeys, pioneer, pubkeyContext, isMax) {
2309
- let tag5 = TAG2 + " | createUnsignedRippleTx | ";
2318
+ let tag6 = TAG2 + " | createUnsignedRippleTx | ";
2310
2319
  try {
2311
2320
  if (!pioneer)
2312
2321
  throw new Error("Failed to init! pioneer");
@@ -2317,7 +2326,7 @@ async function createUnsignedRippleTx(caip, to, amount, memo, pubkeys, pioneer,
2317
2326
  if (!pubkeyContext.networks?.includes(networkId)) {
2318
2327
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
2319
2328
  }
2320
- console.log(tag5, `✅ Using pubkeyContext for network ${networkId}:`, {
2329
+ console.log(tag6, `✅ Using pubkeyContext for network ${networkId}:`, {
2321
2330
  address: pubkeyContext.address
2322
2331
  });
2323
2332
  const fromAddress = pubkeyContext.address || pubkeyContext.pubkey;
@@ -2385,7 +2394,7 @@ async function createUnsignedRippleTx(caip, to, amount, memo, pubkeys, pioneer,
2385
2394
  };
2386
2395
  return unsignedTx;
2387
2396
  } catch (error) {
2388
- console.error(tag5, "Error:", error);
2397
+ console.error(tag6, "Error:", error);
2389
2398
  throw error;
2390
2399
  }
2391
2400
  }
@@ -2525,7 +2534,7 @@ var thorchainDepositTemplate = (params) => ({
2525
2534
  // src/txbuilder/createUnsignedTendermintTx.ts
2526
2535
  var TAG3 = " | createUnsignedTendermintTx | ";
2527
2536
  async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pioneer, pubkeyContext, isMax, to) {
2528
- const tag5 = TAG3 + " | createUnsignedTendermintTx | ";
2537
+ const tag6 = TAG3 + " | createUnsignedTendermintTx | ";
2529
2538
  try {
2530
2539
  if (!pioneer)
2531
2540
  throw new Error("Failed to init! pioneer");
@@ -2536,7 +2545,7 @@ async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pio
2536
2545
  if (!pubkeyContext.networks?.includes(networkId)) {
2537
2546
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
2538
2547
  }
2539
- console.log(tag5, `✅ Using pubkeyContext for network ${networkId}:`, {
2548
+ console.log(tag6, `✅ Using pubkeyContext for network ${networkId}:`, {
2540
2549
  address: pubkeyContext.address,
2541
2550
  addressNList: pubkeyContext.addressNList || pubkeyContext.addressNListMaster
2542
2551
  });
@@ -2559,11 +2568,11 @@ async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pio
2559
2568
  }
2560
2569
  const fromAddress = pubkeyContext.address || pubkeyContext.pubkey;
2561
2570
  let asset = caip.split(":")[1];
2562
- console.log(tag5, `\uD83D\uDD0D Fetching account info for address: ${fromAddress}`);
2571
+ console.log(tag6, `\uD83D\uDD0D Fetching account info for address: ${fromAddress}`);
2563
2572
  const accountInfo = (await pioneer.GetAccountInfo({ network: chain, address: fromAddress })).data;
2564
- console.log(tag5, "\uD83D\uDCCB accountInfo:", JSON.stringify(accountInfo, null, 2));
2573
+ console.log(tag6, "\uD83D\uDCCB accountInfo:", JSON.stringify(accountInfo, null, 2));
2565
2574
  let balanceInfo = await pioneer.GetPubkeyBalance({ asset: chain, pubkey: fromAddress });
2566
- console.log(tag5, `\uD83D\uDCB0 balanceInfo:`, balanceInfo);
2575
+ console.log(tag6, `\uD83D\uDCB0 balanceInfo:`, balanceInfo);
2567
2576
  let account_number, sequence;
2568
2577
  if (accountInfo.account) {
2569
2578
  account_number = accountInfo.account.account_number || "0";
@@ -2574,13 +2583,13 @@ async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pio
2574
2583
  } else {
2575
2584
  throw new Error(`Unexpected account info format for ${networkId}: ${JSON.stringify(accountInfo)}`);
2576
2585
  }
2577
- console.log(tag5, `\uD83D\uDCCA Extracted account_number: ${account_number}, sequence: ${sequence}`);
2586
+ console.log(tag6, `\uD83D\uDCCA Extracted account_number: ${account_number}, sequence: ${sequence}`);
2578
2587
  if (account_number === "0" || account_number === 0) {
2579
- console.log(tag5, `⚠️ WARNING: Account number is 0 from Pioneer API`);
2580
- console.log(tag5, ` This is likely due to stale Pioneer API cache`);
2581
- console.log(tag5, ` The mayachain-network module queries nodes directly but Pioneer API may be cached`);
2582
- console.log(tag5, ` Proceeding with account_number: 0 but transaction will likely fail`);
2583
- console.log(tag5, ` TODO: Fix Pioneer API to use fresh data from mayachain-network module`);
2588
+ console.log(tag6, `⚠️ WARNING: Account number is 0 from Pioneer API`);
2589
+ console.log(tag6, ` This is likely due to stale Pioneer API cache`);
2590
+ console.log(tag6, ` The mayachain-network module queries nodes directly but Pioneer API may be cached`);
2591
+ console.log(tag6, ` Proceeding with account_number: 0 but transaction will likely fail`);
2592
+ console.log(tag6, ` TODO: Fix Pioneer API to use fresh data from mayachain-network module`);
2584
2593
  }
2585
2594
  const fees = {
2586
2595
  "cosmos:thorchain-mainnet-v1": 0.02,
@@ -2735,7 +2744,7 @@ async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pio
2735
2744
  }
2736
2745
  }
2737
2746
  } catch (error) {
2738
- console.error(tag5, "Error:", error);
2747
+ console.error(tag6, "Error:", error);
2739
2748
  throw error;
2740
2749
  }
2741
2750
  }
@@ -2764,7 +2773,7 @@ function getCoinTypeFromNetworkId(networkId) {
2764
2773
  return coinType;
2765
2774
  }
2766
2775
  async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pubkeyContext, isMax, feeLevel = 5, changeScriptType) {
2767
- let tag5 = " | createUnsignedUxtoTx | ";
2776
+ let tag6 = " | createUnsignedUxtoTx | ";
2768
2777
  try {
2769
2778
  if (!pioneer)
2770
2779
  throw Error("Failed to init! pioneer");
@@ -2775,7 +2784,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2775
2784
  if (!pubkeyContext.networks?.includes(networkId)) {
2776
2785
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
2777
2786
  }
2778
- console.log(tag5, `✅ Using pubkeyContext for network ${networkId}:`, {
2787
+ console.log(tag6, `✅ Using pubkeyContext for network ${networkId}:`, {
2779
2788
  address: pubkeyContext.address,
2780
2789
  scriptType: pubkeyContext.scriptType
2781
2790
  });
@@ -2786,15 +2795,15 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2786
2795
  const isSegwit = segwitNetworks.includes(networkId);
2787
2796
  let chain = NetworkIdToChain[networkId];
2788
2797
  const coinType = getCoinTypeFromNetworkId(networkId);
2789
- console.log(`${tag5}: Using SLIP-44 coin type ${coinType} for ${chain}`);
2798
+ console.log(`${tag6}: Using SLIP-44 coin type ${coinType} for ${chain}`);
2790
2799
  const utxos = [];
2791
2800
  for (const pubkey of relevantPubkeys) {
2792
2801
  try {
2793
2802
  let utxosResp = await pioneer.ListUnspent({ network: chain, xpub: pubkey.pubkey });
2794
2803
  utxosResp = utxosResp.data;
2795
- console.log(`${tag5}: ListUnspent response for ${pubkey.scriptType}:`, utxosResp?.length || 0, "UTXOs");
2804
+ console.log(`${tag6}: ListUnspent response for ${pubkey.scriptType}:`, utxosResp?.length || 0, "UTXOs");
2796
2805
  if (!utxosResp || !Array.isArray(utxosResp)) {
2797
- console.warn(`${tag5}: Invalid or empty UTXO response for ${pubkey.pubkey}`);
2806
+ console.warn(`${tag6}: Invalid or empty UTXO response for ${pubkey.pubkey}`);
2798
2807
  continue;
2799
2808
  }
2800
2809
  let scriptType = pubkey.scriptType;
@@ -2803,10 +2812,10 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2803
2812
  }
2804
2813
  utxos.push(...utxosResp);
2805
2814
  } catch (error) {
2806
- console.error(`${tag5}: Failed to fetch UTXOs for ${pubkey.pubkey}:`, error);
2815
+ console.error(`${tag6}: Failed to fetch UTXOs for ${pubkey.pubkey}:`, error);
2807
2816
  }
2808
2817
  }
2809
- console.log(`${tag5}: Total UTXOs collected:`, utxos.length);
2818
+ console.log(`${tag6}: Total UTXOs collected:`, utxos.length);
2810
2819
  if (!utxos || utxos.length === 0)
2811
2820
  throw Error("No UTXOs found across all addresses");
2812
2821
  for (const utxo of utxos) {
@@ -2819,14 +2828,14 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2819
2828
  }, {});
2820
2829
  const mostCommonInputType = Object.entries(scriptTypeCount).sort(([, a2], [, b3]) => b3 - a2)[0]?.[0] || "p2pkh";
2821
2830
  const actualChangeScriptType = changeScriptType || mostCommonInputType || relevantPubkeys[0]?.scriptType || "p2pkh";
2822
- console.log(`${tag5}: Input script types:`, scriptTypeCount);
2823
- console.log(`${tag5}: Using change script type: ${actualChangeScriptType} (matches inputs: ${mostCommonInputType})`);
2831
+ console.log(`${tag6}: Input script types:`, scriptTypeCount);
2832
+ console.log(`${tag6}: Using change script type: ${actualChangeScriptType} (matches inputs: ${mostCommonInputType})`);
2824
2833
  const changeXpubInfo = relevantPubkeys.find((pk) => pk.scriptType === actualChangeScriptType);
2825
2834
  if (!changeXpubInfo) {
2826
2835
  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.`);
2827
2836
  }
2828
2837
  const changeXpub = changeXpubInfo.pubkey;
2829
- console.log(`${tag5}: Change xpub selected for ${actualChangeScriptType}:`, changeXpub?.substring(0, 10) + "...");
2838
+ console.log(`${tag6}: Change xpub selected for ${actualChangeScriptType}:`, changeXpub?.substring(0, 10) + "...");
2830
2839
  let changeAddressIndex = await pioneer.GetChangeAddress({
2831
2840
  network: chain,
2832
2841
  xpub: changeXpub
@@ -2846,7 +2855,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2846
2855
  break;
2847
2856
  }
2848
2857
  const path = bipPath;
2849
- console.log(`${tag5}: Change address path: ${path} (coin type: ${coinType}, index: ${changeAddressIndex})`);
2858
+ console.log(`${tag6}: Change address path: ${path} (coin type: ${coinType}, index: ${changeAddressIndex})`);
2850
2859
  const changeAddress = {
2851
2860
  path,
2852
2861
  isChange: true,
@@ -2856,7 +2865,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2856
2865
  };
2857
2866
  let feeRateFromNode;
2858
2867
  if (networkId === "bip122:00000000001a91e3dace36e2be3bf030") {
2859
- console.log(`${tag5}: Using hardcoded fees for DOGE (10 sat/byte)`);
2868
+ console.log(`${tag6}: Using hardcoded fees for DOGE (10 sat/byte)`);
2860
2869
  feeRateFromNode = {
2861
2870
  slow: 10,
2862
2871
  average: 10,
@@ -2869,19 +2878,19 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2869
2878
  try {
2870
2879
  let feeResponse;
2871
2880
  if (pioneer.GetFeeRateByNetwork) {
2872
- console.log(`${tag5}: Trying GetFeeRateByNetwork for ${networkId}`);
2881
+ console.log(`${tag6}: Trying GetFeeRateByNetwork for ${networkId}`);
2873
2882
  feeResponse = await pioneer.GetFeeRateByNetwork({ networkId });
2874
2883
  } else {
2875
- console.log(`${tag5}: Using GetFeeRate for ${networkId}`);
2884
+ console.log(`${tag6}: Using GetFeeRate for ${networkId}`);
2876
2885
  feeResponse = await pioneer.GetFeeRate({ networkId });
2877
2886
  }
2878
2887
  feeRateFromNode = feeResponse.data;
2879
- console.log(`${tag5}: Got fee rates from API:`, JSON.stringify(feeRateFromNode, null, 2));
2888
+ console.log(`${tag6}: Got fee rates from API:`, JSON.stringify(feeRateFromNode, null, 2));
2880
2889
  const conversionThreshold = 500;
2881
2890
  const needsConversion = feeRateFromNode.slow && feeRateFromNode.slow > conversionThreshold || feeRateFromNode.average && feeRateFromNode.average > conversionThreshold || feeRateFromNode.fast && feeRateFromNode.fast > conversionThreshold || feeRateFromNode.fastest && feeRateFromNode.fastest > conversionThreshold;
2882
2891
  if (needsConversion) {
2883
- console.warn(`${tag5}: Detected wrong units - values appear to be in sat/kB instead of sat/byte`);
2884
- console.warn(`${tag5}: Original values:`, {
2892
+ console.warn(`${tag6}: Detected wrong units - values appear to be in sat/kB instead of sat/byte`);
2893
+ console.warn(`${tag6}: Original values:`, {
2885
2894
  slow: feeRateFromNode.slow,
2886
2895
  average: feeRateFromNode.average,
2887
2896
  fast: feeRateFromNode.fast,
@@ -2895,12 +2904,12 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2895
2904
  feeRateFromNode.fast = feeRateFromNode.fast / 1000;
2896
2905
  if (feeRateFromNode.fastest)
2897
2906
  feeRateFromNode.fastest = feeRateFromNode.fastest / 1000;
2898
- console.warn(`${tag5}: Converted to sat/byte:`, feeRateFromNode);
2907
+ console.warn(`${tag6}: Converted to sat/byte:`, feeRateFromNode);
2899
2908
  }
2900
2909
  if (!feeRateFromNode || typeof feeRateFromNode !== "object") {
2901
2910
  throw new Error(`Invalid fee rate response from API: ${JSON.stringify(feeRateFromNode)}`);
2902
2911
  }
2903
- console.log(`${tag5}: Available fee rates:`, {
2912
+ console.log(`${tag6}: Available fee rates:`, {
2904
2913
  slow: feeRateFromNode.slow,
2905
2914
  average: feeRateFromNode.average,
2906
2915
  fast: feeRateFromNode.fast,
@@ -2910,33 +2919,33 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2910
2919
  throw new Error(`No valid fee rates in API response: ${JSON.stringify(feeRateFromNode)}`);
2911
2920
  }
2912
2921
  } catch (error) {
2913
- console.error(`${tag5}: Failed to get fee rates from Pioneer API:`, error.message || error);
2922
+ console.error(`${tag6}: Failed to get fee rates from Pioneer API:`, error.message || error);
2914
2923
  throw new Error(`Unable to get fee rate for network ${networkId}: ${error.message || "API unavailable"}`);
2915
2924
  }
2916
2925
  }
2917
2926
  let effectiveFeeRate;
2918
- console.log(`${tag5}: Using fee level ${feeLevel}`);
2927
+ console.log(`${tag6}: Using fee level ${feeLevel}`);
2919
2928
  switch (feeLevel) {
2920
2929
  case 1:
2921
2930
  case 2:
2922
2931
  effectiveFeeRate = feeRateFromNode.slow || feeRateFromNode.average;
2923
- console.log(`${tag5}: Using SLOW fee rate: ${effectiveFeeRate} sat/vB`);
2932
+ console.log(`${tag6}: Using SLOW fee rate: ${effectiveFeeRate} sat/vB`);
2924
2933
  break;
2925
2934
  case 3:
2926
2935
  case 4:
2927
2936
  effectiveFeeRate = feeRateFromNode.average || feeRateFromNode.fast;
2928
- console.log(`${tag5}: Using AVERAGE fee rate: ${effectiveFeeRate} sat/vB`);
2937
+ console.log(`${tag6}: Using AVERAGE fee rate: ${effectiveFeeRate} sat/vB`);
2929
2938
  break;
2930
2939
  case 5:
2931
2940
  effectiveFeeRate = feeRateFromNode.fastest || feeRateFromNode.fast;
2932
- console.log(`${tag5}: Using FASTEST fee rate: ${effectiveFeeRate} sat/vB`);
2941
+ console.log(`${tag6}: Using FASTEST fee rate: ${effectiveFeeRate} sat/vB`);
2933
2942
  break;
2934
2943
  default:
2935
2944
  throw new Error(`Invalid fee level: ${feeLevel}. Must be 1-5`);
2936
2945
  }
2937
2946
  if (!effectiveFeeRate)
2938
2947
  throw new Error("Unable to get fee rate for network");
2939
- console.log(`${tag5}: Using fee rate from API:`, {
2948
+ console.log(`${tag6}: Using fee rate from API:`, {
2940
2949
  feeLevel,
2941
2950
  selectedRate: effectiveFeeRate,
2942
2951
  description: feeLevel <= 2 ? "slow" : feeLevel <= 4 ? "average" : "fast"
@@ -2946,22 +2955,22 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2946
2955
  effectiveFeeRate = Math.ceil(effectiveFeeRate);
2947
2956
  const MIN_RELAY_FEE_RATE = 3;
2948
2957
  if (effectiveFeeRate < MIN_RELAY_FEE_RATE) {
2949
- console.log(`${tag5}: Fee rate ${effectiveFeeRate} is below minimum relay fee, increasing to ${MIN_RELAY_FEE_RATE} sat/vB`);
2958
+ console.log(`${tag6}: Fee rate ${effectiveFeeRate} is below minimum relay fee, increasing to ${MIN_RELAY_FEE_RATE} sat/vB`);
2950
2959
  effectiveFeeRate = MIN_RELAY_FEE_RATE;
2951
2960
  }
2952
- console.log(`${tag5}: Final fee rate to use (rounded, with minimums): ${effectiveFeeRate} sat/vB`);
2961
+ console.log(`${tag6}: Final fee rate to use (rounded, with minimums): ${effectiveFeeRate} sat/vB`);
2953
2962
  amount = parseInt(String(amount * 1e8));
2954
2963
  if (amount <= 0 && !isMax)
2955
2964
  throw Error("Invalid amount! 0");
2956
2965
  const totalBalance = utxos.reduce((sum, utxo) => sum + utxo.value, 0);
2957
- console.log(`${tag5}: Coin selection inputs:`, {
2966
+ console.log(`${tag6}: Coin selection inputs:`, {
2958
2967
  utxoCount: utxos.length,
2959
2968
  totalBalance: totalBalance / 1e8,
2960
2969
  requestedAmount: amount / 1e8,
2961
2970
  isMax,
2962
2971
  feeRate: effectiveFeeRate
2963
2972
  });
2964
- console.log(`${tag5}: UTXO details for coin selection:`, utxos.map((u) => ({
2973
+ console.log(`${tag6}: UTXO details for coin selection:`, utxos.map((u) => ({
2965
2974
  value: u.value,
2966
2975
  txid: u.txid?.substring(0, 10) + "...",
2967
2976
  vout: u.vout,
@@ -2975,8 +2984,8 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2975
2984
  } else {
2976
2985
  result = import_coinselect.default(utxos, [{ address: to, value: amount }], effectiveFeeRate);
2977
2986
  }
2978
- console.log(tag5, "coinSelect result object:", result);
2979
- console.log(tag5, "coinSelect result.inputs:", result?.inputs);
2987
+ console.log(tag6, "coinSelect result object:", result);
2988
+ console.log(tag6, "coinSelect result.inputs:", result?.inputs);
2980
2989
  if (!result || !result.inputs) {
2981
2990
  const errorDetails = {
2982
2991
  utxoCount: utxos.length,
@@ -2985,7 +2994,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2985
2994
  feeRate: effectiveFeeRate,
2986
2995
  insufficientFunds: totalBalance < amount
2987
2996
  };
2988
- console.error(`${tag5}: Coin selection failed:`, errorDetails);
2997
+ console.error(`${tag6}: Coin selection failed:`, errorDetails);
2989
2998
  if (utxos.length === 0) {
2990
2999
  throw Error("No UTXOs available for coin selection");
2991
3000
  } else if (totalBalance < amount) {
@@ -3001,7 +3010,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
3001
3010
  throw Error("Failed to create transaction: Missing outputs");
3002
3011
  if (fee === undefined)
3003
3012
  throw Error("Failed to calculate transaction fee");
3004
- console.log(`${tag5}: Transaction built with:`, {
3013
+ console.log(`${tag6}: Transaction built with:`, {
3005
3014
  feeLevel,
3006
3015
  effectiveFeeRate: `${effectiveFeeRate} sat/vB`,
3007
3016
  calculatedFee: `${fee} satoshis`,
@@ -3009,8 +3018,8 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
3009
3018
  outputCount: outputs.length
3010
3019
  });
3011
3020
  const uniqueInputSet = new Set;
3012
- console.log(tag5, "inputs:", inputs);
3013
- console.log(tag5, "inputs:", inputs[0]);
3021
+ console.log(tag6, "inputs:", inputs);
3022
+ console.log(tag6, "inputs:", inputs[0]);
3014
3023
  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 }) => ({
3015
3024
  addressNList: bip32ToAddressNList2(path2),
3016
3025
  scriptType,
@@ -3118,7 +3127,7 @@ class TransactionManager {
3118
3127
  throw new Error(`Unsupported CAIP: ${caip}`);
3119
3128
  }
3120
3129
  async transfer({ caip, to, amount, memo, isMax = false, feeLevel = 5, changeScriptType }) {
3121
- let tag5 = TAG4 + " | transfer | ";
3130
+ let tag6 = TAG4 + " | transfer | ";
3122
3131
  try {
3123
3132
  if (!this.pioneer)
3124
3133
  throw Error("Failed to init! pioneer");
@@ -3156,12 +3165,12 @@ class TransactionManager {
3156
3165
  }
3157
3166
  return unsignedTx;
3158
3167
  } catch (e) {
3159
- console.error(tag5, e);
3168
+ console.error(tag6, e);
3160
3169
  throw e;
3161
3170
  }
3162
3171
  }
3163
3172
  async sign({ caip, unsignedTx }) {
3164
- let tag5 = TAG4 + " | sign | ";
3173
+ let tag6 = TAG4 + " | sign | ";
3165
3174
  try {
3166
3175
  if (!this.pioneer)
3167
3176
  throw Error("Failed to init! pioneer");
@@ -3247,20 +3256,20 @@ class TransactionManager {
3247
3256
  }
3248
3257
  case "cosmos:mayachain-mainnet-v1/slip44:931":
3249
3258
  case "cosmos:mayachain-mainnet-v1/denom:maya": {
3250
- console.log(tag5, "\uD83D\uDD0D ===== MAYACHAIN SIGNING AUDIT =====");
3251
- console.log(tag5, "\uD83D\uDCCB unsignedTx:", JSON.stringify(unsignedTx, null, 2));
3252
- console.log(tag5, "\uD83D\uDD11 unsignedTx.addressNList:", unsignedTx.addressNList);
3253
- console.log(tag5, "\uD83D\uDCCD unsignedTx.signerAddress:", unsignedTx.signerAddress);
3254
- console.log(tag5, "\uD83C\uDF10 pubkeyContext:", this.pubkeyContext);
3255
- console.log(tag5, "\uD83D\uDD10 pubkeyContext.addressNList:", this.pubkeyContext?.addressNList);
3256
- console.log(tag5, "\uD83D\uDD10 pubkeyContext.addressNListMaster:", this.pubkeyContext?.addressNListMaster);
3257
- console.log(tag5, "\uD83D\uDCEC pubkeyContext.address:", this.pubkeyContext?.address);
3258
- console.log(tag5, "=======================================");
3259
+ console.log(tag6, "\uD83D\uDD0D ===== MAYACHAIN SIGNING AUDIT =====");
3260
+ console.log(tag6, "\uD83D\uDCCB unsignedTx:", JSON.stringify(unsignedTx, null, 2));
3261
+ console.log(tag6, "\uD83D\uDD11 unsignedTx.addressNList:", unsignedTx.addressNList);
3262
+ console.log(tag6, "\uD83D\uDCCD unsignedTx.signerAddress:", unsignedTx.signerAddress);
3263
+ console.log(tag6, "\uD83C\uDF10 pubkeyContext:", this.pubkeyContext);
3264
+ console.log(tag6, "\uD83D\uDD10 pubkeyContext.addressNList:", this.pubkeyContext?.addressNList);
3265
+ console.log(tag6, "\uD83D\uDD10 pubkeyContext.addressNListMaster:", this.pubkeyContext?.addressNListMaster);
3266
+ console.log(tag6, "\uD83D\uDCEC pubkeyContext.address:", this.pubkeyContext?.address);
3267
+ console.log(tag6, "=======================================");
3259
3268
  if (unsignedTx.signDoc.msgs[0].type === "mayachain/MsgSend") {
3260
3269
  const responseSign = await this.keepKeySdk.mayachain.mayachainSignAminoTransfer(unsignedTx);
3261
3270
  signedTx = responseSign.serialized;
3262
- console.log(tag5, "✅ Signing completed");
3263
- console.log(tag5, "\uD83D\uDCE6 responseSign:", responseSign);
3271
+ console.log(tag6, "✅ Signing completed");
3272
+ console.log(tag6, "\uD83D\uDCE6 responseSign:", responseSign);
3264
3273
  } else if (unsignedTx.signDoc.msgs[0].type === "mayachain/MsgDeposit") {
3265
3274
  const responseSign = await this.keepKeySdk.mayachain.mayachainSignAminoDeposit(unsignedTx);
3266
3275
  signedTx = responseSign.serialized;
@@ -3282,11 +3291,11 @@ class TransactionManager {
3282
3291
  if (serialized.length > 140) {
3283
3292
  signedTx = serialized;
3284
3293
  } else {
3285
- console.error(tag5, "EIP155 signing returned incomplete transaction - only signature components");
3294
+ console.error(tag6, "EIP155 signing returned incomplete transaction - only signature components");
3286
3295
  throw new Error("KeepKey returned incomplete transaction - cannot reconstruct without r,s,v components");
3287
3296
  }
3288
3297
  } else {
3289
- console.error(tag5, "EIP155 signing failed - no valid signature in response:", responseSign);
3298
+ console.error(tag6, "EIP155 signing failed - no valid signature in response:", responseSign);
3290
3299
  throw new Error("Failed to sign transaction - no valid signature in response");
3291
3300
  }
3292
3301
  break;
@@ -3307,19 +3316,19 @@ class TransactionManager {
3307
3316
  }
3308
3317
  }
3309
3318
  if (!signedTx) {
3310
- console.error(tag5, "CRITICAL ERROR: signedTx is missing after signing process");
3311
- console.error(tag5, "CAIP:", caip);
3312
- console.error(tag5, "Type:", type);
3319
+ console.error(tag6, "CRITICAL ERROR: signedTx is missing after signing process");
3320
+ console.error(tag6, "CAIP:", caip);
3321
+ console.error(tag6, "Type:", type);
3313
3322
  throw Error("Failed to sign! missing signedTx");
3314
3323
  }
3315
3324
  return signedTx;
3316
3325
  } catch (e) {
3317
- console.error(tag5, e);
3326
+ console.error(tag6, e);
3318
3327
  throw e;
3319
3328
  }
3320
3329
  }
3321
3330
  async broadcast({ networkId, serialized }) {
3322
- let tag5 = TAG4 + " | broadcast | ";
3331
+ let tag6 = TAG4 + " | broadcast | ";
3323
3332
  try {
3324
3333
  if (!this.pioneer)
3325
3334
  throw Error("Failed to init! pioneer");
@@ -3333,7 +3342,7 @@ class TransactionManager {
3333
3342
  return result.txid;
3334
3343
  }
3335
3344
  } catch (e) {
3336
- console.error(tag5, e);
3345
+ console.error(tag6, e);
3337
3346
  throw e;
3338
3347
  }
3339
3348
  }
@@ -3453,7 +3462,7 @@ var cosmosClaimAllRewardsTemplate = (params) => ({
3453
3462
  // src/txbuilder/createUnsignedStakingTx.ts
3454
3463
  var TAG5 = " | createUnsignedStakingTx | ";
3455
3464
  async function createUnsignedStakingTx(caip, params, pubkeys, pioneer, pubkeyContext) {
3456
- const tag5 = TAG5 + " | createUnsignedStakingTx | ";
3465
+ const tag6 = TAG5 + " | createUnsignedStakingTx | ";
3457
3466
  try {
3458
3467
  if (!pioneer)
3459
3468
  throw new Error("Failed to init! pioneer");
@@ -3464,7 +3473,7 @@ async function createUnsignedStakingTx(caip, params, pubkeys, pioneer, pubkeyCon
3464
3473
  if (!pubkeyContext.networks?.includes(networkId)) {
3465
3474
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
3466
3475
  }
3467
- console.log(tag5, `✅ Using pubkeyContext for network ${networkId}:`, {
3476
+ console.log(tag6, `✅ Using pubkeyContext for network ${networkId}:`, {
3468
3477
  address: pubkeyContext.address
3469
3478
  });
3470
3479
  let chain;
@@ -3496,10 +3505,10 @@ async function createUnsignedStakingTx(caip, params, pubkeys, pioneer, pubkeyCon
3496
3505
  default:
3497
3506
  throw new Error(`Unsupported networkId for staking: ${networkId}`);
3498
3507
  }
3499
- console.log(tag5, `Building ${params.type} transaction for ${chain}`);
3508
+ console.log(tag6, `Building ${params.type} transaction for ${chain}`);
3500
3509
  const fromAddress = pubkeyContext.address || pubkeyContext.pubkey;
3501
3510
  const accountInfo = (await pioneer.GetAccountInfo({ network: chain, address: fromAddress })).data;
3502
- console.log(tag5, "accountInfo: ", accountInfo);
3511
+ console.log(tag6, "accountInfo: ", accountInfo);
3503
3512
  let account_number;
3504
3513
  let sequence;
3505
3514
  if (networkId === "cosmos:cosmoshub-4" || networkId === "cosmos:osmosis-1") {
@@ -3581,7 +3590,7 @@ async function createUnsignedStakingTx(caip, params, pubkeys, pioneer, pubkeyCon
3581
3590
  throw new Error(`Unsupported staking transaction type: ${params.type}`);
3582
3591
  }
3583
3592
  } catch (error) {
3584
- console.error(tag5, "Error:", error);
3593
+ console.error(tag6, "Error:", error);
3585
3594
  throw error;
3586
3595
  }
3587
3596
  }
@@ -3627,16 +3636,16 @@ function withTimeout(promise, timeoutMs) {
3627
3636
  ]);
3628
3637
  }
3629
3638
  async function getFees(pioneer, networkId) {
3630
- const tag5 = TAG6 + " | getFees | ";
3639
+ const tag6 = TAG6 + " | getFees | ";
3631
3640
  try {
3632
- console.log(tag5, `Fetching fees for network: ${networkId}`);
3641
+ console.log(tag6, `Fetching fees for network: ${networkId}`);
3633
3642
  const networkType = getNetworkType(networkId);
3634
3643
  if (networkType === "COSMOS") {
3635
- console.log(tag5, "Using hardcoded fees for Cosmos network:", networkId);
3644
+ console.log(tag6, "Using hardcoded fees for Cosmos network:", networkId);
3636
3645
  return getCosmosFees(networkId);
3637
3646
  }
3638
3647
  if (networkId === "bip122:00000000001a91e3dace36e2be3bf030") {
3639
- console.log(tag5, "Using hardcoded fees for Dogecoin: 10 sat/byte");
3648
+ console.log(tag6, "Using hardcoded fees for Dogecoin: 10 sat/byte");
3640
3649
  return {
3641
3650
  slow: {
3642
3651
  label: "Slow",
@@ -3673,7 +3682,7 @@ async function getFees(pioneer, networkId) {
3673
3682
  const apiCall = pioneer.GetFeeRateByNetwork ? pioneer.GetFeeRateByNetwork({ networkId }) : pioneer.GetFeeRate({ networkId });
3674
3683
  feeResponse = await withTimeout(apiCall, 3000);
3675
3684
  } catch (timeoutError) {
3676
- console.warn(tag5, "Dash fee API timeout, using fallback fees");
3685
+ console.warn(tag6, "Dash fee API timeout, using fallback fees");
3677
3686
  return {
3678
3687
  slow: {
3679
3688
  label: "Economy",
@@ -3711,17 +3720,17 @@ async function getFees(pioneer, networkId) {
3711
3720
  throw new Error(`No fee data returned for ${networkId}`);
3712
3721
  }
3713
3722
  const feeData = feeResponse.data;
3714
- console.log(tag5, "Raw fee data:", feeData);
3723
+ console.log(tag6, "Raw fee data:", feeData);
3715
3724
  const networkName = getNetworkName(networkId);
3716
3725
  let normalizedFees = normalizeFeeData(feeData, networkType, networkName, networkId);
3717
3726
  normalizedFees = ensureFeeDifferentiation(normalizedFees, networkType);
3718
3727
  normalizedFees.networkId = networkId;
3719
3728
  normalizedFees.networkType = networkType;
3720
3729
  normalizedFees.raw = feeData;
3721
- console.log(tag5, "Normalized fees:", normalizedFees);
3730
+ console.log(tag6, "Normalized fees:", normalizedFees);
3722
3731
  return normalizedFees;
3723
3732
  } catch (error) {
3724
- console.error(tag5, "Failed to fetch fees:", error);
3733
+ console.error(tag6, "Failed to fetch fees:", error);
3725
3734
  return getFallbackFees(networkId);
3726
3735
  }
3727
3736
  }
@@ -4030,7 +4039,7 @@ function estimateTransactionFee(feeRate, unit, networkType, txSize) {
4030
4039
 
4031
4040
  // src/utils/kkapi-detection.ts
4032
4041
  async function detectKkApiAvailability(forceLocalhost) {
4033
- const tag5 = " | detectKkApiAvailability | ";
4042
+ const tag6 = " | detectKkApiAvailability | ";
4034
4043
  try {
4035
4044
  const isTauri = typeof window !== "undefined" && "__TAURI__" in window;
4036
4045
  const isBrowser = typeof window !== "undefined";
@@ -4158,6 +4167,11 @@ function buildDashboardFromBalances(balances, blockchains, assetsMap) {
4158
4167
  return sum + balanceNum;
4159
4168
  }, 0).toString();
4160
4169
  const assetInfo = nativeAssetCaip ? assetsMap.get(nativeAssetCaip) : null;
4170
+ console.log(TAG7, `[DEBUG] Network: ${blockchain}`);
4171
+ console.log(TAG7, `[DEBUG] nativeAssetCaip: ${nativeAssetCaip}`);
4172
+ console.log(TAG7, `[DEBUG] assetInfo:`, assetInfo);
4173
+ console.log(TAG7, `[DEBUG] gasAsset:`, gasAsset);
4174
+ console.log(TAG7, `[DEBUG] Resolved name: ${gasAsset?.name || assetInfo?.name || "NO NAME"}`);
4161
4175
  networksTemp.push({
4162
4176
  networkId: blockchain,
4163
4177
  totalValueUsd: networkTotal,
@@ -4183,11 +4197,11 @@ function buildDashboardFromBalances(balances, blockchains, assetsMap) {
4183
4197
  // src/utils/sync-market.ts
4184
4198
  var TAG8 = " | sync-market | ";
4185
4199
  async function syncMarket(balances, pioneer) {
4186
- const tag5 = `${TAG8} | syncMarket | `;
4200
+ const tag6 = `${TAG8} | syncMarket | `;
4187
4201
  try {
4188
4202
  const invalidBalances = balances.filter((b3) => !b3 || !b3.caip || typeof b3.caip !== "string" || !b3.caip.includes(":"));
4189
4203
  if (invalidBalances.length > 0) {
4190
- console.warn(tag5, `Found ${invalidBalances.length} balances with invalid CAIPs:`, invalidBalances.map((b3) => ({
4204
+ console.warn(tag6, `Found ${invalidBalances.length} balances with invalid CAIPs:`, invalidBalances.map((b3) => ({
4191
4205
  caip: b3?.caip,
4192
4206
  type: typeof b3?.caip,
4193
4207
  symbol: b3?.symbol,
@@ -4202,7 +4216,7 @@ async function syncMarket(balances, pioneer) {
4202
4216
  console.log("GetMarketInfo: payload length: ", allCaips.length);
4203
4217
  const invalidEntries = allCaips.filter((caip) => typeof caip !== "string");
4204
4218
  if (invalidEntries.length > 0) {
4205
- console.error(tag5, "CRITICAL: Invalid entries detected in allCaips:", invalidEntries);
4219
+ console.error(tag6, "CRITICAL: Invalid entries detected in allCaips:", invalidEntries);
4206
4220
  throw new Error("Invalid CAIP entries detected - aborting market sync");
4207
4221
  }
4208
4222
  if (allCaips && allCaips.length > 0) {
@@ -4223,13 +4237,13 @@ async function syncMarket(balances, pioneer) {
4223
4237
  }
4224
4238
  }
4225
4239
  } catch (apiError) {
4226
- console.error(tag5, "API error fetching market info:", apiError);
4227
- console.warn(tag5, "Continuing without market prices");
4240
+ console.error(tag6, "API error fetching market info:", apiError);
4241
+ console.warn(tag6, "Continuing without market prices");
4228
4242
  }
4229
4243
  }
4230
4244
  return true;
4231
4245
  } catch (e) {
4232
- console.error(tag5, "e:", e);
4246
+ console.error(tag6, "e:", e);
4233
4247
  throw e;
4234
4248
  }
4235
4249
  }
@@ -4336,12 +4350,6 @@ class SDK {
4336
4350
  this.blockchains = config.blockchains ? [...new Set(config.blockchains)] : [];
4337
4351
  if (config.blockchains && config.blockchains.length !== this.blockchains.length) {
4338
4352
  }
4339
- if (config.pubkeys && config.pubkeys.length > 0) {
4340
- this.setPubkeys(config.pubkeys);
4341
- } else {
4342
- this.pubkeys = [];
4343
- this.pubkeySet.clear();
4344
- }
4345
4353
  this.balances = config.balances || [];
4346
4354
  this.nodes = config.nodes || [];
4347
4355
  this.charts = ["covalent", "zapper"];
@@ -4399,7 +4407,7 @@ class SDK {
4399
4407
  return true;
4400
4408
  };
4401
4409
  this.setPubkeys = (newPubkeys) => {
4402
- const tag5 = `${TAG9} | setPubkeys | `;
4410
+ const tag6 = `${TAG9} | setPubkeys | `;
4403
4411
  this.pubkeys = [];
4404
4412
  this.pubkeySet.clear();
4405
4413
  let added = 0;
@@ -4409,8 +4417,14 @@ class SDK {
4409
4417
  }
4410
4418
  }
4411
4419
  };
4420
+ if (config.pubkeys && config.pubkeys.length > 0) {
4421
+ this.setPubkeys(config.pubkeys);
4422
+ } else {
4423
+ this.pubkeys = [];
4424
+ this.pubkeySet.clear();
4425
+ }
4412
4426
  this.getUnifiedPortfolio = async function() {
4413
- const tag5 = `${TAG9} | getUnifiedPortfolio | `;
4427
+ const tag6 = `${TAG9} | getUnifiedPortfolio | `;
4414
4428
  try {
4415
4429
  const startTime = performance.now();
4416
4430
  try {
@@ -4421,17 +4435,17 @@ class SDK {
4421
4435
  signal: AbortSignal.timeout(2000)
4422
4436
  });
4423
4437
  if (!portfolioResponse.ok) {
4424
- console.warn(tag5, "Portfolio endpoint returned", portfolioResponse.status);
4438
+ console.warn(tag6, "Portfolio endpoint returned", portfolioResponse.status);
4425
4439
  return null;
4426
4440
  }
4427
4441
  const portfolioData = await portfolioResponse.json();
4428
4442
  const loadTime = performance.now() - startTime;
4429
4443
  if (!portfolioData.success) {
4430
- console.warn(tag5, "Portfolio API returned success=false");
4444
+ console.warn(tag6, "Portfolio API returned success=false");
4431
4445
  return null;
4432
4446
  }
4433
4447
  if (portfolioData.totalValueUsd === 0 || !portfolioData.totalValueUsd) {
4434
- console.warn(tag5, "Portfolio value is $0.00 - may need device connection or sync");
4448
+ console.warn(tag6, "Portfolio value is $0.00 - may need device connection or sync");
4435
4449
  return null;
4436
4450
  }
4437
4451
  let allBalances = [];
@@ -4506,19 +4520,19 @@ class SDK {
4506
4520
  };
4507
4521
  } catch (fetchError) {
4508
4522
  if (fetchError.name === "AbortError") {
4509
- console.log(tag5, "Unified portfolio request timed out (this is normal if vault not running)");
4523
+ console.log(tag6, "Unified portfolio request timed out (this is normal if vault not running)");
4510
4524
  } else {
4511
- console.log(tag5, "Failed to fetch unified portfolio:", fetchError.message);
4525
+ console.log(tag6, "Failed to fetch unified portfolio:", fetchError.message);
4512
4526
  }
4513
4527
  return null;
4514
4528
  }
4515
4529
  } catch (e) {
4516
- console.error(tag5, "Error:", e);
4530
+ console.error(tag6, "Error:", e);
4517
4531
  return null;
4518
4532
  }
4519
4533
  };
4520
4534
  this.init = async function(walletsVerbose, setup) {
4521
- const tag5 = `${TAG9} | init | `;
4535
+ const tag6 = `${TAG9} | init | `;
4522
4536
  try {
4523
4537
  if (!this.username)
4524
4538
  throw Error("username required!");
@@ -4601,7 +4615,7 @@ class SDK {
4601
4615
  }
4602
4616
  return this.pioneer;
4603
4617
  } catch (e) {
4604
- console.error(tag5, "e: ", e);
4618
+ console.error(tag6, "e: ", e);
4605
4619
  throw e;
4606
4620
  }
4607
4621
  };
@@ -4612,7 +4626,7 @@ class SDK {
4612
4626
  return syncMarket(this.balances, this.pioneer);
4613
4627
  };
4614
4628
  this.sync = async function() {
4615
- const tag5 = `${TAG9} | sync | `;
4629
+ const tag6 = `${TAG9} | sync | `;
4616
4630
  try {
4617
4631
  const matchesNetwork = (item, networkId) => {
4618
4632
  if (!item.networks || !Array.isArray(item.networks))
@@ -4664,16 +4678,16 @@ class SDK {
4664
4678
  let totalPortfolioValue = 0;
4665
4679
  const networksTemp = [];
4666
4680
  const uniqueBlockchains = [...new Set(this.blockchains)];
4667
- console.log(tag5, "uniqueBlockchains: ", uniqueBlockchains);
4681
+ console.log(tag6, "uniqueBlockchains: ", uniqueBlockchains);
4668
4682
  for (const blockchain of uniqueBlockchains) {
4669
4683
  const filteredBalances = this.balances.filter((b3) => {
4670
4684
  const networkId = caipToNetworkId7(b3.caip);
4671
4685
  return networkId === blockchain || blockchain === "eip155:*" && networkId.startsWith("eip155:");
4672
4686
  });
4673
- console.log(tag5, `Filtering for blockchain: ${blockchain}`);
4674
- console.log(tag5, `Found ${filteredBalances.length} balances before deduplication`);
4687
+ console.log(tag6, `Filtering for blockchain: ${blockchain}`);
4688
+ console.log(tag6, `Found ${filteredBalances.length} balances before deduplication`);
4675
4689
  filteredBalances.forEach((balance, idx) => {
4676
- console.log(tag5, `Balance[${idx}]:`, {
4690
+ console.log(tag6, `Balance[${idx}]:`, {
4677
4691
  caip: balance.caip,
4678
4692
  pubkey: balance.pubkey,
4679
4693
  balance: balance.balance,
@@ -4683,7 +4697,7 @@ class SDK {
4683
4697
  const balanceMap = new Map;
4684
4698
  const isBitcoin = blockchain.includes("bip122:000000000019d6689c085ae165831e93");
4685
4699
  if (isBitcoin) {
4686
- console.log(tag5, "Bitcoin network detected - checking for duplicate balances");
4700
+ console.log(tag6, "Bitcoin network detected - checking for duplicate balances");
4687
4701
  const bitcoinByValue = new Map;
4688
4702
  filteredBalances.forEach((balance) => {
4689
4703
  const valueKey = `${balance.balance}_${balance.valueUsd}`;
@@ -4694,7 +4708,7 @@ class SDK {
4694
4708
  });
4695
4709
  for (const [valueKey, balances] of bitcoinByValue.entries()) {
4696
4710
  if (balances.length === 3 && parseFloat(balances[0].valueUsd || "0") > 0) {
4697
- console.log(tag5, "BITCOIN API BUG DETECTED: All 3 address types have same balance, keeping only xpub");
4711
+ console.log(tag6, "BITCOIN API BUG DETECTED: All 3 address types have same balance, keeping only xpub");
4698
4712
  const xpubBalance = balances.find((b3) => b3.pubkey?.startsWith("xpub")) || balances[0];
4699
4713
  const key = `${xpubBalance.caip}_${xpubBalance.pubkey || "default"}`;
4700
4714
  balanceMap.set(key, xpubBalance);
@@ -4714,13 +4728,13 @@ class SDK {
4714
4728
  });
4715
4729
  }
4716
4730
  const networkBalances = Array.from(balanceMap.values());
4717
- console.log(tag5, "networkBalances (deduplicated): ", networkBalances);
4718
- console.log(tag5, "networkBalances count: ", networkBalances.length);
4731
+ console.log(tag6, "networkBalances (deduplicated): ", networkBalances);
4732
+ console.log(tag6, "networkBalances count: ", networkBalances.length);
4719
4733
  const networkTotal = networkBalances.reduce((sum, balance, idx) => {
4720
4734
  const valueUsd = typeof balance.valueUsd === "string" ? parseFloat(balance.valueUsd) : balance.valueUsd || 0;
4721
- console.log(tag5, `[${idx}] valueUsd:`, balance.valueUsd, "→ parsed:", valueUsd, "| running sum:", sum + valueUsd);
4735
+ console.log(tag6, `[${idx}] valueUsd:`, balance.valueUsd, "→ parsed:", valueUsd, "| running sum:", sum + valueUsd);
4722
4736
  if (blockchain.includes("bip122:000000000019d6689c085ae165831e93")) {
4723
- console.log(tag5, `[BITCOIN DEBUG ${idx}] pubkey:`, balance.pubkey?.substring(0, 10) + "...", "| balance:", balance.balance, "| valueUsd:", balance.valueUsd, "→ parsed:", valueUsd);
4737
+ console.log(tag6, `[BITCOIN DEBUG ${idx}] pubkey:`, balance.pubkey?.substring(0, 10) + "...", "| balance:", balance.balance, "| valueUsd:", balance.valueUsd, "→ parsed:", valueUsd);
4724
4738
  }
4725
4739
  return sum + valueUsd;
4726
4740
  }, 0);
@@ -4751,7 +4765,7 @@ class SDK {
4751
4765
  this.dashboard = dashboardData;
4752
4766
  return true;
4753
4767
  } catch (e) {
4754
- console.error(tag5, "Error in sync:", e);
4768
+ console.error(tag6, "Error in sync:", e);
4755
4769
  throw e;
4756
4770
  }
4757
4771
  };
@@ -4765,7 +4779,7 @@ class SDK {
4765
4779
  }
4766
4780
  };
4767
4781
  this.buildTx = async function(sendPayload) {
4768
- let tag5 = TAG9 + " | buildTx | ";
4782
+ let tag6 = TAG9 + " | buildTx | ";
4769
4783
  try {
4770
4784
  const transactionDependencies = {
4771
4785
  context: this.context,
@@ -4779,7 +4793,7 @@ class SDK {
4779
4793
  };
4780
4794
  let txManager = new TransactionManager(transactionDependencies, this.events);
4781
4795
  let unsignedTx = await txManager.transfer(sendPayload);
4782
- console.log(tag5, "unsignedTx: ", unsignedTx);
4796
+ console.log(tag6, "unsignedTx: ", unsignedTx);
4783
4797
  return unsignedTx;
4784
4798
  } catch (e) {
4785
4799
  console.error(e);
@@ -4787,14 +4801,14 @@ class SDK {
4787
4801
  }
4788
4802
  };
4789
4803
  this.buildDelegateTx = async function(caip, params) {
4790
- let tag5 = TAG9 + " | buildDelegateTx | ";
4804
+ let tag6 = TAG9 + " | buildDelegateTx | ";
4791
4805
  try {
4792
4806
  const delegateParams = {
4793
4807
  ...params,
4794
4808
  type: "delegate"
4795
4809
  };
4796
4810
  let unsignedTx = await createUnsignedStakingTx(caip, delegateParams, this.pubkeys, this.pioneer, this.pubkeyContext);
4797
- console.log(tag5, "unsignedTx: ", unsignedTx);
4811
+ console.log(tag6, "unsignedTx: ", unsignedTx);
4798
4812
  return unsignedTx;
4799
4813
  } catch (e) {
4800
4814
  console.error(e);
@@ -4802,14 +4816,14 @@ class SDK {
4802
4816
  }
4803
4817
  };
4804
4818
  this.buildUndelegateTx = async function(caip, params) {
4805
- let tag5 = TAG9 + " | buildUndelegateTx | ";
4819
+ let tag6 = TAG9 + " | buildUndelegateTx | ";
4806
4820
  try {
4807
4821
  const undelegateParams = {
4808
4822
  ...params,
4809
4823
  type: "undelegate"
4810
4824
  };
4811
4825
  let unsignedTx = await createUnsignedStakingTx(caip, undelegateParams, this.pubkeys, this.pioneer, this.pubkeyContext);
4812
- console.log(tag5, "unsignedTx: ", unsignedTx);
4826
+ console.log(tag6, "unsignedTx: ", unsignedTx);
4813
4827
  return unsignedTx;
4814
4828
  } catch (e) {
4815
4829
  console.error(e);
@@ -4817,14 +4831,14 @@ class SDK {
4817
4831
  }
4818
4832
  };
4819
4833
  this.buildClaimRewardsTx = async function(caip, params) {
4820
- let tag5 = TAG9 + " | buildClaimRewardsTx | ";
4834
+ let tag6 = TAG9 + " | buildClaimRewardsTx | ";
4821
4835
  try {
4822
4836
  const claimParams = {
4823
4837
  ...params,
4824
4838
  type: "claim_rewards"
4825
4839
  };
4826
4840
  let unsignedTx = await createUnsignedStakingTx(caip, claimParams, this.pubkeys, this.pioneer, this.pubkeyContext);
4827
- console.log(tag5, "unsignedTx: ", unsignedTx);
4841
+ console.log(tag6, "unsignedTx: ", unsignedTx);
4828
4842
  return unsignedTx;
4829
4843
  } catch (e) {
4830
4844
  console.error(e);
@@ -4832,7 +4846,7 @@ class SDK {
4832
4846
  }
4833
4847
  };
4834
4848
  this.buildClaimAllRewardsTx = async function(caip, params) {
4835
- let tag5 = TAG9 + " | buildClaimAllRewardsTx | ";
4849
+ let tag6 = TAG9 + " | buildClaimAllRewardsTx | ";
4836
4850
  try {
4837
4851
  const claimAllParams = {
4838
4852
  ...params,
@@ -4845,8 +4859,8 @@ class SDK {
4845
4859
  throw e;
4846
4860
  }
4847
4861
  };
4848
- this.signTx = async function(unsignedTx) {
4849
- let tag5 = TAG9 + " | signTx | ";
4862
+ this.signTx = async function(caip, unsignedTx) {
4863
+ let tag6 = TAG9 + " | signTx | ";
4850
4864
  try {
4851
4865
  const transactionDependencies = {
4852
4866
  context: this.context,
@@ -4859,7 +4873,7 @@ class SDK {
4859
4873
  keepKeySdk: this.keepKeySdk
4860
4874
  };
4861
4875
  let txManager = new TransactionManager(transactionDependencies, this.events);
4862
- let signedTx = await txManager.sign(unsignedTx);
4876
+ let signedTx = await txManager.sign({ caip, unsignedTx });
4863
4877
  return signedTx;
4864
4878
  } catch (e) {
4865
4879
  console.error(e);
@@ -4867,7 +4881,7 @@ class SDK {
4867
4881
  }
4868
4882
  };
4869
4883
  this.broadcastTx = async function(caip, signedTx) {
4870
- let tag5 = TAG9 + " | broadcastTx | ";
4884
+ let tag6 = TAG9 + " | broadcastTx | ";
4871
4885
  try {
4872
4886
  const transactionDependencies = {
4873
4887
  context: this.context,
@@ -4891,7 +4905,7 @@ class SDK {
4891
4905
  }
4892
4906
  };
4893
4907
  this.swap = async function(swapPayload) {
4894
- let tag5 = `${TAG9} | swap | `;
4908
+ let tag6 = `${TAG9} | swap | `;
4895
4909
  try {
4896
4910
  if (!swapPayload)
4897
4911
  throw Error("swapPayload required!");
@@ -4940,15 +4954,15 @@ class SDK {
4940
4954
  throw new Error(`Cannot use max amount: no balance found for ${swapPayload.caipIn}`);
4941
4955
  }
4942
4956
  let totalBalance = 0;
4943
- console.log(tag5, `Found ${inputBalances.length} balance entries for ${swapPayload.caipIn}`);
4957
+ console.log(tag6, `Found ${inputBalances.length} balance entries for ${swapPayload.caipIn}`);
4944
4958
  for (const balanceEntry of inputBalances) {
4945
4959
  const balance = parseFloat(balanceEntry.balance) || 0;
4946
4960
  totalBalance += balance;
4947
- console.log(tag5, ` - ${balanceEntry.pubkey || balanceEntry.identifier}: ${balance}`);
4961
+ console.log(tag6, ` - ${balanceEntry.pubkey || balanceEntry.identifier}: ${balance}`);
4948
4962
  }
4949
4963
  this.assetContext.balance = totalBalance.toString();
4950
4964
  this.assetContext.valueUsd = (totalBalance * parseFloat(this.assetContext.priceUsd || "0")).toFixed(2);
4951
- console.log(tag5, `Updated assetContext balance to aggregated total: ${totalBalance}`);
4965
+ console.log(tag6, `Updated assetContext balance to aggregated total: ${totalBalance}`);
4952
4966
  const feeReserves = {
4953
4967
  "bip122:000000000019d6689c085ae165831e93/slip44:0": 0.00005,
4954
4968
  "eip155:1/slip44:60": 0.001,
@@ -4959,7 +4973,7 @@ class SDK {
4959
4973
  };
4960
4974
  const reserve = feeReserves[swapPayload.caipIn] || 0.0001;
4961
4975
  inputAmount = Math.max(0, totalBalance - reserve);
4962
- console.log(tag5, `Using max amount for swap: ${inputAmount} (total balance: ${totalBalance}, reserve: ${reserve})`);
4976
+ console.log(tag6, `Using max amount for swap: ${inputAmount} (total balance: ${totalBalance}, reserve: ${reserve})`);
4963
4977
  } else {
4964
4978
  inputAmount = typeof swapPayload.amount === "string" ? parseFloat(swapPayload.amount) : swapPayload.amount;
4965
4979
  if (isNaN(inputAmount) || inputAmount <= 0) {
@@ -4967,23 +4981,23 @@ class SDK {
4967
4981
  }
4968
4982
  }
4969
4983
  let quote = {
4970
- affiliate: "0x658DE0443259a1027caA976ef9a42E6982037A03",
4971
- sellAsset: this.assetContext,
4984
+ sellAsset: this.assetContext.caip,
4972
4985
  sellAmount: inputAmount.toPrecision(8),
4973
- buyAsset: this.outboundAssetContext,
4986
+ buyAsset: this.outboundAssetContext.caip,
4974
4987
  recipientAddress,
4975
4988
  senderAddress,
4976
- slippage: "3"
4989
+ slippage: swapPayload.slippagePercentage || 3
4977
4990
  };
4978
4991
  let result;
4979
4992
  try {
4980
4993
  result = await this.pioneer.Quote(quote);
4981
4994
  result = result.data;
4982
4995
  } catch (e) {
4983
- console.error(tag5, "Failed to get quote: ", e);
4996
+ console.error(tag6, "Failed to get quote: ", e);
4997
+ throw Error("Quote API failed for path: " + quote.sellAsset + " -> " + quote.buyAsset + ". Error: " + e);
4984
4998
  }
4985
- if (result.length === 0)
4986
- throw Error("No quotes available! path: " + quote.sellAsset.caip + " -> " + quote.buyAsset.caip);
4999
+ if (!result || result.length === 0)
5000
+ throw Error("No quotes available! path: " + quote.sellAsset + " -> " + quote.buyAsset);
4987
5001
  let selected = result[0];
4988
5002
  let txs = selected.quote.txs;
4989
5003
  if (!txs)
@@ -4996,6 +5010,7 @@ class SDK {
4996
5010
  balances: this.balances,
4997
5011
  pioneer: this.pioneer,
4998
5012
  pubkeys: this.pubkeys,
5013
+ pubkeyContext: this.pubkeyContext,
4999
5014
  nodes: this.nodes,
5000
5015
  keepKeySdk: this.keepKeySdk
5001
5016
  };
@@ -5003,7 +5018,10 @@ class SDK {
5003
5018
  let caip = swapPayload.caipIn;
5004
5019
  let unsignedTx;
5005
5020
  if (tx.type === "deposit") {
5006
- unsignedTx = await createUnsignedTendermintTx(caip, tx.type, tx.txParams.amount, tx.txParams.memo, this.pubkeys, this.pioneer, this.keepKeySdk, false, undefined);
5021
+ unsignedTx = await createUnsignedTendermintTx(caip, tx.type, tx.txParams.amount, tx.txParams.memo, this.pubkeys, this.pioneer, this.pubkeyContext, false, undefined);
5022
+ } else if (tx.type === "EVM" || tx.type === "evm") {
5023
+ console.log(tag6, "Using pre-built EVM transaction from integration");
5024
+ unsignedTx = tx.txParams;
5007
5025
  } else {
5008
5026
  if (!tx.txParams.memo)
5009
5027
  throw Error("memo required on swaps!");
@@ -5021,12 +5039,12 @@ class SDK {
5021
5039
  return unsignedTx;
5022
5040
  }
5023
5041
  } catch (e) {
5024
- console.error(tag5, "Error: ", e);
5042
+ console.error(tag6, "Error: ", e);
5025
5043
  throw e;
5026
5044
  }
5027
5045
  };
5028
5046
  this.transfer = async function(sendPayload) {
5029
- let tag5 = `${TAG9} | transfer | `;
5047
+ let tag6 = `${TAG9} | transfer | `;
5030
5048
  try {
5031
5049
  if (!sendPayload)
5032
5050
  throw Error("sendPayload required!");
@@ -5060,15 +5078,15 @@ class SDK {
5060
5078
  return { txid, events: this.events };
5061
5079
  } catch (error) {
5062
5080
  if (error instanceof Error) {
5063
- console.error(tag5, "An error occurred during the transfer process:", error.message);
5081
+ console.error(tag6, "An error occurred during the transfer process:", error.message);
5064
5082
  } else {
5065
- console.error(tag5, "An unknown error occurred during the transfer process");
5083
+ console.error(tag6, "An unknown error occurred during the transfer process");
5066
5084
  }
5067
5085
  throw error;
5068
5086
  }
5069
5087
  };
5070
5088
  this.followTransaction = async function(caip, txid) {
5071
- let tag5 = " | followTransaction | ";
5089
+ let tag6 = " | followTransaction | ";
5072
5090
  try {
5073
5091
  const finalConfirmationBlocksByCaip = {
5074
5092
  dogecoin: 3,
@@ -5098,7 +5116,7 @@ class SDK {
5098
5116
  }
5099
5117
  }
5100
5118
  } catch (error) {
5101
- console.error(tag5, "Error:", error);
5119
+ console.error(tag6, "Error:", error);
5102
5120
  }
5103
5121
  if (!isConfirmed) {
5104
5122
  await new Promise((resolve) => setTimeout(resolve, 8000));
@@ -5116,18 +5134,18 @@ class SDK {
5116
5134
  requiredConfirmations
5117
5135
  };
5118
5136
  } catch (error) {
5119
- console.error(tag5, "Error:", error);
5137
+ console.error(tag6, "Error:", error);
5120
5138
  throw new Error("Failed to follow transaction");
5121
5139
  }
5122
5140
  };
5123
5141
  this.setBlockchains = async function(blockchains) {
5124
- const tag5 = `${TAG9} | setBlockchains | `;
5142
+ const tag6 = `${TAG9} | setBlockchains | `;
5125
5143
  try {
5126
5144
  if (!blockchains)
5127
5145
  throw Error("blockchains required!");
5128
5146
  const uniqueBlockchains = [...new Set(blockchains)];
5129
5147
  if (blockchains.length !== uniqueBlockchains.length) {
5130
- console.warn(tag5, `Removed ${blockchains.length - uniqueBlockchains.length} duplicate blockchains`);
5148
+ console.warn(tag6, `Removed ${blockchains.length - uniqueBlockchains.length} duplicate blockchains`);
5131
5149
  }
5132
5150
  this.blockchains = uniqueBlockchains;
5133
5151
  this.events.emit("SET_BLOCKCHAINS", this.blockchains);
@@ -5137,7 +5155,7 @@ class SDK {
5137
5155
  }
5138
5156
  };
5139
5157
  this.addAsset = async function(caip, data) {
5140
- let tag5 = TAG9 + " | addAsset | ";
5158
+ let tag6 = TAG9 + " | addAsset | ";
5141
5159
  try {
5142
5160
  let success = false;
5143
5161
  if (!caip)
@@ -5175,22 +5193,22 @@ class SDK {
5175
5193
  }
5176
5194
  };
5177
5195
  this.clearWalletState = async function() {
5178
- const tag5 = `${TAG9} | clearWalletState | `;
5196
+ const tag6 = `${TAG9} | clearWalletState | `;
5179
5197
  try {
5180
5198
  this.context = null;
5181
5199
  this.paths = [];
5182
5200
  this.blockchains = [];
5183
5201
  this.pubkeys = [];
5184
5202
  this.pubkeySet.clear();
5185
- console.log(tag5, "Cleared wallet state including pubkeys and tracking set");
5203
+ console.log(tag6, "Cleared wallet state including pubkeys and tracking set");
5186
5204
  return true;
5187
5205
  } catch (e) {
5188
- console.error(tag5, "e: ", e);
5206
+ console.error(tag6, "e: ", e);
5189
5207
  throw e;
5190
5208
  }
5191
5209
  };
5192
5210
  this.addPath = async function(path) {
5193
- const tag5 = `${TAG9} | addPath | `;
5211
+ const tag6 = `${TAG9} | addPath | `;
5194
5212
  try {
5195
5213
  this.paths.push(path);
5196
5214
  const pubkey = await getPubkey(path.networks[0], path, this.keepKeySdk, this.context);
@@ -5199,14 +5217,14 @@ class SDK {
5199
5217
  this.buildDashboardFromBalances();
5200
5218
  return { success: true, pubkey };
5201
5219
  } catch (e) {
5202
- console.error(tag5, "Failed:", e);
5220
+ console.error(tag6, "Failed:", e);
5203
5221
  throw e;
5204
5222
  }
5205
5223
  };
5206
5224
  this.addPaths = async function(paths) {
5207
- const tag5 = `${TAG9} | addPaths | `;
5225
+ const tag6 = `${TAG9} | addPaths | `;
5208
5226
  try {
5209
- console.log(tag5, `Adding ${paths.length} paths in batch mode...`);
5227
+ console.log(tag6, `Adding ${paths.length} paths in batch mode...`);
5210
5228
  this.paths.push(...paths);
5211
5229
  const newPubkeys = [];
5212
5230
  for (const path of paths) {
@@ -5215,10 +5233,10 @@ class SDK {
5215
5233
  this.addPubkey(pubkey);
5216
5234
  newPubkeys.push(pubkey);
5217
5235
  } catch (error) {
5218
- console.warn(tag5, `Failed to get pubkey for path ${path.note}:`, error.message);
5236
+ console.warn(tag6, `Failed to get pubkey for path ${path.note}:`, error.message);
5219
5237
  }
5220
5238
  }
5221
- console.log(tag5, `Successfully added ${newPubkeys.length} pubkeys`);
5239
+ console.log(tag6, `Successfully added ${newPubkeys.length} pubkeys`);
5222
5240
  const networkSet = new Set;
5223
5241
  for (const path of paths) {
5224
5242
  if (path.networks && Array.isArray(path.networks)) {
@@ -5226,13 +5244,13 @@ class SDK {
5226
5244
  }
5227
5245
  }
5228
5246
  const uniqueNetworks = [...networkSet];
5229
- console.log(tag5, `Fetching balances for ${uniqueNetworks.length} unique networks in single API call...`);
5247
+ console.log(tag6, `Fetching balances for ${uniqueNetworks.length} unique networks in single API call...`);
5230
5248
  await this.getBalancesForNetworks(uniqueNetworks);
5231
5249
  this.buildDashboardFromBalances();
5232
- console.log(tag5, `Batch add complete: ${paths.length} paths, ${newPubkeys.length} pubkeys, ${this.balances?.length || 0} balances`);
5250
+ console.log(tag6, `Batch add complete: ${paths.length} paths, ${newPubkeys.length} pubkeys, ${this.balances?.length || 0} balances`);
5233
5251
  return { success: true, pubkeys: newPubkeys };
5234
5252
  } catch (e) {
5235
- console.error(tag5, "Failed:", e);
5253
+ console.error(tag6, "Failed:", e);
5236
5254
  throw e;
5237
5255
  }
5238
5256
  };
@@ -5240,7 +5258,7 @@ class SDK {
5240
5258
  return this.getGasAssets();
5241
5259
  };
5242
5260
  this.getGasAssets = async function() {
5243
- const tag5 = `${TAG9} | getGasAssets | `;
5261
+ const tag6 = `${TAG9} | getGasAssets | `;
5244
5262
  try {
5245
5263
  for (let i = 0;i < this.blockchains.length; i++) {
5246
5264
  let networkId = this.blockchains[i];
@@ -5274,7 +5292,7 @@ class SDK {
5274
5292
  denom: "maya"
5275
5293
  };
5276
5294
  this.assetsMap.set(mayaTokenCaip, mayaToken);
5277
- console.log(tag5, "Added MAYA token to assetsMap");
5295
+ console.log(tag6, "Added MAYA token to assetsMap");
5278
5296
  }
5279
5297
  return this.assetsMap;
5280
5298
  } catch (e) {
@@ -5283,7 +5301,7 @@ class SDK {
5283
5301
  }
5284
5302
  };
5285
5303
  this.getPubkeys = async function() {
5286
- const tag5 = `${TAG9} | getPubkeys | `;
5304
+ const tag6 = `${TAG9} | getPubkeys | `;
5287
5305
  try {
5288
5306
  if (this.paths.length === 0)
5289
5307
  throw new Error("No paths found!");
@@ -5299,15 +5317,15 @@ class SDK {
5299
5317
  return pubkeys;
5300
5318
  } catch (error) {
5301
5319
  console.error("Error in getPubkeys:", error);
5302
- console.error(tag5, "Error in getPubkeys:", error);
5320
+ console.error(tag6, "Error in getPubkeys:", error);
5303
5321
  throw error;
5304
5322
  }
5305
5323
  };
5306
5324
  this.getBalancesForNetworks = async function(networkIds) {
5307
- const tag5 = `${TAG9} | getBalancesForNetworks | `;
5325
+ const tag6 = `${TAG9} | getBalancesForNetworks | `;
5308
5326
  try {
5309
5327
  if (!this.pioneer) {
5310
- console.error(tag5, "ERROR: Pioneer client not initialized! this.pioneer is:", this.pioneer);
5328
+ console.error(tag6, "ERROR: Pioneer client not initialized! this.pioneer is:", this.pioneer);
5311
5329
  throw new Error("Pioneer client not initialized. Call init() first.");
5312
5330
  }
5313
5331
  const assetQuery = [];
@@ -5345,48 +5363,48 @@ class SDK {
5345
5363
  identifier: `${balance.caip}:${balance.pubkey}`
5346
5364
  });
5347
5365
  }
5348
- console.log(tag5, "balances: ", balances);
5366
+ console.log(tag6, "balances: ", balances);
5349
5367
  this.balances = balances;
5350
5368
  this.events.emit("SET_BALANCES", this.balances);
5351
5369
  return this.balances;
5352
5370
  } catch (apiError) {
5353
- console.error(tag5, "GetPortfolioBalances API call failed:", apiError);
5371
+ console.error(tag6, "GetPortfolioBalances API call failed:", apiError);
5354
5372
  throw new Error(`GetPortfolioBalances API call failed: ${apiError?.message || "Unknown error"}`);
5355
5373
  }
5356
5374
  } catch (e) {
5357
- console.error(tag5, "Error: ", e);
5375
+ console.error(tag6, "Error: ", e);
5358
5376
  throw e;
5359
5377
  }
5360
5378
  };
5361
5379
  this.getBalances = async function() {
5362
- const tag5 = `${TAG9} | getBalances | `;
5380
+ const tag6 = `${TAG9} | getBalances | `;
5363
5381
  try {
5364
5382
  return await this.getBalancesForNetworks(this.blockchains);
5365
5383
  } catch (e) {
5366
- console.error(tag5, "Error in getBalances: ", e);
5384
+ console.error(tag6, "Error in getBalances: ", e);
5367
5385
  throw e;
5368
5386
  }
5369
5387
  };
5370
5388
  this.getBalance = async function(networkId) {
5371
- const tag5 = `${TAG9} | getBalance | `;
5389
+ const tag6 = `${TAG9} | getBalance | `;
5372
5390
  try {
5373
5391
  const results = await this.getBalancesForNetworks([networkId]);
5374
5392
  const filtered = results.filter(async (b3) => b3.networkId === await networkIdToCaip2(networkId));
5375
5393
  return filtered;
5376
5394
  } catch (e) {
5377
- console.error(tag5, "Error: ", e);
5395
+ console.error(tag6, "Error: ", e);
5378
5396
  throw e;
5379
5397
  }
5380
5398
  };
5381
5399
  this.getFees = async function(networkId) {
5382
- const tag5 = `${TAG9} | getFees | `;
5400
+ const tag6 = `${TAG9} | getFees | `;
5383
5401
  try {
5384
5402
  if (!this.pioneer) {
5385
5403
  throw new Error("Pioneer client not initialized. Call init() first.");
5386
5404
  }
5387
5405
  return await getFees(this.pioneer, networkId);
5388
5406
  } catch (e) {
5389
- console.error(tag5, "Error getting fees: ", e);
5407
+ console.error(tag6, "Error getting fees: ", e);
5390
5408
  throw e;
5391
5409
  }
5392
5410
  };
@@ -5394,11 +5412,11 @@ class SDK {
5394
5412
  return estimateTransactionFee(feeRate, unit, networkType, txSize);
5395
5413
  };
5396
5414
  this.getCharts = async function() {
5397
- const tag5 = `${TAG9} | getCharts | `;
5415
+ const tag6 = `${TAG9} | getCharts | `;
5398
5416
  try {
5399
- console.log(tag5, "Fetching charts");
5417
+ console.log(tag6, "Fetching charts");
5400
5418
  const newBalances = await getCharts(this.blockchains, this.pioneer, this.pubkeys, this.context);
5401
- console.log(tag5, "newBalances: ", newBalances);
5419
+ console.log(tag6, "newBalances: ", newBalances);
5402
5420
  const uniqueBalances = new Map([...this.balances, ...newBalances].map((balance) => [
5403
5421
  balance.identifier,
5404
5422
  {
@@ -5406,17 +5424,17 @@ class SDK {
5406
5424
  type: balance.type || "balance"
5407
5425
  }
5408
5426
  ]));
5409
- console.log(tag5, "uniqueBalances: ", uniqueBalances);
5427
+ console.log(tag6, "uniqueBalances: ", uniqueBalances);
5410
5428
  this.balances = Array.from(uniqueBalances.values());
5411
- console.log(tag5, "Updated this.balances: ", this.balances);
5429
+ console.log(tag6, "Updated this.balances: ", this.balances);
5412
5430
  return this.balances;
5413
5431
  } catch (e) {
5414
- console.error(tag5, "Error in getCharts:", e);
5432
+ console.error(tag6, "Error in getCharts:", e);
5415
5433
  throw e;
5416
5434
  }
5417
5435
  };
5418
5436
  this.setContext = async (context) => {
5419
- const tag5 = `${TAG9} | setContext | `;
5437
+ const tag6 = `${TAG9} | setContext | `;
5420
5438
  try {
5421
5439
  if (!context)
5422
5440
  throw Error("context required!");
@@ -5424,12 +5442,12 @@ class SDK {
5424
5442
  this.events.emit("SET_CONTEXT", context);
5425
5443
  return { success: true };
5426
5444
  } catch (e) {
5427
- console.error(tag5, "e: ", e);
5445
+ console.error(tag6, "e: ", e);
5428
5446
  return { success: false };
5429
5447
  }
5430
5448
  };
5431
5449
  this.setContextType = async (contextType) => {
5432
- const tag5 = `${TAG9} | setContextType | `;
5450
+ const tag6 = `${TAG9} | setContextType | `;
5433
5451
  try {
5434
5452
  if (!contextType)
5435
5453
  throw Error("contextType required!");
@@ -5437,22 +5455,22 @@ class SDK {
5437
5455
  this.events.emit("SET_CONTEXT_TYPE", contextType);
5438
5456
  return { success: true };
5439
5457
  } catch (e) {
5440
- console.error(tag5, "e: ", e);
5458
+ console.error(tag6, "e: ", e);
5441
5459
  return { success: false };
5442
5460
  }
5443
5461
  };
5444
5462
  this.refresh = async () => {
5445
- const tag5 = `${TAG9} | refresh | `;
5463
+ const tag6 = `${TAG9} | refresh | `;
5446
5464
  try {
5447
5465
  await this.sync();
5448
5466
  return this.balances;
5449
5467
  } catch (e) {
5450
- console.error(tag5, "e: ", e);
5468
+ console.error(tag6, "e: ", e);
5451
5469
  throw e;
5452
5470
  }
5453
5471
  };
5454
5472
  this.setAssetContext = async function(asset) {
5455
- const tag5 = `${TAG9} | setAssetContext | `;
5473
+ const tag6 = `${TAG9} | setAssetContext | `;
5456
5474
  try {
5457
5475
  if (!asset) {
5458
5476
  this.assetContext = null;
@@ -5464,7 +5482,7 @@ class SDK {
5464
5482
  asset.networkId = caipToNetworkId7(asset.caip);
5465
5483
  if (!this.pubkeys || this.pubkeys.length === 0) {
5466
5484
  const errorMsg = `Cannot set asset context for ${asset.caip} - no pubkeys loaded. Please initialize wallet first.`;
5467
- console.error(tag5, errorMsg);
5485
+ console.error(tag6, errorMsg);
5468
5486
  throw new Error(errorMsg);
5469
5487
  }
5470
5488
  const pubkeysForNetwork = this.pubkeys.filter((e) => {
@@ -5479,8 +5497,8 @@ class SDK {
5479
5497
  });
5480
5498
  if (pubkeysForNetwork.length === 0) {
5481
5499
  const errorMsg = `Cannot set asset context for ${asset.caip} - no address/xpub found for network ${asset.networkId}`;
5482
- console.error(tag5, errorMsg);
5483
- console.error(tag5, "Available networks in pubkeys:", [
5500
+ console.error(tag6, errorMsg);
5501
+ console.error(tag6, "Available networks in pubkeys:", [
5484
5502
  ...new Set(this.pubkeys.flatMap((p2) => p2.networks || []))
5485
5503
  ]);
5486
5504
  throw new Error(errorMsg);
@@ -5490,43 +5508,43 @@ class SDK {
5490
5508
  const xpubFound = pubkeysForNetwork.some((p2) => p2.type === "xpub" && p2.pubkey);
5491
5509
  if (!xpubFound) {
5492
5510
  const errorMsg = `Cannot set asset context for UTXO chain ${asset.caip} - xpub required but not found`;
5493
- console.error(tag5, errorMsg);
5511
+ console.error(tag6, errorMsg);
5494
5512
  throw new Error(errorMsg);
5495
5513
  }
5496
5514
  }
5497
5515
  const hasValidAddress = pubkeysForNetwork.some((p2) => p2.address || p2.master || p2.pubkey);
5498
5516
  if (!hasValidAddress) {
5499
5517
  const errorMsg = `Cannot set asset context for ${asset.caip} - no valid address found in pubkeys`;
5500
- console.error(tag5, errorMsg);
5518
+ console.error(tag6, errorMsg);
5501
5519
  throw new Error(errorMsg);
5502
5520
  }
5503
- console.log(tag5, `✅ Validated: Found ${pubkeysForNetwork.length} addresses for ${asset.networkId}`);
5521
+ console.log(tag6, `✅ Validated: Found ${pubkeysForNetwork.length} addresses for ${asset.networkId}`);
5504
5522
  let freshPriceUsd = 0;
5505
5523
  try {
5506
5524
  if (!asset.caip || typeof asset.caip !== "string" || !asset.caip.includes(":")) {
5507
- console.warn(tag5, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
5525
+ console.warn(tag6, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
5508
5526
  } else {
5509
- console.log(tag5, "Fetching fresh market price for:", asset.caip);
5527
+ console.log(tag6, "Fetching fresh market price for:", asset.caip);
5510
5528
  const marketData = await this.pioneer.GetMarketInfo([asset.caip]);
5511
- console.log(tag5, "Market data response:", marketData);
5529
+ console.log(tag6, "Market data response:", marketData);
5512
5530
  if (marketData && marketData.data && marketData.data.length > 0) {
5513
5531
  freshPriceUsd = marketData.data[0];
5514
- console.log(tag5, "✅ Fresh market price:", freshPriceUsd);
5532
+ console.log(tag6, "✅ Fresh market price:", freshPriceUsd);
5515
5533
  } else {
5516
- console.warn(tag5, "No market data returned for:", asset.caip);
5534
+ console.warn(tag6, "No market data returned for:", asset.caip);
5517
5535
  }
5518
5536
  }
5519
5537
  } catch (marketError) {
5520
- console.error(tag5, "Error fetching market price:", marketError);
5538
+ console.error(tag6, "Error fetching market price:", marketError);
5521
5539
  }
5522
5540
  let assetInfo = this.assetsMap.get(asset.caip.toLowerCase());
5523
- console.log(tag5, "assetInfo: ", assetInfo);
5541
+ console.log(tag6, "assetInfo: ", assetInfo);
5524
5542
  let assetInfoDiscovery = assetData2[asset.caip];
5525
- console.log(tag5, "assetInfoDiscovery: ", assetInfoDiscovery);
5543
+ console.log(tag6, "assetInfoDiscovery: ", assetInfoDiscovery);
5526
5544
  if (assetInfoDiscovery)
5527
5545
  assetInfo = assetInfoDiscovery;
5528
5546
  if (!assetInfo) {
5529
- console.log(tag5, "Building placeholder asset!");
5547
+ console.log(tag6, "Building placeholder asset!");
5530
5548
  assetInfo = {
5531
5549
  caip: asset.caip.toLowerCase(),
5532
5550
  networkId: asset.networkId,
@@ -5543,30 +5561,30 @@ class SDK {
5543
5561
  const valueUsd = parseFloat(matchingBalances[0].valueUsd);
5544
5562
  if (balance > 0 && valueUsd > 0) {
5545
5563
  priceValue = valueUsd / balance;
5546
- console.log(tag5, "calculated priceUsd from valueUsd/balance:", priceValue);
5564
+ console.log(tag6, "calculated priceUsd from valueUsd/balance:", priceValue);
5547
5565
  }
5548
5566
  }
5549
5567
  if (priceValue && priceValue > 0) {
5550
- console.log(tag5, "detected priceUsd from balance:", priceValue);
5568
+ console.log(tag6, "detected priceUsd from balance:", priceValue);
5551
5569
  assetInfo.priceUsd = priceValue;
5552
5570
  }
5553
5571
  }
5554
5572
  if (freshPriceUsd && freshPriceUsd > 0) {
5555
5573
  assetInfo.priceUsd = freshPriceUsd;
5556
- console.log(tag5, "✅ Using fresh market price:", freshPriceUsd);
5574
+ console.log(tag6, "✅ Using fresh market price:", freshPriceUsd);
5557
5575
  let totalBalance = 0;
5558
5576
  let totalValueUsd = 0;
5559
- console.log(tag5, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5577
+ console.log(tag6, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5560
5578
  for (const balanceEntry of matchingBalances) {
5561
5579
  const balance = parseFloat(balanceEntry.balance) || 0;
5562
5580
  const valueUsd = parseFloat(balanceEntry.valueUsd) || 0;
5563
5581
  totalBalance += balance;
5564
5582
  totalValueUsd += valueUsd;
5565
- console.log(tag5, ` Balance entry: ${balance} (${valueUsd} USD)`);
5583
+ console.log(tag6, ` Balance entry: ${balance} (${valueUsd} USD)`);
5566
5584
  }
5567
5585
  assetInfo.balance = totalBalance.toString();
5568
5586
  assetInfo.valueUsd = totalValueUsd.toFixed(2);
5569
- console.log(tag5, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5587
+ console.log(tag6, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5570
5588
  }
5571
5589
  const assetBalances = this.balances.filter((b3) => b3.caip === asset.caip);
5572
5590
  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")));
@@ -5586,7 +5604,7 @@ class SDK {
5586
5604
  const balanceAmount = parseFloat(balance.balance || 0);
5587
5605
  balance.valueUsd = (balanceAmount * freshPriceUsd).toString();
5588
5606
  }
5589
- console.log(tag5, "Updated all balances with fresh price data");
5607
+ console.log(tag6, "Updated all balances with fresh price data");
5590
5608
  }
5591
5609
  this.assetContext = finalAssetContext;
5592
5610
  if (asset.isToken || asset.type === "token" || assetInfo.isToken || assetInfo.type === "token") {
@@ -5638,20 +5656,20 @@ class SDK {
5638
5656
  const currentContextValid = this.pubkeyContext?.networks?.includes(networkId);
5639
5657
  if (!this.pubkeyContext || !currentContextValid) {
5640
5658
  this.pubkeyContext = assetPubkeys[0];
5641
- console.log(tag5, "Auto-set pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey);
5659
+ console.log(tag6, "Auto-set pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey);
5642
5660
  } else {
5643
- console.log(tag5, "Preserving existing pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey, `(addressNList: [${(this.pubkeyContext.addressNList || this.pubkeyContext.addressNListMaster).join(", ")}])`);
5661
+ console.log(tag6, "Preserving existing pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey, `(addressNList: [${(this.pubkeyContext.addressNList || this.pubkeyContext.addressNListMaster).join(", ")}])`);
5644
5662
  }
5645
5663
  }
5646
5664
  this.events.emit("SET_ASSET_CONTEXT", this.assetContext);
5647
5665
  return this.assetContext;
5648
5666
  } catch (e) {
5649
- console.error(tag5, "e: ", e);
5667
+ console.error(tag6, "e: ", e);
5650
5668
  throw e;
5651
5669
  }
5652
5670
  };
5653
5671
  this.setPubkeyContext = async function(pubkey) {
5654
- let tag5 = `${TAG9} | setPubkeyContext | `;
5672
+ let tag6 = `${TAG9} | setPubkeyContext | `;
5655
5673
  try {
5656
5674
  if (!pubkey)
5657
5675
  throw Error("pubkey is required");
@@ -5659,31 +5677,31 @@ class SDK {
5659
5677
  throw Error("invalid pubkey: missing pubkey or address");
5660
5678
  const exists = this.pubkeys.some((pk) => pk.pubkey === pubkey.pubkey || pk.address === pubkey.address || pk.pubkey === pubkey.address);
5661
5679
  if (!exists) {
5662
- console.warn(tag5, "Pubkey not found in current pubkeys array");
5680
+ console.warn(tag6, "Pubkey not found in current pubkeys array");
5663
5681
  }
5664
5682
  this.pubkeyContext = pubkey;
5665
- console.log(tag5, "Pubkey context set to:", pubkey.address || pubkey.pubkey, "note:", pubkey.note, "addressNList:", pubkey.addressNList || pubkey.addressNListMaster);
5683
+ console.log(tag6, "Pubkey context set to:", pubkey.address || pubkey.pubkey, "note:", pubkey.note, "addressNList:", pubkey.addressNList || pubkey.addressNListMaster);
5666
5684
  return true;
5667
5685
  } catch (e) {
5668
- console.error(tag5, "e: ", e);
5686
+ console.error(tag6, "e: ", e);
5669
5687
  throw e;
5670
5688
  }
5671
5689
  };
5672
5690
  this.setOutboundAssetContext = async function(asset) {
5673
- const tag5 = `${TAG9} | setOutputAssetContext | `;
5691
+ const tag6 = `${TAG9} | setOutputAssetContext | `;
5674
5692
  try {
5675
- console.log(tag5, "0. asset: ", asset);
5693
+ console.log(tag6, "0. asset: ", asset);
5676
5694
  if (!asset) {
5677
5695
  this.outboundAssetContext = null;
5678
5696
  return;
5679
5697
  }
5680
- console.log(tag5, "1 asset: ", asset);
5698
+ console.log(tag6, "1 asset: ", asset);
5681
5699
  if (!asset.caip)
5682
5700
  throw Error("Invalid Asset! missing caip!");
5683
5701
  if (!asset.networkId)
5684
5702
  asset.networkId = caipToNetworkId7(asset.caip);
5685
- console.log(tag5, "networkId: ", asset.networkId);
5686
- console.log(tag5, "this.pubkeys: ", this.pubkeys);
5703
+ console.log(tag6, "networkId: ", asset.networkId);
5704
+ console.log(tag6, "this.pubkeys: ", this.pubkeys);
5687
5705
  const pubkey = this.pubkeys.find((p2) => {
5688
5706
  if (!p2.networks || !Array.isArray(p2.networks))
5689
5707
  return false;
@@ -5698,23 +5716,23 @@ class SDK {
5698
5716
  let freshPriceUsd = 0;
5699
5717
  try {
5700
5718
  if (!asset.caip || typeof asset.caip !== "string" || !asset.caip.includes(":")) {
5701
- console.warn(tag5, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
5719
+ console.warn(tag6, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
5702
5720
  } else {
5703
- console.log(tag5, "Fetching fresh market price for:", asset.caip);
5721
+ console.log(tag6, "Fetching fresh market price for:", asset.caip);
5704
5722
  const marketData = await this.pioneer.GetMarketInfo([asset.caip]);
5705
- console.log(tag5, "Market data response:", marketData);
5723
+ console.log(tag6, "Market data response:", marketData);
5706
5724
  if (marketData && marketData.data && marketData.data.length > 0) {
5707
5725
  freshPriceUsd = marketData.data[0];
5708
- console.log(tag5, "✅ Fresh market price:", freshPriceUsd);
5726
+ console.log(tag6, "✅ Fresh market price:", freshPriceUsd);
5709
5727
  } else {
5710
- console.warn(tag5, "No market data returned for:", asset.caip);
5728
+ console.warn(tag6, "No market data returned for:", asset.caip);
5711
5729
  }
5712
5730
  }
5713
5731
  } catch (marketError) {
5714
- console.error(tag5, "Error fetching market price:", marketError);
5732
+ console.error(tag6, "Error fetching market price:", marketError);
5715
5733
  }
5716
5734
  let assetInfo = this.assetsMap.get(asset.caip.toLowerCase());
5717
- console.log(tag5, "assetInfo: ", assetInfo);
5735
+ console.log(tag6, "assetInfo: ", assetInfo);
5718
5736
  if (!assetInfo) {
5719
5737
  assetInfo = {
5720
5738
  caip: asset.caip.toLowerCase(),
@@ -5732,45 +5750,45 @@ class SDK {
5732
5750
  const valueUsd = parseFloat(matchingBalances[0].valueUsd);
5733
5751
  if (balance > 0 && valueUsd > 0) {
5734
5752
  priceValue = valueUsd / balance;
5735
- console.log(tag5, "calculated priceUsd from valueUsd/balance:", priceValue);
5753
+ console.log(tag6, "calculated priceUsd from valueUsd/balance:", priceValue);
5736
5754
  }
5737
5755
  }
5738
5756
  if (priceValue && priceValue > 0) {
5739
- console.log(tag5, "detected priceUsd from balance:", priceValue);
5757
+ console.log(tag6, "detected priceUsd from balance:", priceValue);
5740
5758
  assetInfo.priceUsd = priceValue;
5741
5759
  }
5742
5760
  }
5743
5761
  if (freshPriceUsd && freshPriceUsd > 0) {
5744
5762
  assetInfo.priceUsd = freshPriceUsd;
5745
- console.log(tag5, "✅ Using fresh market price:", freshPriceUsd);
5763
+ console.log(tag6, "✅ Using fresh market price:", freshPriceUsd);
5746
5764
  let totalBalance = 0;
5747
5765
  let totalValueUsd = 0;
5748
- console.log(tag5, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5766
+ console.log(tag6, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5749
5767
  for (const balanceEntry of matchingBalances) {
5750
5768
  const balance = parseFloat(balanceEntry.balance) || 0;
5751
5769
  const valueUsd = parseFloat(balanceEntry.valueUsd) || 0;
5752
5770
  totalBalance += balance;
5753
5771
  totalValueUsd += valueUsd;
5754
- console.log(tag5, ` Balance entry: ${balance} (${valueUsd} USD)`);
5772
+ console.log(tag6, ` Balance entry: ${balance} (${valueUsd} USD)`);
5755
5773
  }
5756
5774
  assetInfo.balance = totalBalance.toString();
5757
5775
  assetInfo.valueUsd = totalValueUsd.toFixed(2);
5758
- console.log(tag5, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5776
+ console.log(tag6, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5759
5777
  }
5760
- console.log(tag5, "CHECKPOINT 1");
5778
+ console.log(tag6, "CHECKPOINT 1");
5761
5779
  this.outboundAssetContext = { ...assetInfo, ...asset, ...pubkey };
5762
- console.log(tag5, "CHECKPOINT 3");
5763
- console.log(tag5, "outboundAssetContext: assetInfo: ", assetInfo);
5780
+ console.log(tag6, "CHECKPOINT 3");
5781
+ console.log(tag6, "outboundAssetContext: assetInfo: ", assetInfo);
5764
5782
  if (asset.caip) {
5765
5783
  this.outboundBlockchainContext = caipToNetworkId7(asset.caip);
5766
5784
  } else if (asset.networkId) {
5767
5785
  this.outboundBlockchainContext = asset.networkId;
5768
5786
  }
5769
- console.log(tag5, "CHECKPOINT 4");
5787
+ console.log(tag6, "CHECKPOINT 4");
5770
5788
  this.events.emit("SET_OUTBOUND_ASSET_CONTEXT", this.outboundAssetContext);
5771
5789
  return this.outboundAssetContext;
5772
5790
  } catch (e) {
5773
- console.error(tag5, "e: ", e);
5791
+ console.error(tag6, "e: ", e);
5774
5792
  throw e;
5775
5793
  }
5776
5794
  };