@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.cjs CHANGED
@@ -157,46 +157,44 @@ var require_lib = __commonJS((exports2) => {
157
157
  return { value: op[0] ? op[1] : undefined, done: true };
158
158
  }
159
159
  };
160
+ var __importDefault = exports2 && exports2.__importDefault || function(mod) {
161
+ return mod && mod.__esModule ? mod : { default: mod };
162
+ };
160
163
  Object.defineProperty(exports2, "__esModule", { value: true });
161
164
  exports2.Pioneer = undefined;
162
- var Swagger;
163
- var log;
164
- if (typeof window === "undefined") {
165
- Swagger = require("swagger-client");
166
- log = require("@pioneer-platform/loggerdog")();
167
- } else {
168
- Swagger = null;
169
- log = {
170
- debug: function() {
171
- var args = [];
172
- for (var _i = 0;_i < arguments.length; _i++) {
173
- args[_i] = arguments[_i];
174
- }
175
- return console.debug.apply(console, args);
176
- },
177
- info: function() {
178
- var args = [];
179
- for (var _i = 0;_i < arguments.length; _i++) {
180
- args[_i] = arguments[_i];
181
- }
182
- return console.info.apply(console, args);
183
- },
184
- warn: function() {
185
- var args = [];
186
- for (var _i = 0;_i < arguments.length; _i++) {
187
- args[_i] = arguments[_i];
188
- }
189
- return console.warn.apply(console, args);
190
- },
191
- error: function() {
192
- var args = [];
193
- for (var _i = 0;_i < arguments.length; _i++) {
194
- args[_i] = arguments[_i];
195
- }
196
- return console.error.apply(console, args);
165
+ var swagger_client_1 = __importDefault(require("swagger-client"));
166
+ var loggerdog_1 = __importDefault(require("@pioneer-platform/loggerdog"));
167
+ var log = typeof window === "undefined" ? (0, loggerdog_1.default)() : {
168
+ debug: function() {
169
+ var args = [];
170
+ for (var _i = 0;_i < arguments.length; _i++) {
171
+ args[_i] = arguments[_i];
197
172
  }
198
- };
199
- }
173
+ return console.debug.apply(console, args);
174
+ },
175
+ info: function() {
176
+ var args = [];
177
+ for (var _i = 0;_i < arguments.length; _i++) {
178
+ args[_i] = arguments[_i];
179
+ }
180
+ return console.info.apply(console, args);
181
+ },
182
+ warn: function() {
183
+ var args = [];
184
+ for (var _i = 0;_i < arguments.length; _i++) {
185
+ args[_i] = arguments[_i];
186
+ }
187
+ return console.warn.apply(console, args);
188
+ },
189
+ error: function() {
190
+ var args = [];
191
+ for (var _i = 0;_i < arguments.length; _i++) {
192
+ args[_i] = arguments[_i];
193
+ }
194
+ return console.error.apply(console, args);
195
+ }
196
+ };
197
+ var Swagger = swagger_client_1.default;
200
198
  var TAG = " | Client | ";
201
199
  function customHttpClient(req) {
202
200
  var _this = this;
@@ -206,7 +204,7 @@ var require_lib = __commonJS((exports2) => {
206
204
  }, 60000);
207
205
  log.debug(TAG, "HTTP request URL:", req.url);
208
206
  log.debug(TAG, "HTTP request details:", req);
209
- if (Swagger && Swagger.http) {
207
+ if (Swagger.http) {
210
208
  Swagger.http(req).then(function(response) {
211
209
  clearTimeout(timer);
212
210
  resolve(response);
@@ -260,11 +258,11 @@ var require_lib = __commonJS((exports2) => {
260
258
  this.spec = spec;
261
259
  this.queryKey = config.queryKey;
262
260
  this.pioneer = {};
263
- this.timeout = config.queryKey || 45000;
261
+ this.timeout = config.timeout || 45000;
264
262
  }
265
263
  Pioneer2.prototype.init = function() {
266
264
  return __awaiter(this, undefined, undefined, function() {
267
- var tag, _a, specResponse, specData_1, e_1;
265
+ var tag, _a, e_1;
268
266
  var _this = this;
269
267
  return __generator(this, function(_b) {
270
268
  switch (_b.label) {
@@ -272,11 +270,9 @@ var require_lib = __commonJS((exports2) => {
272
270
  tag = TAG + " | init | ";
273
271
  _b.label = 1;
274
272
  case 1:
275
- _b.trys.push([1, 7, , 8]);
273
+ _b.trys.push([1, 3, , 4]);
276
274
  if (!this.queryKey)
277
275
  throw Error(" You must create an api key! ");
278
- if (!Swagger)
279
- return [3, 3];
280
276
  _a = this;
281
277
  return [4, new Swagger({
282
278
  url: this.spec,
@@ -302,73 +298,6 @@ var require_lib = __commonJS((exports2) => {
302
298
  })];
303
299
  case 2:
304
300
  _a.client = _b.sent();
305
- return [3, 6];
306
- case 3:
307
- return [4, fetch(this.spec)];
308
- case 4:
309
- specResponse = _b.sent();
310
- return [4, specResponse.json()];
311
- case 5:
312
- specData_1 = _b.sent();
313
- this.client = {
314
- spec: specData_1,
315
- execute: function(request) {
316
- return __awaiter(_this, undefined, undefined, function() {
317
- var operationId, parameters, requestBody, targetPath, targetMethod, path, method, baseUrl, finalPath, _i, _a2, _b2, key, value, placeholder, url, httpReq;
318
- return __generator(this, function(_c) {
319
- switch (_c.label) {
320
- case 0:
321
- operationId = request.operationId, parameters = request.parameters, requestBody = request.requestBody;
322
- targetPath = "";
323
- targetMethod = "";
324
- for (path in specData_1.paths) {
325
- for (method in specData_1.paths[path]) {
326
- if (specData_1.paths[path][method].operationId === operationId) {
327
- targetPath = path;
328
- targetMethod = method;
329
- break;
330
- }
331
- }
332
- if (targetPath)
333
- break;
334
- }
335
- if (!targetPath) {
336
- throw new Error("Operation ".concat(operationId, " not found in spec"));
337
- }
338
- baseUrl = this.spec.replace("/spec/swagger.json", "");
339
- if (specData_1.servers && specData_1.servers.length > 0) {
340
- baseUrl = specData_1.servers[0].url;
341
- }
342
- finalPath = targetPath;
343
- if (parameters) {
344
- for (_i = 0, _a2 = Object.entries(parameters);_i < _a2.length; _i++) {
345
- _b2 = _a2[_i], key = _b2[0], value = _b2[1];
346
- placeholder = "{".concat(key, "}");
347
- if (finalPath.includes(placeholder)) {
348
- finalPath = finalPath.replace(placeholder, encodeURIComponent(String(value)));
349
- }
350
- }
351
- }
352
- url = "".concat(baseUrl).concat(finalPath);
353
- httpReq = {
354
- method: targetMethod.toUpperCase(),
355
- url,
356
- headers: {
357
- Authorization: this.queryKey,
358
- "Content-Type": "application/json"
359
- },
360
- body: requestBody
361
- };
362
- return [4, customHttpClient(httpReq)];
363
- case 1:
364
- return [2, _c.sent()];
365
- }
366
- });
367
- });
368
- }
369
- };
370
- _b.label = 6;
371
- case 6:
372
301
  Object.keys(this.client.spec.paths).forEach(function(path) {
373
302
  Object.keys(_this.client.spec.paths[path]).forEach(function(method) {
374
303
  var operationId = _this.client.spec.paths[path][method].operationId;
@@ -426,11 +355,11 @@ var require_lib = __commonJS((exports2) => {
426
355
  });
427
356
  });
428
357
  return [2, this.pioneer];
429
- case 7:
358
+ case 3:
430
359
  e_1 = _b.sent();
431
360
  log.error(TAG, "Initialization error:", e_1);
432
361
  throw e_1;
433
- case 8:
362
+ case 4:
434
363
  return [2];
435
364
  }
436
365
  });
@@ -665,21 +594,101 @@ function createBalanceIdentifier(caip, pubkey) {
665
594
  return `${caip}:${pubkey}`;
666
595
  }
667
596
 
597
+ // src/charts/custom-tokens.ts
598
+ var tag = "| charts-custom-tokens |";
599
+ async function fetchCustomTokens(params, balances) {
600
+ const { pioneer, pubkeys, blockchains, context } = params;
601
+ console.log(tag, "Fetching custom tokens...");
602
+ const evmPubkey = pubkeys.find((e) => e.networks && Array.isArray(e.networks) && e.networks.includes("eip155:*"));
603
+ const primaryAddress = evmPubkey?.address || evmPubkey?.master;
604
+ if (!primaryAddress) {
605
+ console.log(tag, "No EVM address found, skipping custom tokens");
606
+ return;
607
+ }
608
+ console.log(tag, "Using EVM address for custom tokens:", primaryAddress);
609
+ const supportedNetworks = blockchains.filter((net) => net.startsWith("eip155:"));
610
+ if (supportedNetworks.length === 0) {
611
+ console.log(tag, "No EVM networks for custom tokens");
612
+ return;
613
+ }
614
+ console.log(tag, `Checking custom tokens on ${supportedNetworks.length} networks`);
615
+ for (const networkId of supportedNetworks) {
616
+ try {
617
+ const response = await pioneer.GetCustomTokens({ networkId, address: primaryAddress });
618
+ const customTokens = response?.data?.tokens || [];
619
+ console.log(tag, `Found ${customTokens.length} custom tokens on ${networkId}`);
620
+ for (const token of customTokens) {
621
+ const chartBalance = processCustomToken(token, primaryAddress, context, blockchains);
622
+ if (chartBalance && !checkDuplicateBalance(balances, chartBalance.caip, chartBalance.pubkey)) {
623
+ balances.push(chartBalance);
624
+ console.log(tag, `Added custom token: ${chartBalance.symbol} = ${chartBalance.balance}`);
625
+ }
626
+ }
627
+ } catch (error) {
628
+ console.error(tag, `Error fetching custom tokens for ${networkId}:`, error.message);
629
+ }
630
+ }
631
+ console.log(tag, `Custom tokens complete. Total balances: ${balances.length}`);
632
+ }
633
+ function processCustomToken(token, primaryAddress, context, blockchains) {
634
+ if (!token.assetCaip || !token.networkId) {
635
+ return null;
636
+ }
637
+ let extractedNetworkId = token.networkId;
638
+ if (token.assetCaip.includes("/denom:")) {
639
+ const parts = token.assetCaip.split("/denom:");
640
+ if (parts.length > 0) {
641
+ extractedNetworkId = parts[0];
642
+ }
643
+ } else if (token.networkId && token.networkId.includes("/")) {
644
+ extractedNetworkId = token.networkId.split("/")[0];
645
+ }
646
+ const isEip155 = extractedNetworkId.startsWith("eip155:");
647
+ if (!isEip155 && !blockchains.includes(extractedNetworkId)) {
648
+ return null;
649
+ }
650
+ const tokenAssetInfo = hydrateAssetData(token.assetCaip);
651
+ const tokenPubkey = token.pubkey || primaryAddress;
652
+ const chartBalance = {
653
+ context,
654
+ chart: "pioneer",
655
+ contextType: context.split(":")[0],
656
+ name: tokenAssetInfo?.name || token.token?.name || "Unknown Custom Token",
657
+ caip: token.assetCaip,
658
+ icon: tokenAssetInfo?.icon || token.token?.icon || "",
659
+ pubkey: tokenPubkey,
660
+ ticker: tokenAssetInfo?.symbol || token.token?.symbol || "UNK",
661
+ ref: `${context}${token.assetCaip}`,
662
+ identifier: createBalanceIdentifier(token.assetCaip, tokenPubkey),
663
+ networkId: extractedNetworkId,
664
+ symbol: tokenAssetInfo?.symbol || token.token?.symbol || "UNK",
665
+ type: tokenAssetInfo?.type || "erc20",
666
+ token: true,
667
+ decimal: tokenAssetInfo?.decimal || token.token?.decimal,
668
+ balance: token.token?.balance?.toString() || "0",
669
+ priceUsd: token.token?.price || 0,
670
+ valueUsd: token.token?.balanceUSD || 0,
671
+ updated: new Date().getTime()
672
+ };
673
+ return chartBalance;
674
+ }
675
+
668
676
  // src/charts/evm.ts
669
- var tag = "| charts-evm |";
677
+ var tag2 = "| charts-evm |";
670
678
  async function getEvmCharts(params) {
671
679
  const { blockchains, pioneer, pubkeys, context } = params;
672
680
  const balances = [];
673
681
  const evmPubkey = pubkeys.find((e) => e.networks && Array.isArray(e.networks) && e.networks.includes("eip155:*"));
674
682
  const primaryAddress = evmPubkey?.address || evmPubkey?.master;
675
- console.log(tag, "Total pubkeys available:", pubkeys.length);
676
- console.log(tag, "Blockchains to process:", blockchains);
683
+ console.log(tag2, "Total pubkeys available:", pubkeys.length);
684
+ console.log(tag2, "Blockchains to process:", blockchains);
677
685
  if (!primaryAddress) {
678
- console.log(tag, "No EVM address found, skipping portfolio lookup (Zapper only supports Ethereum)");
686
+ console.log(tag2, "No EVM address found, skipping portfolio lookup (Zapper only supports Ethereum)");
679
687
  return balances;
680
688
  }
681
- console.log(tag, "Using EVM address for portfolio:", primaryAddress);
689
+ console.log(tag2, "Using EVM address for portfolio:", primaryAddress);
682
690
  await fetchStableCoins(pioneer, primaryAddress, blockchains, balances, context);
691
+ await fetchCustomTokens({ blockchains, pioneer, pubkeys, context }, balances);
683
692
  try {
684
693
  let portfolio = await pioneer.GetPortfolio({
685
694
  networkId: "eip155:1",
@@ -687,10 +696,10 @@ async function getEvmCharts(params) {
687
696
  });
688
697
  portfolio = portfolio.data?.data || portfolio.data;
689
698
  if (!portfolio || !portfolio.balances) {
690
- console.error(tag, "No portfolio.balances found:", portfolio);
699
+ console.error(tag2, "No portfolio.balances found:", portfolio);
691
700
  return balances;
692
701
  }
693
- console.log(tag, `Portfolio returned ${portfolio.balances.length} balances`);
702
+ console.log(tag2, `Portfolio returned ${portfolio.balances.length} balances`);
694
703
  let processedCount = 0;
695
704
  let skippedCount = 0;
696
705
  for (const balance of portfolio.balances) {
@@ -704,9 +713,9 @@ async function getEvmCharts(params) {
704
713
  skippedCount++;
705
714
  }
706
715
  }
707
- console.log(tag, `Processed ${processedCount} balances, skipped ${skippedCount}`);
716
+ console.log(tag2, `Processed ${processedCount} balances, skipped ${skippedCount}`);
708
717
  if (portfolio.tokens && portfolio.tokens.length > 0) {
709
- console.log(tag, "Processing portfolio.tokens:", portfolio.tokens.length);
718
+ console.log(tag2, "Processing portfolio.tokens:", portfolio.tokens.length);
710
719
  for (const token of portfolio.tokens) {
711
720
  const processedToken = processPortfolioToken(token, primaryAddress, context, blockchains);
712
721
  if (processedToken && !checkDuplicateBalance(balances, processedToken.caip, processedToken.pubkey)) {
@@ -715,13 +724,13 @@ async function getEvmCharts(params) {
715
724
  }
716
725
  }
717
726
  } catch (e) {
718
- console.error(tag, "Error fetching portfolio:", e);
727
+ console.error(tag2, "Error fetching portfolio:", e);
719
728
  }
720
729
  return balances;
721
730
  }
722
731
  function processPortfolioBalance(balance, primaryAddress, context, blockchains) {
723
732
  if (!balance.caip) {
724
- console.error(tag, "No caip found for:", balance);
733
+ console.error(tag2, "No caip found for:", balance);
725
734
  return null;
726
735
  }
727
736
  const networkId = balance.caip.split("/")[0];
@@ -739,7 +748,7 @@ function processPortfolioBalance(balance, primaryAddress, context, blockchains)
739
748
  const valueNum = parseFloat(balance.valueUsd.toString());
740
749
  if (balanceNum > 0 && valueNum > 0) {
741
750
  calculatedPrice = valueNum / balanceNum;
742
- console.log(tag, `Calculated price from value/balance: ${calculatedPrice} for ${balance.caip}`);
751
+ console.log(tag2, `Calculated price from value/balance: ${calculatedPrice} for ${balance.caip}`);
743
752
  }
744
753
  }
745
754
  const chartBalance = {
@@ -813,70 +822,70 @@ function processPortfolioToken(token, primaryAddress, context, blockchains) {
813
822
  return chartBalance;
814
823
  }
815
824
  async function fetchStableCoins(pioneer, primaryAddress, blockchains, balances, context) {
816
- console.log(tag, "Fetching stable coins for redundancy...");
825
+ console.log(tag2, "Fetching stable coins for redundancy...");
817
826
  const supportedNetworks = ["eip155:1", "eip155:137", "eip155:8453", "eip155:56"];
818
827
  const networksToCheck = blockchains.filter((net) => supportedNetworks.includes(net));
819
828
  if (networksToCheck.length === 0) {
820
- console.log(tag, "No supported networks for stable coins");
829
+ console.log(tag2, "No supported networks for stable coins");
821
830
  return;
822
831
  }
823
- console.log(tag, `Checking stable coins on ${networksToCheck.length} networks`);
832
+ console.log(tag2, `Checking stable coins on ${networksToCheck.length} networks`);
824
833
  for (const networkId of networksToCheck) {
825
834
  try {
826
835
  const response = await pioneer.GetStableCoins({ networkId, address: primaryAddress });
827
836
  const stableCoins = response?.data?.tokens || [];
828
- console.log(tag, `Found ${stableCoins.length} stable coins on ${networkId}`);
837
+ console.log(tag2, `Found ${stableCoins.length} stable coins on ${networkId}`);
829
838
  for (const token of stableCoins) {
830
839
  const chartBalance = processPortfolioToken(token, primaryAddress, context, blockchains);
831
840
  if (chartBalance && !checkDuplicateBalance(balances, chartBalance.caip, chartBalance.pubkey)) {
832
841
  balances.push(chartBalance);
833
- console.log(tag, `Added stable coin: ${chartBalance.symbol} = ${chartBalance.balance}`);
842
+ console.log(tag2, `Added stable coin: ${chartBalance.symbol} = ${chartBalance.balance}`);
834
843
  }
835
844
  }
836
845
  } catch (error) {
837
- console.error(tag, `Error fetching stable coins for ${networkId}:`, error.message);
846
+ console.error(tag2, `Error fetching stable coins for ${networkId}:`, error.message);
838
847
  }
839
848
  }
840
- console.log(tag, `Stable coin redundancy complete. Total balances: ${balances.length}`);
849
+ console.log(tag2, `Stable coin redundancy complete. Total balances: ${balances.length}`);
841
850
  }
842
851
 
843
852
  // src/charts/maya.ts
844
- var tag2 = "| charts-maya |";
853
+ var tag3 = "| charts-maya |";
845
854
  async function getMayaCharts(params, existingBalances) {
846
855
  const { blockchains, pioneer, pubkeys, context } = params;
847
856
  const balances = [];
848
857
  try {
849
858
  const mayaPubkey = pubkeys.find((p) => p.networks && Array.isArray(p.networks) && p.networks.includes("cosmos:mayachain-mainnet-v1"));
850
859
  if (!mayaPubkey || !mayaPubkey.address) {
851
- console.log(tag2, "No MAYA pubkey found, skipping MAYA token fetch");
860
+ console.log(tag3, "No MAYA pubkey found, skipping MAYA token fetch");
852
861
  return balances;
853
862
  }
854
863
  if (!blockchains.includes("cosmos:mayachain-mainnet-v1")) {
855
- console.log(tag2, "MAYA network not in blockchains list, skipping MAYA token fetch");
864
+ console.log(tag3, "MAYA network not in blockchains list, skipping MAYA token fetch");
856
865
  return balances;
857
866
  }
858
867
  const hasMayaToken = existingBalances.some((b) => b.caip === "cosmos:mayachain-mainnet-v1/denom:maya");
859
868
  if (hasMayaToken) {
860
- console.log(tag2, "MAYA token already exists in balances, skipping");
869
+ console.log(tag3, "MAYA token already exists in balances, skipping");
861
870
  return balances;
862
871
  }
863
- console.log(tag2, "MAYA token not found in portfolio, fetching separately...");
864
- console.log(tag2, "MAYA pubkey address:", mayaPubkey.address);
872
+ console.log(tag3, "MAYA token not found in portfolio, fetching separately...");
873
+ console.log(tag3, "MAYA pubkey address:", mayaPubkey.address);
865
874
  const mayaBalanceResponse = await pioneer.GetPortfolioBalances([
866
875
  {
867
876
  caip: "cosmos:mayachain-mainnet-v1/denom:maya",
868
877
  pubkey: mayaPubkey.address
869
878
  }
870
879
  ]);
871
- console.log(tag2, "MAYA balance response:", JSON.stringify(mayaBalanceResponse?.data, null, 2));
880
+ console.log(tag3, "MAYA balance response:", JSON.stringify(mayaBalanceResponse?.data, null, 2));
872
881
  if (!mayaBalanceResponse?.data || mayaBalanceResponse.data.length === 0) {
873
- console.log(tag2, "No MAYA token balance returned from GetPortfolioBalances API");
882
+ console.log(tag3, "No MAYA token balance returned from GetPortfolioBalances API");
874
883
  return balances;
875
884
  }
876
- console.log(tag2, "Found MAYA token balances:", mayaBalanceResponse.data.length);
885
+ console.log(tag3, "Found MAYA token balances:", mayaBalanceResponse.data.length);
877
886
  for (const mayaBalance of mayaBalanceResponse.data) {
878
887
  if (mayaBalance.caip !== "cosmos:mayachain-mainnet-v1/denom:maya") {
879
- console.log(tag2, "Unexpected balance in MAYA response:", mayaBalance);
888
+ console.log(tag3, "Unexpected balance in MAYA response:", mayaBalance);
880
889
  continue;
881
890
  }
882
891
  const mayaAssetInfo = hydrateAssetData(mayaBalance.caip);
@@ -902,28 +911,28 @@ async function getMayaCharts(params, existingBalances) {
902
911
  valueUsd: parseFloat(mayaBalance.valueUsd) || 0,
903
912
  updated: new Date().getTime()
904
913
  };
905
- console.log(tag2, "Adding MAYA token to balances:", mayaTokenBalance);
914
+ console.log(tag3, "Adding MAYA token to balances:", mayaTokenBalance);
906
915
  balances.push(mayaTokenBalance);
907
916
  }
908
917
  } catch (mayaError) {
909
- console.error(tag2, "Error fetching MAYA token balance:", mayaError);
918
+ console.error(tag3, "Error fetching MAYA token balance:", mayaError);
910
919
  }
911
920
  return balances;
912
921
  }
913
922
 
914
923
  // src/charts/cosmos-staking.ts
915
- var tag3 = "| charts-cosmos-staking |";
924
+ var tag4 = "| charts-cosmos-staking |";
916
925
  async function getCosmosStakingCharts(params) {
917
926
  const { blockchains, pioneer, pubkeys, context } = params;
918
927
  const balances = [];
919
928
  try {
920
- console.log(tag3, "Adding Cosmos staking positions to charts...");
929
+ console.log(tag4, "Adding Cosmos staking positions to charts...");
921
930
  const cosmosPubkeys = pubkeys.filter((p) => p.networks && Array.isArray(p.networks) && p.networks.some((n) => n.includes("cosmos:cosmoshub") || n.includes("cosmos:osmosis")));
922
931
  if (cosmosPubkeys.length === 0) {
923
- console.log(tag3, "No cosmos pubkeys found for staking positions");
932
+ console.log(tag4, "No cosmos pubkeys found for staking positions");
924
933
  return balances;
925
934
  }
926
- console.log(tag3, "Found cosmos pubkeys for staking:", cosmosPubkeys.length);
935
+ console.log(tag4, "Found cosmos pubkeys for staking:", cosmosPubkeys.length);
927
936
  for (const cosmosPubkey of cosmosPubkeys) {
928
937
  if (!cosmosPubkey.address) {
929
938
  continue;
@@ -937,20 +946,20 @@ async function getCosmosStakingCharts(params) {
937
946
  }
938
947
  }
939
948
  } catch (e) {
940
- console.error(tag3, "Error adding cosmos staking positions:", e);
949
+ console.error(tag4, "Error adding cosmos staking positions:", e);
941
950
  }
942
951
  return balances;
943
952
  }
944
953
  async function fetchStakingPositionsForNetwork(networkId, address, context, pioneer, balances) {
945
954
  try {
946
- console.log(tag3, `Fetching staking positions for ${address} on ${networkId}...`);
955
+ console.log(tag4, `Fetching staking positions for ${address} on ${networkId}...`);
947
956
  let network;
948
957
  if (networkId === "cosmos:cosmoshub-4") {
949
958
  network = "cosmos";
950
959
  } else if (networkId === "cosmos:osmosis-1") {
951
960
  network = "osmosis";
952
961
  } else {
953
- console.error(tag3, `Unsupported networkId for staking: ${networkId}`);
962
+ console.error(tag4, `Unsupported networkId for staking: ${networkId}`);
954
963
  return;
955
964
  }
956
965
  const stakingResponse = await pioneer.GetStakingPositions({
@@ -958,15 +967,15 @@ async function fetchStakingPositionsForNetwork(networkId, address, context, pion
958
967
  address
959
968
  });
960
969
  if (!stakingResponse?.data || !Array.isArray(stakingResponse.data)) {
961
- console.log(tag3, `No staking positions found for ${address} on ${networkId}`);
970
+ console.log(tag4, `No staking positions found for ${address} on ${networkId}`);
962
971
  return;
963
972
  }
964
- console.log(tag3, `Found ${stakingResponse.data.length} staking positions for ${networkId}`);
973
+ console.log(tag4, `Found ${stakingResponse.data.length} staking positions for ${networkId}`);
965
974
  for (const position of stakingResponse.data) {
966
975
  const processedPosition = processStakingPosition(position, address, context, networkId);
967
976
  if (processedPosition && !checkDuplicateBalance(balances, processedPosition.caip, processedPosition.pubkey, processedPosition.validator)) {
968
977
  balances.push(processedPosition);
969
- console.log(tag3, `Added ${position.type} position:`, {
978
+ console.log(tag4, `Added ${position.type} position:`, {
970
979
  balance: processedPosition.balance,
971
980
  ticker: processedPosition.ticker,
972
981
  valueUsd: processedPosition.valueUsd,
@@ -975,7 +984,7 @@ async function fetchStakingPositionsForNetwork(networkId, address, context, pion
975
984
  }
976
985
  }
977
986
  } catch (stakingError) {
978
- console.error(tag3, `Error fetching staking positions for ${address} on ${networkId}:`, stakingError);
987
+ console.error(tag4, `Error fetching staking positions for ${address} on ${networkId}:`, stakingError);
979
988
  }
980
989
  }
981
990
  function processStakingPosition(position, address, context, networkId) {
@@ -1010,11 +1019,11 @@ function processStakingPosition(position, address, context, networkId) {
1010
1019
  }
1011
1020
 
1012
1021
  // src/charts/index.ts
1013
- var tag4 = "| getCharts |";
1022
+ var tag5 = "| getCharts |";
1014
1023
  var getCharts = async (blockchains, pioneer, pubkeys, context) => {
1015
1024
  try {
1016
1025
  const balances = [];
1017
- console.log(tag4, "init");
1026
+ console.log(tag5, "init");
1018
1027
  const params = {
1019
1028
  blockchains,
1020
1029
  pioneer,
@@ -1029,7 +1038,7 @@ var getCharts = async (blockchains, pioneer, pubkeys, context) => {
1029
1038
  balances.push(...stakingBalances);
1030
1039
  return balances;
1031
1040
  } catch (error) {
1032
- console.error(tag4, "Error processing charts:", error);
1041
+ console.error(tag5, "Error processing charts:", error);
1033
1042
  throw error;
1034
1043
  }
1035
1044
  };
@@ -1807,7 +1816,7 @@ async function fetchTokenPriceInUsd(pioneer, caip) {
1807
1816
  }
1808
1817
  }
1809
1818
  async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pubkeyContext, isMax, feeLevel = 5) {
1810
- const tag5 = TAG + " | createUnsignedEvmTx | ";
1819
+ const tag6 = TAG + " | createUnsignedEvmTx | ";
1811
1820
  try {
1812
1821
  if (!pioneer)
1813
1822
  throw new Error("Failed to initialize Pioneer");
@@ -1828,11 +1837,11 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1828
1837
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
1829
1838
  }
1830
1839
  const address = pubkeyContext.address || pubkeyContext.pubkey;
1831
- console.log(tag5, "✅ Using FROM address from pubkeyContext:", address, "note:", pubkeyContext.note);
1840
+ console.log(tag6, "✅ Using FROM address from pubkeyContext:", address, "note:", pubkeyContext.note);
1832
1841
  if (!address)
1833
1842
  throw new Error("No address found for the specified network");
1834
1843
  const gasPriceData = await pioneer.GetGasPriceByNetwork({ networkId });
1835
- console.log(tag5, "Gas price data from API:", JSON.stringify(gasPriceData.data));
1844
+ console.log(tag6, "Gas price data from API:", JSON.stringify(gasPriceData.data));
1836
1845
  let gasPrice;
1837
1846
  const defaultGasPrices = {
1838
1847
  1: 30,
@@ -1848,75 +1857,75 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1848
1857
  let selectedGasPrice;
1849
1858
  if (feeLevel <= 2) {
1850
1859
  selectedGasPrice = gasPriceData.data.slow || gasPriceData.data.average || gasPriceData.data.fastest;
1851
- console.log(tag5, "Selecting SLOW gas price from API");
1860
+ console.log(tag6, "Selecting SLOW gas price from API");
1852
1861
  } else if (feeLevel >= 8) {
1853
1862
  selectedGasPrice = gasPriceData.data.fastest || gasPriceData.data.fast || gasPriceData.data.average;
1854
- console.log(tag5, "Selecting FAST gas price from API");
1863
+ console.log(tag6, "Selecting FAST gas price from API");
1855
1864
  } else {
1856
1865
  selectedGasPrice = gasPriceData.data.average || gasPriceData.data.fast || gasPriceData.data.fastest;
1857
- console.log(tag5, "Selecting AVERAGE gas price from API");
1866
+ console.log(tag6, "Selecting AVERAGE gas price from API");
1858
1867
  }
1859
1868
  let gasPriceNum;
1860
1869
  if (selectedGasPrice === undefined || selectedGasPrice === null) {
1861
- console.warn(tag5, "No valid gas price found in API response, using fallback:", fallbackGasGwei, "gwei");
1870
+ console.warn(tag6, "No valid gas price found in API response, using fallback:", fallbackGasGwei, "gwei");
1862
1871
  gasPriceNum = fallbackGasGwei;
1863
1872
  } else {
1864
1873
  gasPriceNum = typeof selectedGasPrice === "string" ? parseFloat(selectedGasPrice) : selectedGasPrice;
1865
1874
  if (isNaN(gasPriceNum) || !isFinite(gasPriceNum)) {
1866
- console.warn(tag5, "Invalid gas price (NaN or Infinite):", selectedGasPrice, "- using fallback:", fallbackGasGwei, "gwei");
1875
+ console.warn(tag6, "Invalid gas price (NaN or Infinite):", selectedGasPrice, "- using fallback:", fallbackGasGwei, "gwei");
1867
1876
  gasPriceNum = fallbackGasGwei;
1868
1877
  }
1869
1878
  }
1870
1879
  gasPrice = BigInt(Math.round(gasPriceNum * 1e9));
1871
1880
  if (gasPrice < MIN_GAS_PRICE_WEI) {
1872
- console.warn(tag5, "Gas price from API too low:", gasPrice.toString(), "wei - using minimum:", MIN_GAS_PRICE_WEI.toString());
1881
+ console.warn(tag6, "Gas price from API too low:", gasPrice.toString(), "wei - using minimum:", MIN_GAS_PRICE_WEI.toString());
1873
1882
  gasPrice = MIN_GAS_PRICE_WEI;
1874
1883
  }
1875
1884
  } else {
1876
1885
  let gasPriceNum;
1877
1886
  if (gasPriceData.data === undefined || gasPriceData.data === null) {
1878
- console.warn(tag5, "Gas price API returned null/undefined, using fallback:", fallbackGasGwei, "gwei");
1887
+ console.warn(tag6, "Gas price API returned null/undefined, using fallback:", fallbackGasGwei, "gwei");
1879
1888
  gasPriceNum = fallbackGasGwei;
1880
1889
  } else {
1881
1890
  gasPriceNum = typeof gasPriceData.data === "string" ? parseFloat(gasPriceData.data) : gasPriceData.data;
1882
1891
  if (isNaN(gasPriceNum) || !isFinite(gasPriceNum)) {
1883
- console.warn(tag5, "Invalid gas price (NaN or Infinite):", gasPriceData.data, "- using fallback:", fallbackGasGwei, "gwei");
1892
+ console.warn(tag6, "Invalid gas price (NaN or Infinite):", gasPriceData.data, "- using fallback:", fallbackGasGwei, "gwei");
1884
1893
  gasPriceNum = fallbackGasGwei;
1885
1894
  }
1886
1895
  }
1887
1896
  const baseGasPrice = BigInt(Math.round(gasPriceNum * 1e9));
1888
1897
  if (feeLevel <= 2) {
1889
1898
  gasPrice = baseGasPrice * BigInt(80) / BigInt(100);
1890
- console.log(tag5, "Using SLOW gas price (80% of base)");
1899
+ console.log(tag6, "Using SLOW gas price (80% of base)");
1891
1900
  } else if (feeLevel >= 8) {
1892
1901
  gasPrice = baseGasPrice * BigInt(150) / BigInt(100);
1893
- console.log(tag5, "Using FAST gas price (150% of base)");
1902
+ console.log(tag6, "Using FAST gas price (150% of base)");
1894
1903
  } else {
1895
1904
  gasPrice = baseGasPrice;
1896
- console.log(tag5, "Using AVERAGE gas price (100% of base)");
1905
+ console.log(tag6, "Using AVERAGE gas price (100% of base)");
1897
1906
  }
1898
1907
  if (gasPrice < MIN_GAS_PRICE_WEI) {
1899
- console.warn(tag5, "Gas price too low:", gasPrice.toString(), "wei - using minimum:", MIN_GAS_PRICE_WEI.toString());
1908
+ console.warn(tag6, "Gas price too low:", gasPrice.toString(), "wei - using minimum:", MIN_GAS_PRICE_WEI.toString());
1900
1909
  gasPrice = MIN_GAS_PRICE_WEI;
1901
1910
  }
1902
1911
  }
1903
- console.log(tag5, "Final gasPrice:", gasPrice.toString(), "wei (", Number(gasPrice) / 1e9, "gwei)");
1912
+ console.log(tag6, "Final gasPrice:", gasPrice.toString(), "wei (", Number(gasPrice) / 1e9, "gwei)");
1904
1913
  let nonce;
1905
1914
  try {
1906
1915
  const nonceData = await pioneer.GetNonceByNetwork({ networkId, address });
1907
1916
  nonce = nonceData.data.nonce;
1908
1917
  if (nonce === undefined || nonce === null) {
1909
- console.log(tag5, "No nonce found for address (likely fresh address), defaulting to 0");
1918
+ console.log(tag6, "No nonce found for address (likely fresh address), defaulting to 0");
1910
1919
  nonce = 0;
1911
1920
  }
1912
1921
  } catch (nonceError) {
1913
- console.log(tag5, "Failed to fetch nonce (likely fresh address):", nonceError.message, "- defaulting to 0");
1922
+ console.log(tag6, "Failed to fetch nonce (likely fresh address):", nonceError.message, "- defaulting to 0");
1914
1923
  nonce = 0;
1915
1924
  }
1916
1925
  const balanceData = await pioneer.GetBalanceAddressByNetwork({ networkId, address });
1917
1926
  const balanceEth = parseFloat(balanceData.data.nativeBalance || balanceData.data.balance || "0");
1918
1927
  const balance = BigInt(Math.round(balanceEth * 1000000000000000000));
1919
- console.log(tag5, "Native ETH balance from API:", balanceData.data.nativeBalance || balanceData.data.balance, "ETH (", balance.toString(), "wei)");
1928
+ console.log(tag6, "Native ETH balance from API:", balanceData.data.nativeBalance || balanceData.data.balance, "ETH (", balance.toString(), "wei)");
1920
1929
  if (balance <= 0n)
1921
1930
  throw new Error("Wallet balance is zero");
1922
1931
  const assetType = classifyCaipEvm(caip);
@@ -1929,7 +1938,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1929
1938
  let gasLimit;
1930
1939
  if (isThorchainOperation) {
1931
1940
  gasLimit = BigInt(120000);
1932
- console.log(tag5, "Using higher gas limit for THORChain swap:", gasLimit.toString());
1941
+ console.log(tag6, "Using higher gas limit for THORChain swap:", gasLimit.toString());
1933
1942
  } else {
1934
1943
  gasLimit = chainId === 1 ? BigInt(21000) : BigInt(25000);
1935
1944
  }
@@ -1945,7 +1954,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1945
1954
  }
1946
1955
  const buffer = BigInt(100);
1947
1956
  amountWei = balance - gasFee - buffer;
1948
- console.log(tag5, "isMax calculation - balance:", balance.toString(), "gasFee:", gasFee.toString(), "buffer:", buffer.toString(), "amountWei:", amountWei.toString());
1957
+ console.log(tag6, "isMax calculation - balance:", balance.toString(), "gasFee:", gasFee.toString(), "buffer:", buffer.toString(), "amountWei:", amountWei.toString());
1949
1958
  } else {
1950
1959
  amountWei = BigInt(Math.round(amount * 1000000000000000000));
1951
1960
  if (amountWei + gasFee > balance) {
@@ -1955,14 +1964,14 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1955
1964
  const isThorchainSwap = memo && (memo.startsWith("=") || memo.startsWith("SWAP") || memo.includes(":"));
1956
1965
  let txData = "0x";
1957
1966
  if (isThorchainSwap) {
1958
- console.log(tag5, "Detected THORChain swap, encoding deposit data for memo:", memo);
1967
+ console.log(tag6, "Detected THORChain swap, encoding deposit data for memo:", memo);
1959
1968
  let fixedMemo = memo;
1960
1969
  if (memo.startsWith("=:b:") || memo.startsWith("=:btc:")) {
1961
1970
  fixedMemo = memo.replace(/^=:(b|btc):/, "=:BTC.BTC:");
1962
- console.log(tag5, "Fixed Bitcoin swap memo from:", memo, "to:", fixedMemo);
1971
+ console.log(tag6, "Fixed Bitcoin swap memo from:", memo, "to:", fixedMemo);
1963
1972
  } else if (memo.startsWith("=:e:") || memo.startsWith("=:eth:")) {
1964
1973
  fixedMemo = memo.replace(/^=:(e|eth):/, "=:ETH.ETH:");
1965
- console.log(tag5, "Fixed Ethereum swap memo from:", memo, "to:", fixedMemo);
1974
+ console.log(tag6, "Fixed Ethereum swap memo from:", memo, "to:", fixedMemo);
1966
1975
  }
1967
1976
  if (fixedMemo.length > 250) {
1968
1977
  throw new Error(`Memo too long for THORChain: ${fixedMemo.length} bytes (max 250)`);
@@ -1978,14 +1987,14 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
1978
1987
  if (ethInbound) {
1979
1988
  vaultAddress = ethInbound.address;
1980
1989
  routerAddress = ethInbound.router || to;
1981
- console.log(tag5, "Using THORChain inbound addresses - vault:", vaultAddress, "router:", routerAddress);
1990
+ console.log(tag6, "Using THORChain inbound addresses - vault:", vaultAddress, "router:", routerAddress);
1982
1991
  to = routerAddress;
1983
1992
  } else {
1984
1993
  throw new Error("ETH inbound is halted or not found - cannot proceed with swap");
1985
1994
  }
1986
1995
  }
1987
1996
  } catch (fetchError) {
1988
- console.error(tag5, "Failed to fetch inbound addresses:", fetchError);
1997
+ console.error(tag6, "Failed to fetch inbound addresses:", fetchError);
1989
1998
  throw new Error(`Cannot proceed with THORChain swap - failed to fetch inbound addresses: ${fetchError.message}`);
1990
1999
  }
1991
2000
  if (vaultAddress === "0x0000000000000000000000000000000000000000") {
@@ -2005,7 +2014,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2005
2014
  const paddingLength = (32 - memoBytes.length % 32) % 32;
2006
2015
  const memoPadded = memoHex + "0".repeat(paddingLength * 2);
2007
2016
  txData = "0x" + functionSelector + vaultPadded + assetPadded + amountPadded + stringOffset + expiryPadded + stringLength + memoPadded;
2008
- console.log(tag5, "Encoded THORChain depositWithExpiry data:", {
2017
+ console.log(tag6, "Encoded THORChain depositWithExpiry data:", {
2009
2018
  functionSelector: "0x" + functionSelector,
2010
2019
  vault: vaultAddress,
2011
2020
  asset: assetAddress,
@@ -2015,9 +2024,9 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2015
2024
  stringOffset: "0x" + stringOffset,
2016
2025
  fullData: txData
2017
2026
  });
2018
- console.log(tag5, "Native ETH swap - value will be set to:", amountWei.toString(), "wei");
2027
+ console.log(tag6, "Native ETH swap - value will be set to:", amountWei.toString(), "wei");
2019
2028
  } catch (error) {
2020
- console.error(tag5, "Error encoding THORChain deposit:", error);
2029
+ console.error(tag6, "Error encoding THORChain deposit:", error);
2021
2030
  throw new Error(`Failed to encode THORChain swap: ${error.message}`);
2022
2031
  }
2023
2032
  } else if (memo) {
@@ -2036,19 +2045,19 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2036
2045
  }
2037
2046
  case "erc20": {
2038
2047
  const contractAddress = extractContractAddressFromCaip(caip);
2039
- console.log(tag5, "Fetching token decimals from contract:", contractAddress, "on network:", networkId);
2048
+ console.log(tag6, "Fetching token decimals from contract:", contractAddress, "on network:", networkId);
2040
2049
  let tokenDecimals;
2041
2050
  try {
2042
- console.log(tag5, "Fetching token decimals via pioneer-server API for", contractAddress, "on", networkId);
2051
+ console.log(tag6, "Fetching token decimals via pioneer-server API for", contractAddress, "on", networkId);
2043
2052
  const decimalsResponse = await pioneer.GetTokenDecimals({
2044
2053
  networkId,
2045
2054
  contractAddress
2046
2055
  });
2047
2056
  tokenDecimals = Number(decimalsResponse.data.decimals);
2048
- console.log(tag5, "✅ Fetched decimals from pioneer-server:", tokenDecimals);
2057
+ console.log(tag6, "✅ Fetched decimals from pioneer-server:", tokenDecimals);
2049
2058
  } catch (error) {
2050
- console.error(tag5, "Failed to fetch token decimals from pioneer-server:", error);
2051
- console.warn(tag5, "⚠️ FALLBACK: Using default 18 decimals - THIS MAY BE INCORRECT!");
2059
+ console.error(tag6, "Failed to fetch token decimals from pioneer-server:", error);
2060
+ console.warn(tag6, "⚠️ FALLBACK: Using default 18 decimals - THIS MAY BE INCORRECT!");
2052
2061
  tokenDecimals = 18;
2053
2062
  }
2054
2063
  const tokenMultiplier = 10n ** BigInt(tokenDecimals);
@@ -2069,7 +2078,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2069
2078
  amountWei = tokenBalance;
2070
2079
  } else {
2071
2080
  amountWei = BigInt(Math.round(amount * Number(tokenMultiplier)));
2072
- console.log(tag5, "Token amount calculation:", {
2081
+ console.log(tag6, "Token amount calculation:", {
2073
2082
  inputAmount: amount,
2074
2083
  decimals: tokenDecimals,
2075
2084
  multiplier: tokenMultiplier,
@@ -2105,23 +2114,23 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2105
2114
  }
2106
2115
  if (pubkeyContext.addressNListMaster) {
2107
2116
  unsignedTx.addressNList = pubkeyContext.addressNListMaster;
2108
- console.log(tag5, "✅ Using addressNListMaster from pubkey context:", unsignedTx.addressNList, "for address:", address);
2117
+ console.log(tag6, "✅ Using addressNListMaster from pubkey context:", unsignedTx.addressNList, "for address:", address);
2109
2118
  } else if (pubkeyContext.pathMaster) {
2110
2119
  unsignedTx.addressNList = import_pioneer_coins2.bip32ToAddressNList(pubkeyContext.pathMaster);
2111
- console.log(tag5, "✅ Converted pathMaster to addressNList:", pubkeyContext.pathMaster, "→", unsignedTx.addressNList);
2120
+ console.log(tag6, "✅ Converted pathMaster to addressNList:", pubkeyContext.pathMaster, "→", unsignedTx.addressNList);
2112
2121
  } else if (pubkeyContext.addressNList) {
2113
2122
  unsignedTx.addressNList = pubkeyContext.addressNList;
2114
- console.log(tag5, "✅ Using addressNList from pubkey context:", unsignedTx.addressNList);
2123
+ console.log(tag6, "✅ Using addressNList from pubkey context:", unsignedTx.addressNList);
2115
2124
  } else if (pubkeyContext.path) {
2116
2125
  unsignedTx.addressNList = import_pioneer_coins2.bip32ToAddressNList(pubkeyContext.path);
2117
- console.log(tag5, "⚠️ Using regular path (not master):", pubkeyContext.path, "→", unsignedTx.addressNList);
2126
+ console.log(tag6, "⚠️ Using regular path (not master):", pubkeyContext.path, "→", unsignedTx.addressNList);
2118
2127
  } else {
2119
2128
  unsignedTx.addressNList = [2147483648 + 44, 2147483648 + 60, 2147483648, 0, 0];
2120
- console.warn(tag5, "⚠️ No path info in pubkey context, using default account 0");
2129
+ console.warn(tag6, "⚠️ No path info in pubkey context, using default account 0");
2121
2130
  }
2122
2131
  return unsignedTx;
2123
2132
  } catch (error) {
2124
- console.error(tag5, "Error:", error.message);
2133
+ console.error(tag6, "Error:", error.message);
2125
2134
  throw error;
2126
2135
  }
2127
2136
  }
@@ -2130,7 +2139,7 @@ async function createUnsignedEvmTx(caip, to, amount, memo, pubkeys, pioneer, pub
2130
2139
  var import_pioneer_caip2 = require("@pioneer-platform/pioneer-caip");
2131
2140
  var TAG2 = " | createUnsignedUxtoTx | ";
2132
2141
  async function createUnsignedRippleTx(caip, to, amount, memo, pubkeys, pioneer, pubkeyContext, isMax) {
2133
- let tag5 = TAG2 + " | createUnsignedRippleTx | ";
2142
+ let tag6 = TAG2 + " | createUnsignedRippleTx | ";
2134
2143
  try {
2135
2144
  if (!pioneer)
2136
2145
  throw new Error("Failed to init! pioneer");
@@ -2141,7 +2150,7 @@ async function createUnsignedRippleTx(caip, to, amount, memo, pubkeys, pioneer,
2141
2150
  if (!pubkeyContext.networks?.includes(networkId)) {
2142
2151
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
2143
2152
  }
2144
- console.log(tag5, `✅ Using pubkeyContext for network ${networkId}:`, {
2153
+ console.log(tag6, `✅ Using pubkeyContext for network ${networkId}:`, {
2145
2154
  address: pubkeyContext.address
2146
2155
  });
2147
2156
  const fromAddress = pubkeyContext.address || pubkeyContext.pubkey;
@@ -2209,7 +2218,7 @@ async function createUnsignedRippleTx(caip, to, amount, memo, pubkeys, pioneer,
2209
2218
  };
2210
2219
  return unsignedTx;
2211
2220
  } catch (error) {
2212
- console.error(tag5, "Error:", error);
2221
+ console.error(tag6, "Error:", error);
2213
2222
  throw error;
2214
2223
  }
2215
2224
  }
@@ -2349,7 +2358,7 @@ var thorchainDepositTemplate = (params) => ({
2349
2358
  // src/txbuilder/createUnsignedTendermintTx.ts
2350
2359
  var TAG3 = " | createUnsignedTendermintTx | ";
2351
2360
  async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pioneer, pubkeyContext, isMax, to) {
2352
- const tag5 = TAG3 + " | createUnsignedTendermintTx | ";
2361
+ const tag6 = TAG3 + " | createUnsignedTendermintTx | ";
2353
2362
  try {
2354
2363
  if (!pioneer)
2355
2364
  throw new Error("Failed to init! pioneer");
@@ -2360,7 +2369,7 @@ async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pio
2360
2369
  if (!pubkeyContext.networks?.includes(networkId)) {
2361
2370
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
2362
2371
  }
2363
- console.log(tag5, `✅ Using pubkeyContext for network ${networkId}:`, {
2372
+ console.log(tag6, `✅ Using pubkeyContext for network ${networkId}:`, {
2364
2373
  address: pubkeyContext.address,
2365
2374
  addressNList: pubkeyContext.addressNList || pubkeyContext.addressNListMaster
2366
2375
  });
@@ -2383,11 +2392,11 @@ async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pio
2383
2392
  }
2384
2393
  const fromAddress = pubkeyContext.address || pubkeyContext.pubkey;
2385
2394
  let asset = caip.split(":")[1];
2386
- console.log(tag5, `\uD83D\uDD0D Fetching account info for address: ${fromAddress}`);
2395
+ console.log(tag6, `\uD83D\uDD0D Fetching account info for address: ${fromAddress}`);
2387
2396
  const accountInfo = (await pioneer.GetAccountInfo({ network: chain, address: fromAddress })).data;
2388
- console.log(tag5, "\uD83D\uDCCB accountInfo:", JSON.stringify(accountInfo, null, 2));
2397
+ console.log(tag6, "\uD83D\uDCCB accountInfo:", JSON.stringify(accountInfo, null, 2));
2389
2398
  let balanceInfo = await pioneer.GetPubkeyBalance({ asset: chain, pubkey: fromAddress });
2390
- console.log(tag5, `\uD83D\uDCB0 balanceInfo:`, balanceInfo);
2399
+ console.log(tag6, `\uD83D\uDCB0 balanceInfo:`, balanceInfo);
2391
2400
  let account_number, sequence;
2392
2401
  if (accountInfo.account) {
2393
2402
  account_number = accountInfo.account.account_number || "0";
@@ -2398,13 +2407,13 @@ async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pio
2398
2407
  } else {
2399
2408
  throw new Error(`Unexpected account info format for ${networkId}: ${JSON.stringify(accountInfo)}`);
2400
2409
  }
2401
- console.log(tag5, `\uD83D\uDCCA Extracted account_number: ${account_number}, sequence: ${sequence}`);
2410
+ console.log(tag6, `\uD83D\uDCCA Extracted account_number: ${account_number}, sequence: ${sequence}`);
2402
2411
  if (account_number === "0" || account_number === 0) {
2403
- console.log(tag5, `⚠️ WARNING: Account number is 0 from Pioneer API`);
2404
- console.log(tag5, ` This is likely due to stale Pioneer API cache`);
2405
- console.log(tag5, ` The mayachain-network module queries nodes directly but Pioneer API may be cached`);
2406
- console.log(tag5, ` Proceeding with account_number: 0 but transaction will likely fail`);
2407
- console.log(tag5, ` TODO: Fix Pioneer API to use fresh data from mayachain-network module`);
2412
+ console.log(tag6, `⚠️ WARNING: Account number is 0 from Pioneer API`);
2413
+ console.log(tag6, ` This is likely due to stale Pioneer API cache`);
2414
+ console.log(tag6, ` The mayachain-network module queries nodes directly but Pioneer API may be cached`);
2415
+ console.log(tag6, ` Proceeding with account_number: 0 but transaction will likely fail`);
2416
+ console.log(tag6, ` TODO: Fix Pioneer API to use fresh data from mayachain-network module`);
2408
2417
  }
2409
2418
  const fees = {
2410
2419
  "cosmos:thorchain-mainnet-v1": 0.02,
@@ -2559,7 +2568,7 @@ async function createUnsignedTendermintTx(caip, type, amount, memo, pubkeys, pio
2559
2568
  }
2560
2569
  }
2561
2570
  } catch (error) {
2562
- console.error(tag5, "Error:", error);
2571
+ console.error(tag6, "Error:", error);
2563
2572
  throw error;
2564
2573
  }
2565
2574
  }
@@ -2588,7 +2597,7 @@ function getCoinTypeFromNetworkId(networkId) {
2588
2597
  return coinType;
2589
2598
  }
2590
2599
  async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pubkeyContext, isMax, feeLevel = 5, changeScriptType) {
2591
- let tag5 = " | createUnsignedUxtoTx | ";
2600
+ let tag6 = " | createUnsignedUxtoTx | ";
2592
2601
  try {
2593
2602
  if (!pioneer)
2594
2603
  throw Error("Failed to init! pioneer");
@@ -2599,7 +2608,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2599
2608
  if (!pubkeyContext.networks?.includes(networkId)) {
2600
2609
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
2601
2610
  }
2602
- console.log(tag5, `✅ Using pubkeyContext for network ${networkId}:`, {
2611
+ console.log(tag6, `✅ Using pubkeyContext for network ${networkId}:`, {
2603
2612
  address: pubkeyContext.address,
2604
2613
  scriptType: pubkeyContext.scriptType
2605
2614
  });
@@ -2610,15 +2619,15 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2610
2619
  const isSegwit = segwitNetworks.includes(networkId);
2611
2620
  let chain = import_pioneer_caip4.NetworkIdToChain[networkId];
2612
2621
  const coinType = getCoinTypeFromNetworkId(networkId);
2613
- console.log(`${tag5}: Using SLIP-44 coin type ${coinType} for ${chain}`);
2622
+ console.log(`${tag6}: Using SLIP-44 coin type ${coinType} for ${chain}`);
2614
2623
  const utxos = [];
2615
2624
  for (const pubkey of relevantPubkeys) {
2616
2625
  try {
2617
2626
  let utxosResp = await pioneer.ListUnspent({ network: chain, xpub: pubkey.pubkey });
2618
2627
  utxosResp = utxosResp.data;
2619
- console.log(`${tag5}: ListUnspent response for ${pubkey.scriptType}:`, utxosResp?.length || 0, "UTXOs");
2628
+ console.log(`${tag6}: ListUnspent response for ${pubkey.scriptType}:`, utxosResp?.length || 0, "UTXOs");
2620
2629
  if (!utxosResp || !Array.isArray(utxosResp)) {
2621
- console.warn(`${tag5}: Invalid or empty UTXO response for ${pubkey.pubkey}`);
2630
+ console.warn(`${tag6}: Invalid or empty UTXO response for ${pubkey.pubkey}`);
2622
2631
  continue;
2623
2632
  }
2624
2633
  let scriptType = pubkey.scriptType;
@@ -2627,10 +2636,10 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2627
2636
  }
2628
2637
  utxos.push(...utxosResp);
2629
2638
  } catch (error) {
2630
- console.error(`${tag5}: Failed to fetch UTXOs for ${pubkey.pubkey}:`, error);
2639
+ console.error(`${tag6}: Failed to fetch UTXOs for ${pubkey.pubkey}:`, error);
2631
2640
  }
2632
2641
  }
2633
- console.log(`${tag5}: Total UTXOs collected:`, utxos.length);
2642
+ console.log(`${tag6}: Total UTXOs collected:`, utxos.length);
2634
2643
  if (!utxos || utxos.length === 0)
2635
2644
  throw Error("No UTXOs found across all addresses");
2636
2645
  for (const utxo of utxos) {
@@ -2643,14 +2652,14 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2643
2652
  }, {});
2644
2653
  const mostCommonInputType = Object.entries(scriptTypeCount).sort(([, a], [, b2]) => b2 - a)[0]?.[0] || "p2pkh";
2645
2654
  const actualChangeScriptType = changeScriptType || mostCommonInputType || relevantPubkeys[0]?.scriptType || "p2pkh";
2646
- console.log(`${tag5}: Input script types:`, scriptTypeCount);
2647
- console.log(`${tag5}: Using change script type: ${actualChangeScriptType} (matches inputs: ${mostCommonInputType})`);
2655
+ console.log(`${tag6}: Input script types:`, scriptTypeCount);
2656
+ console.log(`${tag6}: Using change script type: ${actualChangeScriptType} (matches inputs: ${mostCommonInputType})`);
2648
2657
  const changeXpubInfo = relevantPubkeys.find((pk) => pk.scriptType === actualChangeScriptType);
2649
2658
  if (!changeXpubInfo) {
2650
2659
  throw new Error(`No ${actualChangeScriptType} xpub available for change address. ` + `Available types: ${relevantPubkeys.map((pk) => pk.scriptType).join(", ")}. ` + `Cannot create change output with mismatched script type.`);
2651
2660
  }
2652
2661
  const changeXpub = changeXpubInfo.pubkey;
2653
- console.log(`${tag5}: Change xpub selected for ${actualChangeScriptType}:`, changeXpub?.substring(0, 10) + "...");
2662
+ console.log(`${tag6}: Change xpub selected for ${actualChangeScriptType}:`, changeXpub?.substring(0, 10) + "...");
2654
2663
  let changeAddressIndex = await pioneer.GetChangeAddress({
2655
2664
  network: chain,
2656
2665
  xpub: changeXpub
@@ -2670,7 +2679,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2670
2679
  break;
2671
2680
  }
2672
2681
  const path = bipPath;
2673
- console.log(`${tag5}: Change address path: ${path} (coin type: ${coinType}, index: ${changeAddressIndex})`);
2682
+ console.log(`${tag6}: Change address path: ${path} (coin type: ${coinType}, index: ${changeAddressIndex})`);
2674
2683
  const changeAddress = {
2675
2684
  path,
2676
2685
  isChange: true,
@@ -2680,7 +2689,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2680
2689
  };
2681
2690
  let feeRateFromNode;
2682
2691
  if (networkId === "bip122:00000000001a91e3dace36e2be3bf030") {
2683
- console.log(`${tag5}: Using hardcoded fees for DOGE (10 sat/byte)`);
2692
+ console.log(`${tag6}: Using hardcoded fees for DOGE (10 sat/byte)`);
2684
2693
  feeRateFromNode = {
2685
2694
  slow: 10,
2686
2695
  average: 10,
@@ -2693,19 +2702,19 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2693
2702
  try {
2694
2703
  let feeResponse;
2695
2704
  if (pioneer.GetFeeRateByNetwork) {
2696
- console.log(`${tag5}: Trying GetFeeRateByNetwork for ${networkId}`);
2705
+ console.log(`${tag6}: Trying GetFeeRateByNetwork for ${networkId}`);
2697
2706
  feeResponse = await pioneer.GetFeeRateByNetwork({ networkId });
2698
2707
  } else {
2699
- console.log(`${tag5}: Using GetFeeRate for ${networkId}`);
2708
+ console.log(`${tag6}: Using GetFeeRate for ${networkId}`);
2700
2709
  feeResponse = await pioneer.GetFeeRate({ networkId });
2701
2710
  }
2702
2711
  feeRateFromNode = feeResponse.data;
2703
- console.log(`${tag5}: Got fee rates from API:`, JSON.stringify(feeRateFromNode, null, 2));
2712
+ console.log(`${tag6}: Got fee rates from API:`, JSON.stringify(feeRateFromNode, null, 2));
2704
2713
  const conversionThreshold = 500;
2705
2714
  const needsConversion = feeRateFromNode.slow && feeRateFromNode.slow > conversionThreshold || feeRateFromNode.average && feeRateFromNode.average > conversionThreshold || feeRateFromNode.fast && feeRateFromNode.fast > conversionThreshold || feeRateFromNode.fastest && feeRateFromNode.fastest > conversionThreshold;
2706
2715
  if (needsConversion) {
2707
- console.warn(`${tag5}: Detected wrong units - values appear to be in sat/kB instead of sat/byte`);
2708
- console.warn(`${tag5}: Original values:`, {
2716
+ console.warn(`${tag6}: Detected wrong units - values appear to be in sat/kB instead of sat/byte`);
2717
+ console.warn(`${tag6}: Original values:`, {
2709
2718
  slow: feeRateFromNode.slow,
2710
2719
  average: feeRateFromNode.average,
2711
2720
  fast: feeRateFromNode.fast,
@@ -2719,12 +2728,12 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2719
2728
  feeRateFromNode.fast = feeRateFromNode.fast / 1000;
2720
2729
  if (feeRateFromNode.fastest)
2721
2730
  feeRateFromNode.fastest = feeRateFromNode.fastest / 1000;
2722
- console.warn(`${tag5}: Converted to sat/byte:`, feeRateFromNode);
2731
+ console.warn(`${tag6}: Converted to sat/byte:`, feeRateFromNode);
2723
2732
  }
2724
2733
  if (!feeRateFromNode || typeof feeRateFromNode !== "object") {
2725
2734
  throw new Error(`Invalid fee rate response from API: ${JSON.stringify(feeRateFromNode)}`);
2726
2735
  }
2727
- console.log(`${tag5}: Available fee rates:`, {
2736
+ console.log(`${tag6}: Available fee rates:`, {
2728
2737
  slow: feeRateFromNode.slow,
2729
2738
  average: feeRateFromNode.average,
2730
2739
  fast: feeRateFromNode.fast,
@@ -2734,33 +2743,33 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2734
2743
  throw new Error(`No valid fee rates in API response: ${JSON.stringify(feeRateFromNode)}`);
2735
2744
  }
2736
2745
  } catch (error) {
2737
- console.error(`${tag5}: Failed to get fee rates from Pioneer API:`, error.message || error);
2746
+ console.error(`${tag6}: Failed to get fee rates from Pioneer API:`, error.message || error);
2738
2747
  throw new Error(`Unable to get fee rate for network ${networkId}: ${error.message || "API unavailable"}`);
2739
2748
  }
2740
2749
  }
2741
2750
  let effectiveFeeRate;
2742
- console.log(`${tag5}: Using fee level ${feeLevel}`);
2751
+ console.log(`${tag6}: Using fee level ${feeLevel}`);
2743
2752
  switch (feeLevel) {
2744
2753
  case 1:
2745
2754
  case 2:
2746
2755
  effectiveFeeRate = feeRateFromNode.slow || feeRateFromNode.average;
2747
- console.log(`${tag5}: Using SLOW fee rate: ${effectiveFeeRate} sat/vB`);
2756
+ console.log(`${tag6}: Using SLOW fee rate: ${effectiveFeeRate} sat/vB`);
2748
2757
  break;
2749
2758
  case 3:
2750
2759
  case 4:
2751
2760
  effectiveFeeRate = feeRateFromNode.average || feeRateFromNode.fast;
2752
- console.log(`${tag5}: Using AVERAGE fee rate: ${effectiveFeeRate} sat/vB`);
2761
+ console.log(`${tag6}: Using AVERAGE fee rate: ${effectiveFeeRate} sat/vB`);
2753
2762
  break;
2754
2763
  case 5:
2755
2764
  effectiveFeeRate = feeRateFromNode.fastest || feeRateFromNode.fast;
2756
- console.log(`${tag5}: Using FASTEST fee rate: ${effectiveFeeRate} sat/vB`);
2765
+ console.log(`${tag6}: Using FASTEST fee rate: ${effectiveFeeRate} sat/vB`);
2757
2766
  break;
2758
2767
  default:
2759
2768
  throw new Error(`Invalid fee level: ${feeLevel}. Must be 1-5`);
2760
2769
  }
2761
2770
  if (!effectiveFeeRate)
2762
2771
  throw new Error("Unable to get fee rate for network");
2763
- console.log(`${tag5}: Using fee rate from API:`, {
2772
+ console.log(`${tag6}: Using fee rate from API:`, {
2764
2773
  feeLevel,
2765
2774
  selectedRate: effectiveFeeRate,
2766
2775
  description: feeLevel <= 2 ? "slow" : feeLevel <= 4 ? "average" : "fast"
@@ -2770,22 +2779,22 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2770
2779
  effectiveFeeRate = Math.ceil(effectiveFeeRate);
2771
2780
  const MIN_RELAY_FEE_RATE = 3;
2772
2781
  if (effectiveFeeRate < MIN_RELAY_FEE_RATE) {
2773
- console.log(`${tag5}: Fee rate ${effectiveFeeRate} is below minimum relay fee, increasing to ${MIN_RELAY_FEE_RATE} sat/vB`);
2782
+ console.log(`${tag6}: Fee rate ${effectiveFeeRate} is below minimum relay fee, increasing to ${MIN_RELAY_FEE_RATE} sat/vB`);
2774
2783
  effectiveFeeRate = MIN_RELAY_FEE_RATE;
2775
2784
  }
2776
- console.log(`${tag5}: Final fee rate to use (rounded, with minimums): ${effectiveFeeRate} sat/vB`);
2785
+ console.log(`${tag6}: Final fee rate to use (rounded, with minimums): ${effectiveFeeRate} sat/vB`);
2777
2786
  amount = parseInt(String(amount * 1e8));
2778
2787
  if (amount <= 0 && !isMax)
2779
2788
  throw Error("Invalid amount! 0");
2780
2789
  const totalBalance = utxos.reduce((sum, utxo) => sum + utxo.value, 0);
2781
- console.log(`${tag5}: Coin selection inputs:`, {
2790
+ console.log(`${tag6}: Coin selection inputs:`, {
2782
2791
  utxoCount: utxos.length,
2783
2792
  totalBalance: totalBalance / 1e8,
2784
2793
  requestedAmount: amount / 1e8,
2785
2794
  isMax,
2786
2795
  feeRate: effectiveFeeRate
2787
2796
  });
2788
- console.log(`${tag5}: UTXO details for coin selection:`, utxos.map((u) => ({
2797
+ console.log(`${tag6}: UTXO details for coin selection:`, utxos.map((u) => ({
2789
2798
  value: u.value,
2790
2799
  txid: u.txid?.substring(0, 10) + "...",
2791
2800
  vout: u.vout,
@@ -2799,8 +2808,8 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2799
2808
  } else {
2800
2809
  result = import_coinselect.default(utxos, [{ address: to, value: amount }], effectiveFeeRate);
2801
2810
  }
2802
- console.log(tag5, "coinSelect result object:", result);
2803
- console.log(tag5, "coinSelect result.inputs:", result?.inputs);
2811
+ console.log(tag6, "coinSelect result object:", result);
2812
+ console.log(tag6, "coinSelect result.inputs:", result?.inputs);
2804
2813
  if (!result || !result.inputs) {
2805
2814
  const errorDetails = {
2806
2815
  utxoCount: utxos.length,
@@ -2809,7 +2818,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2809
2818
  feeRate: effectiveFeeRate,
2810
2819
  insufficientFunds: totalBalance < amount
2811
2820
  };
2812
- console.error(`${tag5}: Coin selection failed:`, errorDetails);
2821
+ console.error(`${tag6}: Coin selection failed:`, errorDetails);
2813
2822
  if (utxos.length === 0) {
2814
2823
  throw Error("No UTXOs available for coin selection");
2815
2824
  } else if (totalBalance < amount) {
@@ -2825,7 +2834,7 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2825
2834
  throw Error("Failed to create transaction: Missing outputs");
2826
2835
  if (fee === undefined)
2827
2836
  throw Error("Failed to calculate transaction fee");
2828
- console.log(`${tag5}: Transaction built with:`, {
2837
+ console.log(`${tag6}: Transaction built with:`, {
2829
2838
  feeLevel,
2830
2839
  effectiveFeeRate: `${effectiveFeeRate} sat/vB`,
2831
2840
  calculatedFee: `${fee} satoshis`,
@@ -2833,8 +2842,8 @@ async function createUnsignedUxtoTx(caip, to, amount, memo, pubkeys, pioneer, pu
2833
2842
  outputCount: outputs.length
2834
2843
  });
2835
2844
  const uniqueInputSet = new Set;
2836
- console.log(tag5, "inputs:", inputs);
2837
- console.log(tag5, "inputs:", inputs[0]);
2845
+ console.log(tag6, "inputs:", inputs);
2846
+ console.log(tag6, "inputs:", inputs[0]);
2838
2847
  const preparedInputs = inputs.map(transformInput).filter(({ hash, index }) => uniqueInputSet.has(`${hash}:${index}`) ? false : uniqueInputSet.add(`${hash}:${index}`)).map(({ value, index, hash, txHex, path: path2, scriptType }) => ({
2839
2848
  addressNList: import_pioneer_coins3.bip32ToAddressNList(path2),
2840
2849
  scriptType,
@@ -2942,7 +2951,7 @@ class TransactionManager {
2942
2951
  throw new Error(`Unsupported CAIP: ${caip}`);
2943
2952
  }
2944
2953
  async transfer({ caip, to, amount, memo, isMax = false, feeLevel = 5, changeScriptType }) {
2945
- let tag5 = TAG4 + " | transfer | ";
2954
+ let tag6 = TAG4 + " | transfer | ";
2946
2955
  try {
2947
2956
  if (!this.pioneer)
2948
2957
  throw Error("Failed to init! pioneer");
@@ -2980,12 +2989,12 @@ class TransactionManager {
2980
2989
  }
2981
2990
  return unsignedTx;
2982
2991
  } catch (e) {
2983
- console.error(tag5, e);
2992
+ console.error(tag6, e);
2984
2993
  throw e;
2985
2994
  }
2986
2995
  }
2987
2996
  async sign({ caip, unsignedTx }) {
2988
- let tag5 = TAG4 + " | sign | ";
2997
+ let tag6 = TAG4 + " | sign | ";
2989
2998
  try {
2990
2999
  if (!this.pioneer)
2991
3000
  throw Error("Failed to init! pioneer");
@@ -3071,20 +3080,20 @@ class TransactionManager {
3071
3080
  }
3072
3081
  case "cosmos:mayachain-mainnet-v1/slip44:931":
3073
3082
  case "cosmos:mayachain-mainnet-v1/denom:maya": {
3074
- console.log(tag5, "\uD83D\uDD0D ===== MAYACHAIN SIGNING AUDIT =====");
3075
- console.log(tag5, "\uD83D\uDCCB unsignedTx:", JSON.stringify(unsignedTx, null, 2));
3076
- console.log(tag5, "\uD83D\uDD11 unsignedTx.addressNList:", unsignedTx.addressNList);
3077
- console.log(tag5, "\uD83D\uDCCD unsignedTx.signerAddress:", unsignedTx.signerAddress);
3078
- console.log(tag5, "\uD83C\uDF10 pubkeyContext:", this.pubkeyContext);
3079
- console.log(tag5, "\uD83D\uDD10 pubkeyContext.addressNList:", this.pubkeyContext?.addressNList);
3080
- console.log(tag5, "\uD83D\uDD10 pubkeyContext.addressNListMaster:", this.pubkeyContext?.addressNListMaster);
3081
- console.log(tag5, "\uD83D\uDCEC pubkeyContext.address:", this.pubkeyContext?.address);
3082
- console.log(tag5, "=======================================");
3083
+ console.log(tag6, "\uD83D\uDD0D ===== MAYACHAIN SIGNING AUDIT =====");
3084
+ console.log(tag6, "\uD83D\uDCCB unsignedTx:", JSON.stringify(unsignedTx, null, 2));
3085
+ console.log(tag6, "\uD83D\uDD11 unsignedTx.addressNList:", unsignedTx.addressNList);
3086
+ console.log(tag6, "\uD83D\uDCCD unsignedTx.signerAddress:", unsignedTx.signerAddress);
3087
+ console.log(tag6, "\uD83C\uDF10 pubkeyContext:", this.pubkeyContext);
3088
+ console.log(tag6, "\uD83D\uDD10 pubkeyContext.addressNList:", this.pubkeyContext?.addressNList);
3089
+ console.log(tag6, "\uD83D\uDD10 pubkeyContext.addressNListMaster:", this.pubkeyContext?.addressNListMaster);
3090
+ console.log(tag6, "\uD83D\uDCEC pubkeyContext.address:", this.pubkeyContext?.address);
3091
+ console.log(tag6, "=======================================");
3083
3092
  if (unsignedTx.signDoc.msgs[0].type === "mayachain/MsgSend") {
3084
3093
  const responseSign = await this.keepKeySdk.mayachain.mayachainSignAminoTransfer(unsignedTx);
3085
3094
  signedTx = responseSign.serialized;
3086
- console.log(tag5, "✅ Signing completed");
3087
- console.log(tag5, "\uD83D\uDCE6 responseSign:", responseSign);
3095
+ console.log(tag6, "✅ Signing completed");
3096
+ console.log(tag6, "\uD83D\uDCE6 responseSign:", responseSign);
3088
3097
  } else if (unsignedTx.signDoc.msgs[0].type === "mayachain/MsgDeposit") {
3089
3098
  const responseSign = await this.keepKeySdk.mayachain.mayachainSignAminoDeposit(unsignedTx);
3090
3099
  signedTx = responseSign.serialized;
@@ -3106,11 +3115,11 @@ class TransactionManager {
3106
3115
  if (serialized.length > 140) {
3107
3116
  signedTx = serialized;
3108
3117
  } else {
3109
- console.error(tag5, "EIP155 signing returned incomplete transaction - only signature components");
3118
+ console.error(tag6, "EIP155 signing returned incomplete transaction - only signature components");
3110
3119
  throw new Error("KeepKey returned incomplete transaction - cannot reconstruct without r,s,v components");
3111
3120
  }
3112
3121
  } else {
3113
- console.error(tag5, "EIP155 signing failed - no valid signature in response:", responseSign);
3122
+ console.error(tag6, "EIP155 signing failed - no valid signature in response:", responseSign);
3114
3123
  throw new Error("Failed to sign transaction - no valid signature in response");
3115
3124
  }
3116
3125
  break;
@@ -3131,19 +3140,19 @@ class TransactionManager {
3131
3140
  }
3132
3141
  }
3133
3142
  if (!signedTx) {
3134
- console.error(tag5, "CRITICAL ERROR: signedTx is missing after signing process");
3135
- console.error(tag5, "CAIP:", caip);
3136
- console.error(tag5, "Type:", type);
3143
+ console.error(tag6, "CRITICAL ERROR: signedTx is missing after signing process");
3144
+ console.error(tag6, "CAIP:", caip);
3145
+ console.error(tag6, "Type:", type);
3137
3146
  throw Error("Failed to sign! missing signedTx");
3138
3147
  }
3139
3148
  return signedTx;
3140
3149
  } catch (e) {
3141
- console.error(tag5, e);
3150
+ console.error(tag6, e);
3142
3151
  throw e;
3143
3152
  }
3144
3153
  }
3145
3154
  async broadcast({ networkId, serialized }) {
3146
- let tag5 = TAG4 + " | broadcast | ";
3155
+ let tag6 = TAG4 + " | broadcast | ";
3147
3156
  try {
3148
3157
  if (!this.pioneer)
3149
3158
  throw Error("Failed to init! pioneer");
@@ -3157,7 +3166,7 @@ class TransactionManager {
3157
3166
  return result.txid;
3158
3167
  }
3159
3168
  } catch (e) {
3160
- console.error(tag5, e);
3169
+ console.error(tag6, e);
3161
3170
  throw e;
3162
3171
  }
3163
3172
  }
@@ -3277,7 +3286,7 @@ var cosmosClaimAllRewardsTemplate = (params) => ({
3277
3286
  // src/txbuilder/createUnsignedStakingTx.ts
3278
3287
  var TAG5 = " | createUnsignedStakingTx | ";
3279
3288
  async function createUnsignedStakingTx(caip, params, pubkeys, pioneer, pubkeyContext) {
3280
- const tag5 = TAG5 + " | createUnsignedStakingTx | ";
3289
+ const tag6 = TAG5 + " | createUnsignedStakingTx | ";
3281
3290
  try {
3282
3291
  if (!pioneer)
3283
3292
  throw new Error("Failed to init! pioneer");
@@ -3288,7 +3297,7 @@ async function createUnsignedStakingTx(caip, params, pubkeys, pioneer, pubkeyCon
3288
3297
  if (!pubkeyContext.networks?.includes(networkId)) {
3289
3298
  throw new Error(`Pubkey context is for wrong network. Expected ${networkId}, got ${pubkeyContext.networks}`);
3290
3299
  }
3291
- console.log(tag5, `✅ Using pubkeyContext for network ${networkId}:`, {
3300
+ console.log(tag6, `✅ Using pubkeyContext for network ${networkId}:`, {
3292
3301
  address: pubkeyContext.address
3293
3302
  });
3294
3303
  let chain;
@@ -3320,10 +3329,10 @@ async function createUnsignedStakingTx(caip, params, pubkeys, pioneer, pubkeyCon
3320
3329
  default:
3321
3330
  throw new Error(`Unsupported networkId for staking: ${networkId}`);
3322
3331
  }
3323
- console.log(tag5, `Building ${params.type} transaction for ${chain}`);
3332
+ console.log(tag6, `Building ${params.type} transaction for ${chain}`);
3324
3333
  const fromAddress = pubkeyContext.address || pubkeyContext.pubkey;
3325
3334
  const accountInfo = (await pioneer.GetAccountInfo({ network: chain, address: fromAddress })).data;
3326
- console.log(tag5, "accountInfo: ", accountInfo);
3335
+ console.log(tag6, "accountInfo: ", accountInfo);
3327
3336
  let account_number;
3328
3337
  let sequence;
3329
3338
  if (networkId === "cosmos:cosmoshub-4" || networkId === "cosmos:osmosis-1") {
@@ -3405,7 +3414,7 @@ async function createUnsignedStakingTx(caip, params, pubkeys, pioneer, pubkeyCon
3405
3414
  throw new Error(`Unsupported staking transaction type: ${params.type}`);
3406
3415
  }
3407
3416
  } catch (error) {
3408
- console.error(tag5, "Error:", error);
3417
+ console.error(tag6, "Error:", error);
3409
3418
  throw error;
3410
3419
  }
3411
3420
  }
@@ -3451,16 +3460,16 @@ function withTimeout(promise, timeoutMs) {
3451
3460
  ]);
3452
3461
  }
3453
3462
  async function getFees(pioneer, networkId) {
3454
- const tag5 = TAG6 + " | getFees | ";
3463
+ const tag6 = TAG6 + " | getFees | ";
3455
3464
  try {
3456
- console.log(tag5, `Fetching fees for network: ${networkId}`);
3465
+ console.log(tag6, `Fetching fees for network: ${networkId}`);
3457
3466
  const networkType = getNetworkType(networkId);
3458
3467
  if (networkType === "COSMOS") {
3459
- console.log(tag5, "Using hardcoded fees for Cosmos network:", networkId);
3468
+ console.log(tag6, "Using hardcoded fees for Cosmos network:", networkId);
3460
3469
  return getCosmosFees(networkId);
3461
3470
  }
3462
3471
  if (networkId === "bip122:00000000001a91e3dace36e2be3bf030") {
3463
- console.log(tag5, "Using hardcoded fees for Dogecoin: 10 sat/byte");
3472
+ console.log(tag6, "Using hardcoded fees for Dogecoin: 10 sat/byte");
3464
3473
  return {
3465
3474
  slow: {
3466
3475
  label: "Slow",
@@ -3497,7 +3506,7 @@ async function getFees(pioneer, networkId) {
3497
3506
  const apiCall = pioneer.GetFeeRateByNetwork ? pioneer.GetFeeRateByNetwork({ networkId }) : pioneer.GetFeeRate({ networkId });
3498
3507
  feeResponse = await withTimeout(apiCall, 3000);
3499
3508
  } catch (timeoutError) {
3500
- console.warn(tag5, "Dash fee API timeout, using fallback fees");
3509
+ console.warn(tag6, "Dash fee API timeout, using fallback fees");
3501
3510
  return {
3502
3511
  slow: {
3503
3512
  label: "Economy",
@@ -3535,17 +3544,17 @@ async function getFees(pioneer, networkId) {
3535
3544
  throw new Error(`No fee data returned for ${networkId}`);
3536
3545
  }
3537
3546
  const feeData = feeResponse.data;
3538
- console.log(tag5, "Raw fee data:", feeData);
3547
+ console.log(tag6, "Raw fee data:", feeData);
3539
3548
  const networkName = getNetworkName(networkId);
3540
3549
  let normalizedFees = normalizeFeeData(feeData, networkType, networkName, networkId);
3541
3550
  normalizedFees = ensureFeeDifferentiation(normalizedFees, networkType);
3542
3551
  normalizedFees.networkId = networkId;
3543
3552
  normalizedFees.networkType = networkType;
3544
3553
  normalizedFees.raw = feeData;
3545
- console.log(tag5, "Normalized fees:", normalizedFees);
3554
+ console.log(tag6, "Normalized fees:", normalizedFees);
3546
3555
  return normalizedFees;
3547
3556
  } catch (error) {
3548
- console.error(tag5, "Failed to fetch fees:", error);
3557
+ console.error(tag6, "Failed to fetch fees:", error);
3549
3558
  return getFallbackFees(networkId);
3550
3559
  }
3551
3560
  }
@@ -3854,7 +3863,7 @@ function estimateTransactionFee(feeRate, unit, networkType, txSize) {
3854
3863
 
3855
3864
  // src/utils/kkapi-detection.ts
3856
3865
  async function detectKkApiAvailability(forceLocalhost) {
3857
- const tag5 = " | detectKkApiAvailability | ";
3866
+ const tag6 = " | detectKkApiAvailability | ";
3858
3867
  try {
3859
3868
  const isTauri = typeof window !== "undefined" && "__TAURI__" in window;
3860
3869
  const isBrowser = typeof window !== "undefined";
@@ -3982,6 +3991,11 @@ function buildDashboardFromBalances(balances, blockchains, assetsMap) {
3982
3991
  return sum + balanceNum;
3983
3992
  }, 0).toString();
3984
3993
  const assetInfo = nativeAssetCaip ? assetsMap.get(nativeAssetCaip) : null;
3994
+ console.log(TAG7, `[DEBUG] Network: ${blockchain}`);
3995
+ console.log(TAG7, `[DEBUG] nativeAssetCaip: ${nativeAssetCaip}`);
3996
+ console.log(TAG7, `[DEBUG] assetInfo:`, assetInfo);
3997
+ console.log(TAG7, `[DEBUG] gasAsset:`, gasAsset);
3998
+ console.log(TAG7, `[DEBUG] Resolved name: ${gasAsset?.name || assetInfo?.name || "NO NAME"}`);
3985
3999
  networksTemp.push({
3986
4000
  networkId: blockchain,
3987
4001
  totalValueUsd: networkTotal,
@@ -4007,11 +4021,11 @@ function buildDashboardFromBalances(balances, blockchains, assetsMap) {
4007
4021
  // src/utils/sync-market.ts
4008
4022
  var TAG8 = " | sync-market | ";
4009
4023
  async function syncMarket(balances, pioneer) {
4010
- const tag5 = `${TAG8} | syncMarket | `;
4024
+ const tag6 = `${TAG8} | syncMarket | `;
4011
4025
  try {
4012
4026
  const invalidBalances = balances.filter((b2) => !b2 || !b2.caip || typeof b2.caip !== "string" || !b2.caip.includes(":"));
4013
4027
  if (invalidBalances.length > 0) {
4014
- console.warn(tag5, `Found ${invalidBalances.length} balances with invalid CAIPs:`, invalidBalances.map((b2) => ({
4028
+ console.warn(tag6, `Found ${invalidBalances.length} balances with invalid CAIPs:`, invalidBalances.map((b2) => ({
4015
4029
  caip: b2?.caip,
4016
4030
  type: typeof b2?.caip,
4017
4031
  symbol: b2?.symbol,
@@ -4026,7 +4040,7 @@ async function syncMarket(balances, pioneer) {
4026
4040
  console.log("GetMarketInfo: payload length: ", allCaips.length);
4027
4041
  const invalidEntries = allCaips.filter((caip) => typeof caip !== "string");
4028
4042
  if (invalidEntries.length > 0) {
4029
- console.error(tag5, "CRITICAL: Invalid entries detected in allCaips:", invalidEntries);
4043
+ console.error(tag6, "CRITICAL: Invalid entries detected in allCaips:", invalidEntries);
4030
4044
  throw new Error("Invalid CAIP entries detected - aborting market sync");
4031
4045
  }
4032
4046
  if (allCaips && allCaips.length > 0) {
@@ -4047,13 +4061,13 @@ async function syncMarket(balances, pioneer) {
4047
4061
  }
4048
4062
  }
4049
4063
  } catch (apiError) {
4050
- console.error(tag5, "API error fetching market info:", apiError);
4051
- console.warn(tag5, "Continuing without market prices");
4064
+ console.error(tag6, "API error fetching market info:", apiError);
4065
+ console.warn(tag6, "Continuing without market prices");
4052
4066
  }
4053
4067
  }
4054
4068
  return true;
4055
4069
  } catch (e) {
4056
- console.error(tag5, "e:", e);
4070
+ console.error(tag6, "e:", e);
4057
4071
  throw e;
4058
4072
  }
4059
4073
  }
@@ -4160,12 +4174,6 @@ class SDK {
4160
4174
  this.blockchains = config.blockchains ? [...new Set(config.blockchains)] : [];
4161
4175
  if (config.blockchains && config.blockchains.length !== this.blockchains.length) {
4162
4176
  }
4163
- if (config.pubkeys && config.pubkeys.length > 0) {
4164
- this.setPubkeys(config.pubkeys);
4165
- } else {
4166
- this.pubkeys = [];
4167
- this.pubkeySet.clear();
4168
- }
4169
4177
  this.balances = config.balances || [];
4170
4178
  this.nodes = config.nodes || [];
4171
4179
  this.charts = ["covalent", "zapper"];
@@ -4223,7 +4231,7 @@ class SDK {
4223
4231
  return true;
4224
4232
  };
4225
4233
  this.setPubkeys = (newPubkeys) => {
4226
- const tag5 = `${TAG9} | setPubkeys | `;
4234
+ const tag6 = `${TAG9} | setPubkeys | `;
4227
4235
  this.pubkeys = [];
4228
4236
  this.pubkeySet.clear();
4229
4237
  let added = 0;
@@ -4233,8 +4241,14 @@ class SDK {
4233
4241
  }
4234
4242
  }
4235
4243
  };
4244
+ if (config.pubkeys && config.pubkeys.length > 0) {
4245
+ this.setPubkeys(config.pubkeys);
4246
+ } else {
4247
+ this.pubkeys = [];
4248
+ this.pubkeySet.clear();
4249
+ }
4236
4250
  this.getUnifiedPortfolio = async function() {
4237
- const tag5 = `${TAG9} | getUnifiedPortfolio | `;
4251
+ const tag6 = `${TAG9} | getUnifiedPortfolio | `;
4238
4252
  try {
4239
4253
  const startTime = performance.now();
4240
4254
  try {
@@ -4245,17 +4259,17 @@ class SDK {
4245
4259
  signal: AbortSignal.timeout(2000)
4246
4260
  });
4247
4261
  if (!portfolioResponse.ok) {
4248
- console.warn(tag5, "Portfolio endpoint returned", portfolioResponse.status);
4262
+ console.warn(tag6, "Portfolio endpoint returned", portfolioResponse.status);
4249
4263
  return null;
4250
4264
  }
4251
4265
  const portfolioData = await portfolioResponse.json();
4252
4266
  const loadTime = performance.now() - startTime;
4253
4267
  if (!portfolioData.success) {
4254
- console.warn(tag5, "Portfolio API returned success=false");
4268
+ console.warn(tag6, "Portfolio API returned success=false");
4255
4269
  return null;
4256
4270
  }
4257
4271
  if (portfolioData.totalValueUsd === 0 || !portfolioData.totalValueUsd) {
4258
- console.warn(tag5, "Portfolio value is $0.00 - may need device connection or sync");
4272
+ console.warn(tag6, "Portfolio value is $0.00 - may need device connection or sync");
4259
4273
  return null;
4260
4274
  }
4261
4275
  let allBalances = [];
@@ -4330,19 +4344,19 @@ class SDK {
4330
4344
  };
4331
4345
  } catch (fetchError) {
4332
4346
  if (fetchError.name === "AbortError") {
4333
- console.log(tag5, "Unified portfolio request timed out (this is normal if vault not running)");
4347
+ console.log(tag6, "Unified portfolio request timed out (this is normal if vault not running)");
4334
4348
  } else {
4335
- console.log(tag5, "Failed to fetch unified portfolio:", fetchError.message);
4349
+ console.log(tag6, "Failed to fetch unified portfolio:", fetchError.message);
4336
4350
  }
4337
4351
  return null;
4338
4352
  }
4339
4353
  } catch (e) {
4340
- console.error(tag5, "Error:", e);
4354
+ console.error(tag6, "Error:", e);
4341
4355
  return null;
4342
4356
  }
4343
4357
  };
4344
4358
  this.init = async function(walletsVerbose, setup) {
4345
- const tag5 = `${TAG9} | init | `;
4359
+ const tag6 = `${TAG9} | init | `;
4346
4360
  try {
4347
4361
  if (!this.username)
4348
4362
  throw Error("username required!");
@@ -4425,7 +4439,7 @@ class SDK {
4425
4439
  }
4426
4440
  return this.pioneer;
4427
4441
  } catch (e) {
4428
- console.error(tag5, "e: ", e);
4442
+ console.error(tag6, "e: ", e);
4429
4443
  throw e;
4430
4444
  }
4431
4445
  };
@@ -4436,7 +4450,7 @@ class SDK {
4436
4450
  return syncMarket(this.balances, this.pioneer);
4437
4451
  };
4438
4452
  this.sync = async function() {
4439
- const tag5 = `${TAG9} | sync | `;
4453
+ const tag6 = `${TAG9} | sync | `;
4440
4454
  try {
4441
4455
  const matchesNetwork = (item, networkId) => {
4442
4456
  if (!item.networks || !Array.isArray(item.networks))
@@ -4488,16 +4502,16 @@ class SDK {
4488
4502
  let totalPortfolioValue = 0;
4489
4503
  const networksTemp = [];
4490
4504
  const uniqueBlockchains = [...new Set(this.blockchains)];
4491
- console.log(tag5, "uniqueBlockchains: ", uniqueBlockchains);
4505
+ console.log(tag6, "uniqueBlockchains: ", uniqueBlockchains);
4492
4506
  for (const blockchain of uniqueBlockchains) {
4493
4507
  const filteredBalances = this.balances.filter((b2) => {
4494
4508
  const networkId = import_pioneer_caip7.caipToNetworkId(b2.caip);
4495
4509
  return networkId === blockchain || blockchain === "eip155:*" && networkId.startsWith("eip155:");
4496
4510
  });
4497
- console.log(tag5, `Filtering for blockchain: ${blockchain}`);
4498
- console.log(tag5, `Found ${filteredBalances.length} balances before deduplication`);
4511
+ console.log(tag6, `Filtering for blockchain: ${blockchain}`);
4512
+ console.log(tag6, `Found ${filteredBalances.length} balances before deduplication`);
4499
4513
  filteredBalances.forEach((balance, idx) => {
4500
- console.log(tag5, `Balance[${idx}]:`, {
4514
+ console.log(tag6, `Balance[${idx}]:`, {
4501
4515
  caip: balance.caip,
4502
4516
  pubkey: balance.pubkey,
4503
4517
  balance: balance.balance,
@@ -4507,7 +4521,7 @@ class SDK {
4507
4521
  const balanceMap = new Map;
4508
4522
  const isBitcoin = blockchain.includes("bip122:000000000019d6689c085ae165831e93");
4509
4523
  if (isBitcoin) {
4510
- console.log(tag5, "Bitcoin network detected - checking for duplicate balances");
4524
+ console.log(tag6, "Bitcoin network detected - checking for duplicate balances");
4511
4525
  const bitcoinByValue = new Map;
4512
4526
  filteredBalances.forEach((balance) => {
4513
4527
  const valueKey = `${balance.balance}_${balance.valueUsd}`;
@@ -4518,7 +4532,7 @@ class SDK {
4518
4532
  });
4519
4533
  for (const [valueKey, balances] of bitcoinByValue.entries()) {
4520
4534
  if (balances.length === 3 && parseFloat(balances[0].valueUsd || "0") > 0) {
4521
- console.log(tag5, "BITCOIN API BUG DETECTED: All 3 address types have same balance, keeping only xpub");
4535
+ console.log(tag6, "BITCOIN API BUG DETECTED: All 3 address types have same balance, keeping only xpub");
4522
4536
  const xpubBalance = balances.find((b2) => b2.pubkey?.startsWith("xpub")) || balances[0];
4523
4537
  const key = `${xpubBalance.caip}_${xpubBalance.pubkey || "default"}`;
4524
4538
  balanceMap.set(key, xpubBalance);
@@ -4538,13 +4552,13 @@ class SDK {
4538
4552
  });
4539
4553
  }
4540
4554
  const networkBalances = Array.from(balanceMap.values());
4541
- console.log(tag5, "networkBalances (deduplicated): ", networkBalances);
4542
- console.log(tag5, "networkBalances count: ", networkBalances.length);
4555
+ console.log(tag6, "networkBalances (deduplicated): ", networkBalances);
4556
+ console.log(tag6, "networkBalances count: ", networkBalances.length);
4543
4557
  const networkTotal = networkBalances.reduce((sum, balance, idx) => {
4544
4558
  const valueUsd = typeof balance.valueUsd === "string" ? parseFloat(balance.valueUsd) : balance.valueUsd || 0;
4545
- console.log(tag5, `[${idx}] valueUsd:`, balance.valueUsd, "→ parsed:", valueUsd, "| running sum:", sum + valueUsd);
4559
+ console.log(tag6, `[${idx}] valueUsd:`, balance.valueUsd, "→ parsed:", valueUsd, "| running sum:", sum + valueUsd);
4546
4560
  if (blockchain.includes("bip122:000000000019d6689c085ae165831e93")) {
4547
- console.log(tag5, `[BITCOIN DEBUG ${idx}] pubkey:`, balance.pubkey?.substring(0, 10) + "...", "| balance:", balance.balance, "| valueUsd:", balance.valueUsd, "→ parsed:", valueUsd);
4561
+ console.log(tag6, `[BITCOIN DEBUG ${idx}] pubkey:`, balance.pubkey?.substring(0, 10) + "...", "| balance:", balance.balance, "| valueUsd:", balance.valueUsd, "→ parsed:", valueUsd);
4548
4562
  }
4549
4563
  return sum + valueUsd;
4550
4564
  }, 0);
@@ -4575,7 +4589,7 @@ class SDK {
4575
4589
  this.dashboard = dashboardData;
4576
4590
  return true;
4577
4591
  } catch (e) {
4578
- console.error(tag5, "Error in sync:", e);
4592
+ console.error(tag6, "Error in sync:", e);
4579
4593
  throw e;
4580
4594
  }
4581
4595
  };
@@ -4589,7 +4603,7 @@ class SDK {
4589
4603
  }
4590
4604
  };
4591
4605
  this.buildTx = async function(sendPayload) {
4592
- let tag5 = TAG9 + " | buildTx | ";
4606
+ let tag6 = TAG9 + " | buildTx | ";
4593
4607
  try {
4594
4608
  const transactionDependencies = {
4595
4609
  context: this.context,
@@ -4603,7 +4617,7 @@ class SDK {
4603
4617
  };
4604
4618
  let txManager = new TransactionManager(transactionDependencies, this.events);
4605
4619
  let unsignedTx = await txManager.transfer(sendPayload);
4606
- console.log(tag5, "unsignedTx: ", unsignedTx);
4620
+ console.log(tag6, "unsignedTx: ", unsignedTx);
4607
4621
  return unsignedTx;
4608
4622
  } catch (e) {
4609
4623
  console.error(e);
@@ -4611,14 +4625,14 @@ class SDK {
4611
4625
  }
4612
4626
  };
4613
4627
  this.buildDelegateTx = async function(caip, params) {
4614
- let tag5 = TAG9 + " | buildDelegateTx | ";
4628
+ let tag6 = TAG9 + " | buildDelegateTx | ";
4615
4629
  try {
4616
4630
  const delegateParams = {
4617
4631
  ...params,
4618
4632
  type: "delegate"
4619
4633
  };
4620
4634
  let unsignedTx = await createUnsignedStakingTx(caip, delegateParams, this.pubkeys, this.pioneer, this.pubkeyContext);
4621
- console.log(tag5, "unsignedTx: ", unsignedTx);
4635
+ console.log(tag6, "unsignedTx: ", unsignedTx);
4622
4636
  return unsignedTx;
4623
4637
  } catch (e) {
4624
4638
  console.error(e);
@@ -4626,14 +4640,14 @@ class SDK {
4626
4640
  }
4627
4641
  };
4628
4642
  this.buildUndelegateTx = async function(caip, params) {
4629
- let tag5 = TAG9 + " | buildUndelegateTx | ";
4643
+ let tag6 = TAG9 + " | buildUndelegateTx | ";
4630
4644
  try {
4631
4645
  const undelegateParams = {
4632
4646
  ...params,
4633
4647
  type: "undelegate"
4634
4648
  };
4635
4649
  let unsignedTx = await createUnsignedStakingTx(caip, undelegateParams, this.pubkeys, this.pioneer, this.pubkeyContext);
4636
- console.log(tag5, "unsignedTx: ", unsignedTx);
4650
+ console.log(tag6, "unsignedTx: ", unsignedTx);
4637
4651
  return unsignedTx;
4638
4652
  } catch (e) {
4639
4653
  console.error(e);
@@ -4641,14 +4655,14 @@ class SDK {
4641
4655
  }
4642
4656
  };
4643
4657
  this.buildClaimRewardsTx = async function(caip, params) {
4644
- let tag5 = TAG9 + " | buildClaimRewardsTx | ";
4658
+ let tag6 = TAG9 + " | buildClaimRewardsTx | ";
4645
4659
  try {
4646
4660
  const claimParams = {
4647
4661
  ...params,
4648
4662
  type: "claim_rewards"
4649
4663
  };
4650
4664
  let unsignedTx = await createUnsignedStakingTx(caip, claimParams, this.pubkeys, this.pioneer, this.pubkeyContext);
4651
- console.log(tag5, "unsignedTx: ", unsignedTx);
4665
+ console.log(tag6, "unsignedTx: ", unsignedTx);
4652
4666
  return unsignedTx;
4653
4667
  } catch (e) {
4654
4668
  console.error(e);
@@ -4656,7 +4670,7 @@ class SDK {
4656
4670
  }
4657
4671
  };
4658
4672
  this.buildClaimAllRewardsTx = async function(caip, params) {
4659
- let tag5 = TAG9 + " | buildClaimAllRewardsTx | ";
4673
+ let tag6 = TAG9 + " | buildClaimAllRewardsTx | ";
4660
4674
  try {
4661
4675
  const claimAllParams = {
4662
4676
  ...params,
@@ -4669,8 +4683,8 @@ class SDK {
4669
4683
  throw e;
4670
4684
  }
4671
4685
  };
4672
- this.signTx = async function(unsignedTx) {
4673
- let tag5 = TAG9 + " | signTx | ";
4686
+ this.signTx = async function(caip, unsignedTx) {
4687
+ let tag6 = TAG9 + " | signTx | ";
4674
4688
  try {
4675
4689
  const transactionDependencies = {
4676
4690
  context: this.context,
@@ -4683,7 +4697,7 @@ class SDK {
4683
4697
  keepKeySdk: this.keepKeySdk
4684
4698
  };
4685
4699
  let txManager = new TransactionManager(transactionDependencies, this.events);
4686
- let signedTx = await txManager.sign(unsignedTx);
4700
+ let signedTx = await txManager.sign({ caip, unsignedTx });
4687
4701
  return signedTx;
4688
4702
  } catch (e) {
4689
4703
  console.error(e);
@@ -4691,7 +4705,7 @@ class SDK {
4691
4705
  }
4692
4706
  };
4693
4707
  this.broadcastTx = async function(caip, signedTx) {
4694
- let tag5 = TAG9 + " | broadcastTx | ";
4708
+ let tag6 = TAG9 + " | broadcastTx | ";
4695
4709
  try {
4696
4710
  const transactionDependencies = {
4697
4711
  context: this.context,
@@ -4715,7 +4729,7 @@ class SDK {
4715
4729
  }
4716
4730
  };
4717
4731
  this.swap = async function(swapPayload) {
4718
- let tag5 = `${TAG9} | swap | `;
4732
+ let tag6 = `${TAG9} | swap | `;
4719
4733
  try {
4720
4734
  if (!swapPayload)
4721
4735
  throw Error("swapPayload required!");
@@ -4764,15 +4778,15 @@ class SDK {
4764
4778
  throw new Error(`Cannot use max amount: no balance found for ${swapPayload.caipIn}`);
4765
4779
  }
4766
4780
  let totalBalance = 0;
4767
- console.log(tag5, `Found ${inputBalances.length} balance entries for ${swapPayload.caipIn}`);
4781
+ console.log(tag6, `Found ${inputBalances.length} balance entries for ${swapPayload.caipIn}`);
4768
4782
  for (const balanceEntry of inputBalances) {
4769
4783
  const balance = parseFloat(balanceEntry.balance) || 0;
4770
4784
  totalBalance += balance;
4771
- console.log(tag5, ` - ${balanceEntry.pubkey || balanceEntry.identifier}: ${balance}`);
4785
+ console.log(tag6, ` - ${balanceEntry.pubkey || balanceEntry.identifier}: ${balance}`);
4772
4786
  }
4773
4787
  this.assetContext.balance = totalBalance.toString();
4774
4788
  this.assetContext.valueUsd = (totalBalance * parseFloat(this.assetContext.priceUsd || "0")).toFixed(2);
4775
- console.log(tag5, `Updated assetContext balance to aggregated total: ${totalBalance}`);
4789
+ console.log(tag6, `Updated assetContext balance to aggregated total: ${totalBalance}`);
4776
4790
  const feeReserves = {
4777
4791
  "bip122:000000000019d6689c085ae165831e93/slip44:0": 0.00005,
4778
4792
  "eip155:1/slip44:60": 0.001,
@@ -4783,7 +4797,7 @@ class SDK {
4783
4797
  };
4784
4798
  const reserve = feeReserves[swapPayload.caipIn] || 0.0001;
4785
4799
  inputAmount = Math.max(0, totalBalance - reserve);
4786
- console.log(tag5, `Using max amount for swap: ${inputAmount} (total balance: ${totalBalance}, reserve: ${reserve})`);
4800
+ console.log(tag6, `Using max amount for swap: ${inputAmount} (total balance: ${totalBalance}, reserve: ${reserve})`);
4787
4801
  } else {
4788
4802
  inputAmount = typeof swapPayload.amount === "string" ? parseFloat(swapPayload.amount) : swapPayload.amount;
4789
4803
  if (isNaN(inputAmount) || inputAmount <= 0) {
@@ -4791,23 +4805,23 @@ class SDK {
4791
4805
  }
4792
4806
  }
4793
4807
  let quote = {
4794
- affiliate: "0x658DE0443259a1027caA976ef9a42E6982037A03",
4795
- sellAsset: this.assetContext,
4808
+ sellAsset: this.assetContext.caip,
4796
4809
  sellAmount: inputAmount.toPrecision(8),
4797
- buyAsset: this.outboundAssetContext,
4810
+ buyAsset: this.outboundAssetContext.caip,
4798
4811
  recipientAddress,
4799
4812
  senderAddress,
4800
- slippage: "3"
4813
+ slippage: swapPayload.slippagePercentage || 3
4801
4814
  };
4802
4815
  let result;
4803
4816
  try {
4804
4817
  result = await this.pioneer.Quote(quote);
4805
4818
  result = result.data;
4806
4819
  } catch (e) {
4807
- console.error(tag5, "Failed to get quote: ", e);
4820
+ console.error(tag6, "Failed to get quote: ", e);
4821
+ throw Error("Quote API failed for path: " + quote.sellAsset + " -> " + quote.buyAsset + ". Error: " + e);
4808
4822
  }
4809
- if (result.length === 0)
4810
- throw Error("No quotes available! path: " + quote.sellAsset.caip + " -> " + quote.buyAsset.caip);
4823
+ if (!result || result.length === 0)
4824
+ throw Error("No quotes available! path: " + quote.sellAsset + " -> " + quote.buyAsset);
4811
4825
  let selected = result[0];
4812
4826
  let txs = selected.quote.txs;
4813
4827
  if (!txs)
@@ -4820,6 +4834,7 @@ class SDK {
4820
4834
  balances: this.balances,
4821
4835
  pioneer: this.pioneer,
4822
4836
  pubkeys: this.pubkeys,
4837
+ pubkeyContext: this.pubkeyContext,
4823
4838
  nodes: this.nodes,
4824
4839
  keepKeySdk: this.keepKeySdk
4825
4840
  };
@@ -4827,7 +4842,10 @@ class SDK {
4827
4842
  let caip = swapPayload.caipIn;
4828
4843
  let unsignedTx;
4829
4844
  if (tx.type === "deposit") {
4830
- unsignedTx = await createUnsignedTendermintTx(caip, tx.type, tx.txParams.amount, tx.txParams.memo, this.pubkeys, this.pioneer, this.keepKeySdk, false, undefined);
4845
+ unsignedTx = await createUnsignedTendermintTx(caip, tx.type, tx.txParams.amount, tx.txParams.memo, this.pubkeys, this.pioneer, this.pubkeyContext, false, undefined);
4846
+ } else if (tx.type === "EVM" || tx.type === "evm") {
4847
+ console.log(tag6, "Using pre-built EVM transaction from integration");
4848
+ unsignedTx = tx.txParams;
4831
4849
  } else {
4832
4850
  if (!tx.txParams.memo)
4833
4851
  throw Error("memo required on swaps!");
@@ -4845,12 +4863,12 @@ class SDK {
4845
4863
  return unsignedTx;
4846
4864
  }
4847
4865
  } catch (e) {
4848
- console.error(tag5, "Error: ", e);
4866
+ console.error(tag6, "Error: ", e);
4849
4867
  throw e;
4850
4868
  }
4851
4869
  };
4852
4870
  this.transfer = async function(sendPayload) {
4853
- let tag5 = `${TAG9} | transfer | `;
4871
+ let tag6 = `${TAG9} | transfer | `;
4854
4872
  try {
4855
4873
  if (!sendPayload)
4856
4874
  throw Error("sendPayload required!");
@@ -4884,15 +4902,15 @@ class SDK {
4884
4902
  return { txid, events: this.events };
4885
4903
  } catch (error) {
4886
4904
  if (error instanceof Error) {
4887
- console.error(tag5, "An error occurred during the transfer process:", error.message);
4905
+ console.error(tag6, "An error occurred during the transfer process:", error.message);
4888
4906
  } else {
4889
- console.error(tag5, "An unknown error occurred during the transfer process");
4907
+ console.error(tag6, "An unknown error occurred during the transfer process");
4890
4908
  }
4891
4909
  throw error;
4892
4910
  }
4893
4911
  };
4894
4912
  this.followTransaction = async function(caip, txid) {
4895
- let tag5 = " | followTransaction | ";
4913
+ let tag6 = " | followTransaction | ";
4896
4914
  try {
4897
4915
  const finalConfirmationBlocksByCaip = {
4898
4916
  dogecoin: 3,
@@ -4922,7 +4940,7 @@ class SDK {
4922
4940
  }
4923
4941
  }
4924
4942
  } catch (error) {
4925
- console.error(tag5, "Error:", error);
4943
+ console.error(tag6, "Error:", error);
4926
4944
  }
4927
4945
  if (!isConfirmed) {
4928
4946
  await new Promise((resolve) => setTimeout(resolve, 8000));
@@ -4940,18 +4958,18 @@ class SDK {
4940
4958
  requiredConfirmations
4941
4959
  };
4942
4960
  } catch (error) {
4943
- console.error(tag5, "Error:", error);
4961
+ console.error(tag6, "Error:", error);
4944
4962
  throw new Error("Failed to follow transaction");
4945
4963
  }
4946
4964
  };
4947
4965
  this.setBlockchains = async function(blockchains) {
4948
- const tag5 = `${TAG9} | setBlockchains | `;
4966
+ const tag6 = `${TAG9} | setBlockchains | `;
4949
4967
  try {
4950
4968
  if (!blockchains)
4951
4969
  throw Error("blockchains required!");
4952
4970
  const uniqueBlockchains = [...new Set(blockchains)];
4953
4971
  if (blockchains.length !== uniqueBlockchains.length) {
4954
- console.warn(tag5, `Removed ${blockchains.length - uniqueBlockchains.length} duplicate blockchains`);
4972
+ console.warn(tag6, `Removed ${blockchains.length - uniqueBlockchains.length} duplicate blockchains`);
4955
4973
  }
4956
4974
  this.blockchains = uniqueBlockchains;
4957
4975
  this.events.emit("SET_BLOCKCHAINS", this.blockchains);
@@ -4961,7 +4979,7 @@ class SDK {
4961
4979
  }
4962
4980
  };
4963
4981
  this.addAsset = async function(caip, data) {
4964
- let tag5 = TAG9 + " | addAsset | ";
4982
+ let tag6 = TAG9 + " | addAsset | ";
4965
4983
  try {
4966
4984
  let success = false;
4967
4985
  if (!caip)
@@ -4999,22 +5017,22 @@ class SDK {
4999
5017
  }
5000
5018
  };
5001
5019
  this.clearWalletState = async function() {
5002
- const tag5 = `${TAG9} | clearWalletState | `;
5020
+ const tag6 = `${TAG9} | clearWalletState | `;
5003
5021
  try {
5004
5022
  this.context = null;
5005
5023
  this.paths = [];
5006
5024
  this.blockchains = [];
5007
5025
  this.pubkeys = [];
5008
5026
  this.pubkeySet.clear();
5009
- console.log(tag5, "Cleared wallet state including pubkeys and tracking set");
5027
+ console.log(tag6, "Cleared wallet state including pubkeys and tracking set");
5010
5028
  return true;
5011
5029
  } catch (e) {
5012
- console.error(tag5, "e: ", e);
5030
+ console.error(tag6, "e: ", e);
5013
5031
  throw e;
5014
5032
  }
5015
5033
  };
5016
5034
  this.addPath = async function(path) {
5017
- const tag5 = `${TAG9} | addPath | `;
5035
+ const tag6 = `${TAG9} | addPath | `;
5018
5036
  try {
5019
5037
  this.paths.push(path);
5020
5038
  const pubkey = await getPubkey(path.networks[0], path, this.keepKeySdk, this.context);
@@ -5023,14 +5041,14 @@ class SDK {
5023
5041
  this.buildDashboardFromBalances();
5024
5042
  return { success: true, pubkey };
5025
5043
  } catch (e) {
5026
- console.error(tag5, "Failed:", e);
5044
+ console.error(tag6, "Failed:", e);
5027
5045
  throw e;
5028
5046
  }
5029
5047
  };
5030
5048
  this.addPaths = async function(paths) {
5031
- const tag5 = `${TAG9} | addPaths | `;
5049
+ const tag6 = `${TAG9} | addPaths | `;
5032
5050
  try {
5033
- console.log(tag5, `Adding ${paths.length} paths in batch mode...`);
5051
+ console.log(tag6, `Adding ${paths.length} paths in batch mode...`);
5034
5052
  this.paths.push(...paths);
5035
5053
  const newPubkeys = [];
5036
5054
  for (const path of paths) {
@@ -5039,10 +5057,10 @@ class SDK {
5039
5057
  this.addPubkey(pubkey);
5040
5058
  newPubkeys.push(pubkey);
5041
5059
  } catch (error) {
5042
- console.warn(tag5, `Failed to get pubkey for path ${path.note}:`, error.message);
5060
+ console.warn(tag6, `Failed to get pubkey for path ${path.note}:`, error.message);
5043
5061
  }
5044
5062
  }
5045
- console.log(tag5, `Successfully added ${newPubkeys.length} pubkeys`);
5063
+ console.log(tag6, `Successfully added ${newPubkeys.length} pubkeys`);
5046
5064
  const networkSet = new Set;
5047
5065
  for (const path of paths) {
5048
5066
  if (path.networks && Array.isArray(path.networks)) {
@@ -5050,13 +5068,13 @@ class SDK {
5050
5068
  }
5051
5069
  }
5052
5070
  const uniqueNetworks = [...networkSet];
5053
- console.log(tag5, `Fetching balances for ${uniqueNetworks.length} unique networks in single API call...`);
5071
+ console.log(tag6, `Fetching balances for ${uniqueNetworks.length} unique networks in single API call...`);
5054
5072
  await this.getBalancesForNetworks(uniqueNetworks);
5055
5073
  this.buildDashboardFromBalances();
5056
- console.log(tag5, `Batch add complete: ${paths.length} paths, ${newPubkeys.length} pubkeys, ${this.balances?.length || 0} balances`);
5074
+ console.log(tag6, `Batch add complete: ${paths.length} paths, ${newPubkeys.length} pubkeys, ${this.balances?.length || 0} balances`);
5057
5075
  return { success: true, pubkeys: newPubkeys };
5058
5076
  } catch (e) {
5059
- console.error(tag5, "Failed:", e);
5077
+ console.error(tag6, "Failed:", e);
5060
5078
  throw e;
5061
5079
  }
5062
5080
  };
@@ -5064,7 +5082,7 @@ class SDK {
5064
5082
  return this.getGasAssets();
5065
5083
  };
5066
5084
  this.getGasAssets = async function() {
5067
- const tag5 = `${TAG9} | getGasAssets | `;
5085
+ const tag6 = `${TAG9} | getGasAssets | `;
5068
5086
  try {
5069
5087
  for (let i = 0;i < this.blockchains.length; i++) {
5070
5088
  let networkId = this.blockchains[i];
@@ -5098,7 +5116,7 @@ class SDK {
5098
5116
  denom: "maya"
5099
5117
  };
5100
5118
  this.assetsMap.set(mayaTokenCaip, mayaToken);
5101
- console.log(tag5, "Added MAYA token to assetsMap");
5119
+ console.log(tag6, "Added MAYA token to assetsMap");
5102
5120
  }
5103
5121
  return this.assetsMap;
5104
5122
  } catch (e) {
@@ -5107,7 +5125,7 @@ class SDK {
5107
5125
  }
5108
5126
  };
5109
5127
  this.getPubkeys = async function() {
5110
- const tag5 = `${TAG9} | getPubkeys | `;
5128
+ const tag6 = `${TAG9} | getPubkeys | `;
5111
5129
  try {
5112
5130
  if (this.paths.length === 0)
5113
5131
  throw new Error("No paths found!");
@@ -5123,15 +5141,15 @@ class SDK {
5123
5141
  return pubkeys;
5124
5142
  } catch (error) {
5125
5143
  console.error("Error in getPubkeys:", error);
5126
- console.error(tag5, "Error in getPubkeys:", error);
5144
+ console.error(tag6, "Error in getPubkeys:", error);
5127
5145
  throw error;
5128
5146
  }
5129
5147
  };
5130
5148
  this.getBalancesForNetworks = async function(networkIds) {
5131
- const tag5 = `${TAG9} | getBalancesForNetworks | `;
5149
+ const tag6 = `${TAG9} | getBalancesForNetworks | `;
5132
5150
  try {
5133
5151
  if (!this.pioneer) {
5134
- console.error(tag5, "ERROR: Pioneer client not initialized! this.pioneer is:", this.pioneer);
5152
+ console.error(tag6, "ERROR: Pioneer client not initialized! this.pioneer is:", this.pioneer);
5135
5153
  throw new Error("Pioneer client not initialized. Call init() first.");
5136
5154
  }
5137
5155
  const assetQuery = [];
@@ -5169,48 +5187,48 @@ class SDK {
5169
5187
  identifier: `${balance.caip}:${balance.pubkey}`
5170
5188
  });
5171
5189
  }
5172
- console.log(tag5, "balances: ", balances);
5190
+ console.log(tag6, "balances: ", balances);
5173
5191
  this.balances = balances;
5174
5192
  this.events.emit("SET_BALANCES", this.balances);
5175
5193
  return this.balances;
5176
5194
  } catch (apiError) {
5177
- console.error(tag5, "GetPortfolioBalances API call failed:", apiError);
5195
+ console.error(tag6, "GetPortfolioBalances API call failed:", apiError);
5178
5196
  throw new Error(`GetPortfolioBalances API call failed: ${apiError?.message || "Unknown error"}`);
5179
5197
  }
5180
5198
  } catch (e) {
5181
- console.error(tag5, "Error: ", e);
5199
+ console.error(tag6, "Error: ", e);
5182
5200
  throw e;
5183
5201
  }
5184
5202
  };
5185
5203
  this.getBalances = async function() {
5186
- const tag5 = `${TAG9} | getBalances | `;
5204
+ const tag6 = `${TAG9} | getBalances | `;
5187
5205
  try {
5188
5206
  return await this.getBalancesForNetworks(this.blockchains);
5189
5207
  } catch (e) {
5190
- console.error(tag5, "Error in getBalances: ", e);
5208
+ console.error(tag6, "Error in getBalances: ", e);
5191
5209
  throw e;
5192
5210
  }
5193
5211
  };
5194
5212
  this.getBalance = async function(networkId) {
5195
- const tag5 = `${TAG9} | getBalance | `;
5213
+ const tag6 = `${TAG9} | getBalance | `;
5196
5214
  try {
5197
5215
  const results = await this.getBalancesForNetworks([networkId]);
5198
5216
  const filtered = results.filter(async (b2) => b2.networkId === await import_pioneer_caip7.networkIdToCaip(networkId));
5199
5217
  return filtered;
5200
5218
  } catch (e) {
5201
- console.error(tag5, "Error: ", e);
5219
+ console.error(tag6, "Error: ", e);
5202
5220
  throw e;
5203
5221
  }
5204
5222
  };
5205
5223
  this.getFees = async function(networkId) {
5206
- const tag5 = `${TAG9} | getFees | `;
5224
+ const tag6 = `${TAG9} | getFees | `;
5207
5225
  try {
5208
5226
  if (!this.pioneer) {
5209
5227
  throw new Error("Pioneer client not initialized. Call init() first.");
5210
5228
  }
5211
5229
  return await getFees(this.pioneer, networkId);
5212
5230
  } catch (e) {
5213
- console.error(tag5, "Error getting fees: ", e);
5231
+ console.error(tag6, "Error getting fees: ", e);
5214
5232
  throw e;
5215
5233
  }
5216
5234
  };
@@ -5218,11 +5236,11 @@ class SDK {
5218
5236
  return estimateTransactionFee(feeRate, unit, networkType, txSize);
5219
5237
  };
5220
5238
  this.getCharts = async function() {
5221
- const tag5 = `${TAG9} | getCharts | `;
5239
+ const tag6 = `${TAG9} | getCharts | `;
5222
5240
  try {
5223
- console.log(tag5, "Fetching charts");
5241
+ console.log(tag6, "Fetching charts");
5224
5242
  const newBalances = await getCharts(this.blockchains, this.pioneer, this.pubkeys, this.context);
5225
- console.log(tag5, "newBalances: ", newBalances);
5243
+ console.log(tag6, "newBalances: ", newBalances);
5226
5244
  const uniqueBalances = new Map([...this.balances, ...newBalances].map((balance) => [
5227
5245
  balance.identifier,
5228
5246
  {
@@ -5230,17 +5248,17 @@ class SDK {
5230
5248
  type: balance.type || "balance"
5231
5249
  }
5232
5250
  ]));
5233
- console.log(tag5, "uniqueBalances: ", uniqueBalances);
5251
+ console.log(tag6, "uniqueBalances: ", uniqueBalances);
5234
5252
  this.balances = Array.from(uniqueBalances.values());
5235
- console.log(tag5, "Updated this.balances: ", this.balances);
5253
+ console.log(tag6, "Updated this.balances: ", this.balances);
5236
5254
  return this.balances;
5237
5255
  } catch (e) {
5238
- console.error(tag5, "Error in getCharts:", e);
5256
+ console.error(tag6, "Error in getCharts:", e);
5239
5257
  throw e;
5240
5258
  }
5241
5259
  };
5242
5260
  this.setContext = async (context) => {
5243
- const tag5 = `${TAG9} | setContext | `;
5261
+ const tag6 = `${TAG9} | setContext | `;
5244
5262
  try {
5245
5263
  if (!context)
5246
5264
  throw Error("context required!");
@@ -5248,12 +5266,12 @@ class SDK {
5248
5266
  this.events.emit("SET_CONTEXT", context);
5249
5267
  return { success: true };
5250
5268
  } catch (e) {
5251
- console.error(tag5, "e: ", e);
5269
+ console.error(tag6, "e: ", e);
5252
5270
  return { success: false };
5253
5271
  }
5254
5272
  };
5255
5273
  this.setContextType = async (contextType) => {
5256
- const tag5 = `${TAG9} | setContextType | `;
5274
+ const tag6 = `${TAG9} | setContextType | `;
5257
5275
  try {
5258
5276
  if (!contextType)
5259
5277
  throw Error("contextType required!");
@@ -5261,22 +5279,22 @@ class SDK {
5261
5279
  this.events.emit("SET_CONTEXT_TYPE", contextType);
5262
5280
  return { success: true };
5263
5281
  } catch (e) {
5264
- console.error(tag5, "e: ", e);
5282
+ console.error(tag6, "e: ", e);
5265
5283
  return { success: false };
5266
5284
  }
5267
5285
  };
5268
5286
  this.refresh = async () => {
5269
- const tag5 = `${TAG9} | refresh | `;
5287
+ const tag6 = `${TAG9} | refresh | `;
5270
5288
  try {
5271
5289
  await this.sync();
5272
5290
  return this.balances;
5273
5291
  } catch (e) {
5274
- console.error(tag5, "e: ", e);
5292
+ console.error(tag6, "e: ", e);
5275
5293
  throw e;
5276
5294
  }
5277
5295
  };
5278
5296
  this.setAssetContext = async function(asset) {
5279
- const tag5 = `${TAG9} | setAssetContext | `;
5297
+ const tag6 = `${TAG9} | setAssetContext | `;
5280
5298
  try {
5281
5299
  if (!asset) {
5282
5300
  this.assetContext = null;
@@ -5288,7 +5306,7 @@ class SDK {
5288
5306
  asset.networkId = import_pioneer_caip7.caipToNetworkId(asset.caip);
5289
5307
  if (!this.pubkeys || this.pubkeys.length === 0) {
5290
5308
  const errorMsg = `Cannot set asset context for ${asset.caip} - no pubkeys loaded. Please initialize wallet first.`;
5291
- console.error(tag5, errorMsg);
5309
+ console.error(tag6, errorMsg);
5292
5310
  throw new Error(errorMsg);
5293
5311
  }
5294
5312
  const pubkeysForNetwork = this.pubkeys.filter((e) => {
@@ -5303,8 +5321,8 @@ class SDK {
5303
5321
  });
5304
5322
  if (pubkeysForNetwork.length === 0) {
5305
5323
  const errorMsg = `Cannot set asset context for ${asset.caip} - no address/xpub found for network ${asset.networkId}`;
5306
- console.error(tag5, errorMsg);
5307
- console.error(tag5, "Available networks in pubkeys:", [
5324
+ console.error(tag6, errorMsg);
5325
+ console.error(tag6, "Available networks in pubkeys:", [
5308
5326
  ...new Set(this.pubkeys.flatMap((p2) => p2.networks || []))
5309
5327
  ]);
5310
5328
  throw new Error(errorMsg);
@@ -5314,43 +5332,43 @@ class SDK {
5314
5332
  const xpubFound = pubkeysForNetwork.some((p2) => p2.type === "xpub" && p2.pubkey);
5315
5333
  if (!xpubFound) {
5316
5334
  const errorMsg = `Cannot set asset context for UTXO chain ${asset.caip} - xpub required but not found`;
5317
- console.error(tag5, errorMsg);
5335
+ console.error(tag6, errorMsg);
5318
5336
  throw new Error(errorMsg);
5319
5337
  }
5320
5338
  }
5321
5339
  const hasValidAddress = pubkeysForNetwork.some((p2) => p2.address || p2.master || p2.pubkey);
5322
5340
  if (!hasValidAddress) {
5323
5341
  const errorMsg = `Cannot set asset context for ${asset.caip} - no valid address found in pubkeys`;
5324
- console.error(tag5, errorMsg);
5342
+ console.error(tag6, errorMsg);
5325
5343
  throw new Error(errorMsg);
5326
5344
  }
5327
- console.log(tag5, `✅ Validated: Found ${pubkeysForNetwork.length} addresses for ${asset.networkId}`);
5345
+ console.log(tag6, `✅ Validated: Found ${pubkeysForNetwork.length} addresses for ${asset.networkId}`);
5328
5346
  let freshPriceUsd = 0;
5329
5347
  try {
5330
5348
  if (!asset.caip || typeof asset.caip !== "string" || !asset.caip.includes(":")) {
5331
- console.warn(tag5, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
5349
+ console.warn(tag6, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
5332
5350
  } else {
5333
- console.log(tag5, "Fetching fresh market price for:", asset.caip);
5351
+ console.log(tag6, "Fetching fresh market price for:", asset.caip);
5334
5352
  const marketData = await this.pioneer.GetMarketInfo([asset.caip]);
5335
- console.log(tag5, "Market data response:", marketData);
5353
+ console.log(tag6, "Market data response:", marketData);
5336
5354
  if (marketData && marketData.data && marketData.data.length > 0) {
5337
5355
  freshPriceUsd = marketData.data[0];
5338
- console.log(tag5, "✅ Fresh market price:", freshPriceUsd);
5356
+ console.log(tag6, "✅ Fresh market price:", freshPriceUsd);
5339
5357
  } else {
5340
- console.warn(tag5, "No market data returned for:", asset.caip);
5358
+ console.warn(tag6, "No market data returned for:", asset.caip);
5341
5359
  }
5342
5360
  }
5343
5361
  } catch (marketError) {
5344
- console.error(tag5, "Error fetching market price:", marketError);
5362
+ console.error(tag6, "Error fetching market price:", marketError);
5345
5363
  }
5346
5364
  let assetInfo = this.assetsMap.get(asset.caip.toLowerCase());
5347
- console.log(tag5, "assetInfo: ", assetInfo);
5365
+ console.log(tag6, "assetInfo: ", assetInfo);
5348
5366
  let assetInfoDiscovery = import_pioneer_discovery2.assetData[asset.caip];
5349
- console.log(tag5, "assetInfoDiscovery: ", assetInfoDiscovery);
5367
+ console.log(tag6, "assetInfoDiscovery: ", assetInfoDiscovery);
5350
5368
  if (assetInfoDiscovery)
5351
5369
  assetInfo = assetInfoDiscovery;
5352
5370
  if (!assetInfo) {
5353
- console.log(tag5, "Building placeholder asset!");
5371
+ console.log(tag6, "Building placeholder asset!");
5354
5372
  assetInfo = {
5355
5373
  caip: asset.caip.toLowerCase(),
5356
5374
  networkId: asset.networkId,
@@ -5367,30 +5385,30 @@ class SDK {
5367
5385
  const valueUsd = parseFloat(matchingBalances[0].valueUsd);
5368
5386
  if (balance > 0 && valueUsd > 0) {
5369
5387
  priceValue = valueUsd / balance;
5370
- console.log(tag5, "calculated priceUsd from valueUsd/balance:", priceValue);
5388
+ console.log(tag6, "calculated priceUsd from valueUsd/balance:", priceValue);
5371
5389
  }
5372
5390
  }
5373
5391
  if (priceValue && priceValue > 0) {
5374
- console.log(tag5, "detected priceUsd from balance:", priceValue);
5392
+ console.log(tag6, "detected priceUsd from balance:", priceValue);
5375
5393
  assetInfo.priceUsd = priceValue;
5376
5394
  }
5377
5395
  }
5378
5396
  if (freshPriceUsd && freshPriceUsd > 0) {
5379
5397
  assetInfo.priceUsd = freshPriceUsd;
5380
- console.log(tag5, "✅ Using fresh market price:", freshPriceUsd);
5398
+ console.log(tag6, "✅ Using fresh market price:", freshPriceUsd);
5381
5399
  let totalBalance = 0;
5382
5400
  let totalValueUsd = 0;
5383
- console.log(tag5, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5401
+ console.log(tag6, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5384
5402
  for (const balanceEntry of matchingBalances) {
5385
5403
  const balance = parseFloat(balanceEntry.balance) || 0;
5386
5404
  const valueUsd = parseFloat(balanceEntry.valueUsd) || 0;
5387
5405
  totalBalance += balance;
5388
5406
  totalValueUsd += valueUsd;
5389
- console.log(tag5, ` Balance entry: ${balance} (${valueUsd} USD)`);
5407
+ console.log(tag6, ` Balance entry: ${balance} (${valueUsd} USD)`);
5390
5408
  }
5391
5409
  assetInfo.balance = totalBalance.toString();
5392
5410
  assetInfo.valueUsd = totalValueUsd.toFixed(2);
5393
- console.log(tag5, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5411
+ console.log(tag6, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5394
5412
  }
5395
5413
  const assetBalances = this.balances.filter((b2) => b2.caip === asset.caip);
5396
5414
  const assetPubkeys = this.pubkeys.filter((p2) => p2.networks && Array.isArray(p2.networks) && p2.networks.includes(import_pioneer_caip7.caipToNetworkId(asset.caip)) || import_pioneer_caip7.caipToNetworkId(asset.caip).includes("eip155") && p2.networks && Array.isArray(p2.networks) && p2.networks.some((n2) => n2.startsWith("eip155")));
@@ -5410,7 +5428,7 @@ class SDK {
5410
5428
  const balanceAmount = parseFloat(balance.balance || 0);
5411
5429
  balance.valueUsd = (balanceAmount * freshPriceUsd).toString();
5412
5430
  }
5413
- console.log(tag5, "Updated all balances with fresh price data");
5431
+ console.log(tag6, "Updated all balances with fresh price data");
5414
5432
  }
5415
5433
  this.assetContext = finalAssetContext;
5416
5434
  if (asset.isToken || asset.type === "token" || assetInfo.isToken || assetInfo.type === "token") {
@@ -5462,20 +5480,20 @@ class SDK {
5462
5480
  const currentContextValid = this.pubkeyContext?.networks?.includes(networkId);
5463
5481
  if (!this.pubkeyContext || !currentContextValid) {
5464
5482
  this.pubkeyContext = assetPubkeys[0];
5465
- console.log(tag5, "Auto-set pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey);
5483
+ console.log(tag6, "Auto-set pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey);
5466
5484
  } else {
5467
- console.log(tag5, "Preserving existing pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey, `(addressNList: [${(this.pubkeyContext.addressNList || this.pubkeyContext.addressNListMaster).join(", ")}])`);
5485
+ console.log(tag6, "Preserving existing pubkey context for network:", this.pubkeyContext.address || this.pubkeyContext.pubkey, `(addressNList: [${(this.pubkeyContext.addressNList || this.pubkeyContext.addressNListMaster).join(", ")}])`);
5468
5486
  }
5469
5487
  }
5470
5488
  this.events.emit("SET_ASSET_CONTEXT", this.assetContext);
5471
5489
  return this.assetContext;
5472
5490
  } catch (e) {
5473
- console.error(tag5, "e: ", e);
5491
+ console.error(tag6, "e: ", e);
5474
5492
  throw e;
5475
5493
  }
5476
5494
  };
5477
5495
  this.setPubkeyContext = async function(pubkey) {
5478
- let tag5 = `${TAG9} | setPubkeyContext | `;
5496
+ let tag6 = `${TAG9} | setPubkeyContext | `;
5479
5497
  try {
5480
5498
  if (!pubkey)
5481
5499
  throw Error("pubkey is required");
@@ -5483,31 +5501,31 @@ class SDK {
5483
5501
  throw Error("invalid pubkey: missing pubkey or address");
5484
5502
  const exists = this.pubkeys.some((pk) => pk.pubkey === pubkey.pubkey || pk.address === pubkey.address || pk.pubkey === pubkey.address);
5485
5503
  if (!exists) {
5486
- console.warn(tag5, "Pubkey not found in current pubkeys array");
5504
+ console.warn(tag6, "Pubkey not found in current pubkeys array");
5487
5505
  }
5488
5506
  this.pubkeyContext = pubkey;
5489
- console.log(tag5, "Pubkey context set to:", pubkey.address || pubkey.pubkey, "note:", pubkey.note, "addressNList:", pubkey.addressNList || pubkey.addressNListMaster);
5507
+ console.log(tag6, "Pubkey context set to:", pubkey.address || pubkey.pubkey, "note:", pubkey.note, "addressNList:", pubkey.addressNList || pubkey.addressNListMaster);
5490
5508
  return true;
5491
5509
  } catch (e) {
5492
- console.error(tag5, "e: ", e);
5510
+ console.error(tag6, "e: ", e);
5493
5511
  throw e;
5494
5512
  }
5495
5513
  };
5496
5514
  this.setOutboundAssetContext = async function(asset) {
5497
- const tag5 = `${TAG9} | setOutputAssetContext | `;
5515
+ const tag6 = `${TAG9} | setOutputAssetContext | `;
5498
5516
  try {
5499
- console.log(tag5, "0. asset: ", asset);
5517
+ console.log(tag6, "0. asset: ", asset);
5500
5518
  if (!asset) {
5501
5519
  this.outboundAssetContext = null;
5502
5520
  return;
5503
5521
  }
5504
- console.log(tag5, "1 asset: ", asset);
5522
+ console.log(tag6, "1 asset: ", asset);
5505
5523
  if (!asset.caip)
5506
5524
  throw Error("Invalid Asset! missing caip!");
5507
5525
  if (!asset.networkId)
5508
5526
  asset.networkId = import_pioneer_caip7.caipToNetworkId(asset.caip);
5509
- console.log(tag5, "networkId: ", asset.networkId);
5510
- console.log(tag5, "this.pubkeys: ", this.pubkeys);
5527
+ console.log(tag6, "networkId: ", asset.networkId);
5528
+ console.log(tag6, "this.pubkeys: ", this.pubkeys);
5511
5529
  const pubkey = this.pubkeys.find((p2) => {
5512
5530
  if (!p2.networks || !Array.isArray(p2.networks))
5513
5531
  return false;
@@ -5522,23 +5540,23 @@ class SDK {
5522
5540
  let freshPriceUsd = 0;
5523
5541
  try {
5524
5542
  if (!asset.caip || typeof asset.caip !== "string" || !asset.caip.includes(":")) {
5525
- console.warn(tag5, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
5543
+ console.warn(tag6, "Invalid or missing CAIP, skipping market price fetch:", asset.caip);
5526
5544
  } else {
5527
- console.log(tag5, "Fetching fresh market price for:", asset.caip);
5545
+ console.log(tag6, "Fetching fresh market price for:", asset.caip);
5528
5546
  const marketData = await this.pioneer.GetMarketInfo([asset.caip]);
5529
- console.log(tag5, "Market data response:", marketData);
5547
+ console.log(tag6, "Market data response:", marketData);
5530
5548
  if (marketData && marketData.data && marketData.data.length > 0) {
5531
5549
  freshPriceUsd = marketData.data[0];
5532
- console.log(tag5, "✅ Fresh market price:", freshPriceUsd);
5550
+ console.log(tag6, "✅ Fresh market price:", freshPriceUsd);
5533
5551
  } else {
5534
- console.warn(tag5, "No market data returned for:", asset.caip);
5552
+ console.warn(tag6, "No market data returned for:", asset.caip);
5535
5553
  }
5536
5554
  }
5537
5555
  } catch (marketError) {
5538
- console.error(tag5, "Error fetching market price:", marketError);
5556
+ console.error(tag6, "Error fetching market price:", marketError);
5539
5557
  }
5540
5558
  let assetInfo = this.assetsMap.get(asset.caip.toLowerCase());
5541
- console.log(tag5, "assetInfo: ", assetInfo);
5559
+ console.log(tag6, "assetInfo: ", assetInfo);
5542
5560
  if (!assetInfo) {
5543
5561
  assetInfo = {
5544
5562
  caip: asset.caip.toLowerCase(),
@@ -5556,45 +5574,45 @@ class SDK {
5556
5574
  const valueUsd = parseFloat(matchingBalances[0].valueUsd);
5557
5575
  if (balance > 0 && valueUsd > 0) {
5558
5576
  priceValue = valueUsd / balance;
5559
- console.log(tag5, "calculated priceUsd from valueUsd/balance:", priceValue);
5577
+ console.log(tag6, "calculated priceUsd from valueUsd/balance:", priceValue);
5560
5578
  }
5561
5579
  }
5562
5580
  if (priceValue && priceValue > 0) {
5563
- console.log(tag5, "detected priceUsd from balance:", priceValue);
5581
+ console.log(tag6, "detected priceUsd from balance:", priceValue);
5564
5582
  assetInfo.priceUsd = priceValue;
5565
5583
  }
5566
5584
  }
5567
5585
  if (freshPriceUsd && freshPriceUsd > 0) {
5568
5586
  assetInfo.priceUsd = freshPriceUsd;
5569
- console.log(tag5, "✅ Using fresh market price:", freshPriceUsd);
5587
+ console.log(tag6, "✅ Using fresh market price:", freshPriceUsd);
5570
5588
  let totalBalance = 0;
5571
5589
  let totalValueUsd = 0;
5572
- console.log(tag5, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5590
+ console.log(tag6, `Found ${matchingBalances.length} balance entries for ${asset.caip}`);
5573
5591
  for (const balanceEntry of matchingBalances) {
5574
5592
  const balance = parseFloat(balanceEntry.balance) || 0;
5575
5593
  const valueUsd = parseFloat(balanceEntry.valueUsd) || 0;
5576
5594
  totalBalance += balance;
5577
5595
  totalValueUsd += valueUsd;
5578
- console.log(tag5, ` Balance entry: ${balance} (${valueUsd} USD)`);
5596
+ console.log(tag6, ` Balance entry: ${balance} (${valueUsd} USD)`);
5579
5597
  }
5580
5598
  assetInfo.balance = totalBalance.toString();
5581
5599
  assetInfo.valueUsd = totalValueUsd.toFixed(2);
5582
- console.log(tag5, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5600
+ console.log(tag6, `Aggregated balance: ${totalBalance} (${totalValueUsd.toFixed(2)} USD)`);
5583
5601
  }
5584
- console.log(tag5, "CHECKPOINT 1");
5602
+ console.log(tag6, "CHECKPOINT 1");
5585
5603
  this.outboundAssetContext = { ...assetInfo, ...asset, ...pubkey };
5586
- console.log(tag5, "CHECKPOINT 3");
5587
- console.log(tag5, "outboundAssetContext: assetInfo: ", assetInfo);
5604
+ console.log(tag6, "CHECKPOINT 3");
5605
+ console.log(tag6, "outboundAssetContext: assetInfo: ", assetInfo);
5588
5606
  if (asset.caip) {
5589
5607
  this.outboundBlockchainContext = import_pioneer_caip7.caipToNetworkId(asset.caip);
5590
5608
  } else if (asset.networkId) {
5591
5609
  this.outboundBlockchainContext = asset.networkId;
5592
5610
  }
5593
- console.log(tag5, "CHECKPOINT 4");
5611
+ console.log(tag6, "CHECKPOINT 4");
5594
5612
  this.events.emit("SET_OUTBOUND_ASSET_CONTEXT", this.outboundAssetContext);
5595
5613
  return this.outboundAssetContext;
5596
5614
  } catch (e) {
5597
- console.error(tag5, "e: ", e);
5615
+ console.error(tag6, "e: ", e);
5598
5616
  throw e;
5599
5617
  }
5600
5618
  };